diff --git a/.continue/rules/dev-data-guide.md b/.continue/rules/dev-data-guide.md new file mode 100644 index 000000000..7321b93c0 --- /dev/null +++ b/.continue/rules/dev-data-guide.md @@ -0,0 +1,200 @@ +--- +alwaysApply: false +--- + +# Continue Development Data (Dev Data) Guide + +## Overview + +Development data (dev data) captures detailed information about how developers interact with LLM-aided development tools. Unlike basic telemetry, dev data includes lots of details into the complete software development workflow, including code context, user interactions, and development patterns. + +## Core Architecture + +### Primary Implementation Files + +- **`/core/data/log.ts`**: Main `DataLogger` class - singleton for event logging and remote transmission +- **`/packages/config-yaml/src/schemas/data/`**: Schema definitions for all event types + +### Storage Locations + +- **Default storage**: `~/.continue/dev_data/` +- **Event files**: `~/.continue/dev_data/{version}/{eventName}.jsonl` + +## Event Types and Schemas + +### Core Event Types + +1. **`tokensGenerated`**: LLM token usage tracking +2. **`autocomplete`**: Code completion interactions +3. **`chatInteraction`**: Chat-based development assistance +4. **`editInteraction`**: Code editing sessions +5. **`editOutcome`**: Results of edit operations +6. **`nextEditOutcome`**: Next Edit feature outcomes +7. **`chatFeedback`**: User feedback on AI responses +8. **`toolUsage`**: Tool interaction statistics +9. **`quickEdit`**: Quick edit functionality usage + +### Schema Versioning + +- **Version 0.1.0**: Initial schema implementation +- **Version 0.2.0**: Current schema with expanded fields and metadata +- **Schema files**: Located in `/packages/config-yaml/src/schemas/data/` + +### Base Schema Structure + +All events inherit from a base schema (`/packages/config-yaml/src/schemas/data/base.ts`): + +```typescript +{ + eventName: string, + schema: string, + timestamp: string, + userId: string, + userAgent: string, + selectedProfileId: string +} +``` + +## Key Integration Points + +### Autocomplete System + +- **File**: `/core/autocomplete/util/AutocompleteLoggingService.ts` +- **Purpose**: Tracks code completion acceptance/rejection, timing, and cache hits +- **Integration**: Called from autocomplete engine when completions are shown/accepted + +### Chat Interface + +- **Integration**: Chat interactions logged through `DataLogger.logDevData()` +- **Data**: Includes prompts, responses, context, and user feedback +- **Privacy**: Can be configured to exclude code content + +### Edit Features + +- **Files**: `/extensions/vscode/src/extension/EditOutcomeTracker.ts`, `/core/nextEdit/NextEditLoggingService.ts` +- **Purpose**: Track edit suggestions, acceptance rates, and outcomes +- **Integration**: Embedded in edit workflow to capture user decisions + +### LLM Token Tracking + +- **File**: `/core/llm/index.ts` +- **Purpose**: Track token usage across all LLM providers +- **Storage**: SQLite database for efficient querying and reporting + +## Configuration and Customization + +### Configuration Structure + +Dev data is configured through `data` blocks in your Continue config: + +```yaml +data: + - name: "Local Development Data" + destination: "file:///Users/developer/.continue/dev_data" + schema: "0.2.0" + level: "all" + events: ["autocomplete", "chatInteraction", "editOutcome"] + + - name: "Team Analytics" + destination: "https://analytics.yourcompany.com/api/events" + schema: "0.2.0" + level: "noCode" + apiKey: "your-api-key-here" + events: ["tokensGenerated", "toolUsage"] +``` + +### Configuration Options + +- **`destination`**: Where to send data (`file://` for local, `http://`/`https://` for remote) +- **`schema`**: Schema version to use (`"0.1.0"` or `"0.2.0"`) +- **`level`**: Data detail level (`"all"` includes code, `"noCode"` excludes code content) +- **`events`**: Array of event types to collect +- **`apiKey`**: Authentication for remote endpoints + +### Privacy Controls + +- **`"all"` level**: Includes code content (prefixes, suffixes, completions) +- **`"noCode"` level**: Excludes code content, only metadata and metrics +- **Local-first**: Data is always stored locally, remote transmission is optional + +## Making Changes to Dev Data + +### Adding New Event Types + +1. **Create schema**: Add new event schema in `/packages/config-yaml/src/schemas/data/` +2. **Update index**: Add to schema aggregator in `/packages/config-yaml/src/schemas/data/index.ts` +3. **Implement logging**: Add logging calls in relevant service files +4. **Update version**: Consider schema version bump if breaking changes + +### Modifying Existing Events + +1. **Schema changes**: Update schema files in `/packages/config-yaml/src/schemas/data/` +2. **Backward compatibility**: Ensure changes don't break existing data consumers +3. **Version management**: Increment schema version for breaking changes +4. **Test thoroughly**: Validate schema changes with existing data + +### Adding New Logging Points + +1. **Import DataLogger**: `import { DataLogger } from "core/data/log"` +2. **Log events**: Call `DataLogger.getInstance().logDevData(eventName, data)` +3. **Follow patterns**: Use existing logging services as examples +4. **Validate data**: Ensure logged data matches schema requirements + +### Debugging Dev Data Issues + +1. **Check local storage**: Verify files are being created in `~/.continue/dev_data/` +2. **Validate schemas**: Ensure event data matches expected schema format +3. **Review configuration**: Check `data` blocks in Continue config +4. **Test endpoints**: Verify remote endpoints are reachable and accepting data + +## Best Practices + +### When Adding New Events + +- Follow existing naming conventions for event types +- Include sufficient context for analysis without oversharing sensitive data +- Consider privacy implications and respect user configuration levels +- Add appropriate error handling and logging + +### When Modifying Schemas + +- Maintain backward compatibility when possible +- Document schema changes thoroughly +- Consider impact on existing data consumers +- Test with real development data + +### When Integrating Logging + +- Use the singleton pattern: `DataLogger.getInstance()` +- Log events at appropriate points in user workflow +- Respect user privacy settings and configuration +- Handle errors gracefully without disrupting user experience + +## Common Patterns + +### Service-Based Logging + +Most dev data logging follows a service pattern: + +```typescript +export class FeatureLoggingService { + private dataLogger = DataLogger.getInstance(); + + logFeatureUsage(data: FeatureUsageData) { + this.dataLogger.logDevData("featureUsage", data); + } +} +``` + +### Event-Driven Logging + +Events are typically logged at key interaction points: + +```typescript +// When user accepts autocomplete +onAutocompleteAccepted(completion: CompletionData) { + AutocompleteLoggingService.getInstance().logAutocompleteAccepted(completion); +} +``` + +This guide provides the foundation for understanding and working with Continue's dev data system. Always prioritize user privacy and follow established patterns when making changes. diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 920ed808b..956d249c4 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -168,7 +168,7 @@ jobs: key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - name: Build packages (Unix) - run: ./scripts/build-packages.sh + run: cd ../.. && ./scripts/build-packages.sh # npm install core - name: Install core node_modules diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 0ea873978..5b0636368 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -223,19 +223,6 @@ ], "type": "shell", "problemMatcher": [] - }, - { - "label": "Terminate All Tasks", - "command": "${input:terminate}", - "type": "shell" - } - ], - "inputs": [ - { - "id": "terminate", - "type": "command", - "command": "workbench.action.tasks.terminate", - "args": "terminateAll" } ] } diff --git a/binary/.gitignore b/binary/.gitignore index 3b0c8035f..356b68c71 100644 --- a/binary/.gitignore +++ b/binary/.gitignore @@ -3,3 +3,4 @@ bin data out tmp +tree-sitter diff --git a/binary/build.js b/binary/build.js index c2431333c..839bbb281 100644 --- a/binary/build.js +++ b/binary/build.js @@ -21,6 +21,7 @@ function cleanSlate() { rimrafSync(out); rimrafSync(build); rimrafSync(path.join(__dirname, "tmp")); + rimrafSync(path.join(__dirname, "tree-sitter")); fs.mkdirSync(bin); fs.mkdirSync(out); fs.mkdirSync(build); @@ -142,6 +143,25 @@ async function buildWithEsbuild() { ); }); + // copy tree-sitter colder to binary folder to make it available when running in intellij debug mode + const treeSitterDir = path.join(__dirname, "tree-sitter"); + fs.mkdirSync(treeSitterDir); + await new Promise((resolve, reject) => { + ncp( + path.join(__dirname, "..", "extensions", "vscode", "tree-sitter"), + treeSitterDir, + { dereference: true }, + (error) => { + if (error) { + console.warn("[error] Error copying tree-sitter files", error); + reject(error); + } else { + resolve(); + } + }, + ); + }); + const filesToCopy = [ "../core/vendor/tree-sitter.wasm", "../core/llm/llamaTokenizerWorkerPool.mjs", diff --git a/binary/package-lock.json b/binary/package-lock.json index 51e6f5cf9..11dd6505b 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -121,6 +121,8 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", + "@shikijs/colorized-brackets": "^3.7.0", + "@shikijs/transformers": "^3.7.0", "@types/diff": "^7.0.1", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", diff --git a/binary/pkgJson/darwin-arm64/package.json b/binary/pkgJson/darwin-arm64/package.json index afc840e85..885f2f215 100644 --- a/binary/pkgJson/darwin-arm64/package.json +++ b/binary/pkgJson/darwin-arm64/package.json @@ -11,6 +11,7 @@ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", "../../out/tree-sitter-wasms/*", + "../../tree-sitter/**/*", "../../out/llamaTokenizer.mjs", "../../out/llamaTokenizerWorkerPool.mjs", "../../out/tiktokenWorkerPool.mjs", diff --git a/binary/pkgJson/darwin-x64/package.json b/binary/pkgJson/darwin-x64/package.json index 4ba10b526..eba774c71 100644 --- a/binary/pkgJson/darwin-x64/package.json +++ b/binary/pkgJson/darwin-x64/package.json @@ -11,6 +11,7 @@ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", "../../out/tree-sitter-wasms/*", + "../../tree-sitter/**/*", "../../out/llamaTokenizer.mjs", "../../out/llamaTokenizerWorkerPool.mjs", "../../out/tiktokenWorkerPool.mjs", diff --git a/binary/pkgJson/linux-arm64/package.json b/binary/pkgJson/linux-arm64/package.json index efa9b2ad1..a3db51040 100644 --- a/binary/pkgJson/linux-arm64/package.json +++ b/binary/pkgJson/linux-arm64/package.json @@ -11,6 +11,7 @@ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", "../../out/tree-sitter-wasms/*", + "../../tree-sitter/**/*", "../../out/llamaTokenizer.mjs", "../../out/llamaTokenizerWorkerPool.mjs", "../../out/tiktokenWorkerPool.mjs", diff --git a/binary/pkgJson/linux-x64/package.json b/binary/pkgJson/linux-x64/package.json index c80a0af36..f23f4ce49 100644 --- a/binary/pkgJson/linux-x64/package.json +++ b/binary/pkgJson/linux-x64/package.json @@ -11,6 +11,7 @@ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", "../../out/tree-sitter-wasms/*", + "../../tree-sitter/**/*", "../../out/llamaTokenizer.mjs", "../../out/llamaTokenizerWorkerPool.mjs", "../../out/tiktokenWorkerPool.mjs", diff --git a/binary/pkgJson/win32-arm64/package.json b/binary/pkgJson/win32-arm64/package.json index 0aceefbe2..6134fb8fe 100644 --- a/binary/pkgJson/win32-arm64/package.json +++ b/binary/pkgJson/win32-arm64/package.json @@ -11,6 +11,7 @@ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", "../../out/tree-sitter-wasms/*", + "../../tree-sitter/**/*", "../../node_modules/win-ca/lib/crypt32-ia32.node", "../../node_modules/win-ca/lib/crypt32-x64.node", "../../node_modules/win-ca/lib/roots.exe", diff --git a/binary/pkgJson/win32-x64/package.json b/binary/pkgJson/win32-x64/package.json index 71de49f1c..be714529a 100644 --- a/binary/pkgJson/win32-x64/package.json +++ b/binary/pkgJson/win32-x64/package.json @@ -11,6 +11,7 @@ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", "../../out/tree-sitter-wasms/*", + "../../tree-sitter/**/*", "../../node_modules/win-ca/lib/crypt32-ia32.node", "../../node_modules/win-ca/lib/crypt32-x64.node", "../../node_modules/win-ca/lib/roots.exe", diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 749b44e25..e6111a508 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -254,7 +254,7 @@ export class CompletionProvider { completionId: helper.input.completionId, gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), - timestamp: Date.now(), + timestamp: new Date().toISOString(), ...helper.options, }; diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index 3959bff9c..bd385fb47 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -41,5 +41,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions { gitRepo?: string; completionId: string; uniqueId: string; - timestamp: number; + timestamp: string; } diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index af971d813..3d39a0c7c 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -47,7 +47,8 @@ class MCPConnection { }; constructor(public options: MCPOptions) { - this.transport = this.constructTransport(options); + // Don't construct transport in constructor to avoid blocking + this.transport = {} as Transport; // Will be set in connectClient this.client = new Client( { @@ -132,7 +133,8 @@ class MCPConnection { }); }), (async () => { - this.transport = this.constructTransport(this.options); + this.transport = await this.constructTransportAsync(this.options); + try { await this.client.connect(this.transport); } catch (error) { @@ -295,7 +297,9 @@ class MCPConnection { }; } - private constructTransport(options: MCPOptions): Transport { + private async constructTransportAsync( + options: MCPOptions, + ): Promise { switch (options.transport.type) { case "stdio": const env: Record = options.transport.env @@ -309,7 +313,7 @@ class MCPConnection { // For non-Windows platforms, try to get the PATH from user shell if (process.platform !== "win32") { try { - const shellEnvPath = getEnvPathFromUserShell(); + const shellEnvPath = await getEnvPathFromUserShell(); if (shellEnvPath && shellEnvPath !== process.env.PATH) { env.PATH = shellEnvPath; } diff --git a/core/context/mcp/MCPConnection.vitest.ts b/core/context/mcp/MCPConnection.vitest.ts index 0933ec020..510d80d54 100644 --- a/core/context/mcp/MCPConnection.vitest.ts +++ b/core/context/mcp/MCPConnection.vitest.ts @@ -3,6 +3,13 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import MCPConnection from "./MCPConnection"; import { StdioOptions } from "../../index.d.js"; +// Mock the shell path utility +vi.mock("../../util/shellPath", () => ({ + getEnvPathFromUserShell: vi + .fn() + .mockResolvedValue("/usr/local/bin:/usr/bin:/bin"), +})); + describe("MCPConnection", () => { beforeEach(() => { vi.restoreAllMocks(); @@ -98,7 +105,7 @@ describe("MCPConnection", () => { expect(conn.status).toBe("not-connected"); }); - it("should throw on invalid transport type", () => { + it("should throw on invalid transport type", async () => { const options = { name: "test-mcp", id: "test-id", @@ -107,9 +114,14 @@ describe("MCPConnection", () => { } as any, }; - expect(() => new MCPConnection(options)).toThrow( - "Unsupported transport type: invalid", - ); + const conn = new MCPConnection(options); + const abortController = new AbortController(); + + // The validation now happens during connectClient, not constructor + await conn.connectClient(false, abortController.signal); + + expect(conn.status).toBe("error"); + expect(conn.errors[0]).toContain("Unsupported transport type: invalid"); }); }); @@ -203,6 +215,15 @@ describe("MCPConnection", () => { () => new Promise((resolve) => setTimeout(resolve, 1000)), ); + // Mock the required methods for successful connection + const mockGetServerCapabilities = vi + .spyOn(Client.prototype, "getServerCapabilities") + .mockReturnValue({ + resources: {}, + tools: {}, + prompts: {}, + }); + const abortController = new AbortController(); await conn.connectClient(false, abortController.signal); @@ -211,7 +232,7 @@ describe("MCPConnection", () => { }); it("should handle connection timeout", async () => { - const conn = new MCPConnection({ ...options, timeout: 1 }); + const conn = new MCPConnection({ ...options, timeout: 50 }); const mockConnect = vi .spyOn(Client.prototype, "connect") .mockImplementation( @@ -223,7 +244,9 @@ describe("MCPConnection", () => { expect(conn.status).toBe("error"); expect(conn.errors[0]).toContain("Failed to connect"); - expect(mockConnect).toHaveBeenCalled(); + // The connection should timeout before connect is called due to transport construction + // Since transport construction happens first, and we're not mocking that, + // the timeout will happen during transport construction or connect attempt }); it("should handle already connected state", async () => { diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 360e68670..0f87a3f61 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -145,6 +145,11 @@ class DocsContextProvider extends BaseContextProvider { async loadSubmenuItems( args: LoadSubmenuItemsArgs, ): Promise { + const { config } = args; + // This set is used to filter out the docs that is not in docs config but exist in sqlite metadata + const configDocsSet = new Set( + config.docs?.map((doc) => doc.startUrl) || [], + ); // Get docs service const docsService = DocsService.getSingleton(); if (!docsService) { @@ -159,12 +164,14 @@ class DocsContextProvider extends BaseContextProvider { // Get all indexed docs from the database const docs = (await docsService.listMetadata()) ?? []; for (const { startUrl, title, favicon } of docs) { - submenuItems.push({ - title, - id: startUrl, - description: new URL(startUrl).hostname, - icon: favicon, - }); + if (configDocsSet.has(startUrl)) { + submenuItems.push({ + title, + id: startUrl, + description: new URL(startUrl).hostname, + icon: favicon, + }); + } } // Sort alphabetically diff --git a/core/context/providers/HttpContextProvider.ts b/core/context/providers/HttpContextProvider.ts index 7451fd461..5c879e064 100644 --- a/core/context/providers/HttpContextProvider.ts +++ b/core/context/providers/HttpContextProvider.ts @@ -72,6 +72,10 @@ class HttpContextProvider extends BaseContextProvider { description: item.description ?? "HTTP Context Item", content: item.content ?? "", name: item.name ?? this.options.title ?? "HTTP", + uri: { + type: item.uri.type, + value: item.uri.value, + }, }); return Array.isArray(json) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 7ea3d444e..0ccb4804e 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -107,6 +107,17 @@ const siteIndexingConfigsAreEqual = ( ); }; +const siteIndexingConfigsAreEqualExceptTitleAndFavicon = ( + config1: SiteIndexingConfig, + config2: SiteIndexingConfig, +) => { + return ( + config1.startUrl === config2.startUrl && + config1.maxDepth === config2.maxDepth && + config1.useLocalCrawling === config2.useLocalCrawling + ); +}; + /* General process: - On config update: @@ -395,6 +406,21 @@ export default class DocsService { siteIndexingConfig: SiteIndexingConfig, ): Promise { try { + // Set a initial status when retrieving cache + this.handleStatusUpdate({ + type: "docs", + id: startUrl, + embeddingsProviderId: embeddingId, + isReindexing: false, + title: siteIndexingConfig.title, + debugInfo: "Loaded from cache", + icon: siteIndexingConfig.faviconUrl, + url: startUrl, + progress: 0, + description: "Try to retrieve cache", + status: "indexing", + }); + const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId); if (cacheHit) { @@ -429,7 +455,8 @@ export default class DocsService { siteIndexingConfig: SiteIndexingConfig, forceReindex: boolean = false, ): Promise { - const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig; + const { startUrl, useLocalCrawling, maxDepth, faviconUrl } = + siteIndexingConfig; // First, if indexing is already in process, don't attempt // This queue is necessary because indexAndAdd is invoked circularly by config edits @@ -685,7 +712,9 @@ export default class DocsService { await this.deleteIndexes(startUrl); } - const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); + const favicon = + faviconUrl || + (await fetchFavicon(new URL(siteIndexingConfig.startUrl))); if (this.shouldCancel(startUrl, startedWithEmbedder)) { return; @@ -718,10 +747,6 @@ export default class DocsService { void this.ide.showToast("info", `Successfully indexed ${startUrl}`); } - this.messenger?.send("refreshSubmenuItems", { - providers: ["docs"], - }); - removeFromFailedGlobalContext(siteIndexingConfig); } catch (e) { console.error( @@ -766,14 +791,22 @@ export default class DocsService { const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; // Try to get a favicon for the site - const favicon = await fetchFavicon(new URL(startUrl)); + const favicon = + this.statuses.get(startUrl)?.icon || + (await fetchFavicon(new URL(startUrl))); + + // Always try to make the title match what users set in the config + const title = + this.statuses.get(startUrl)?.title || + siteEmbeddings.title || + new URL(startUrl).hostname; // Add the cached embeddings to our database await this.add({ favicon, siteIndexingConfig: { startUrl, - title: siteEmbeddings.title || new URL(startUrl).hostname, + title, }, chunks: siteEmbeddings.chunks, embeddings: siteEmbeddings.chunks.map((c) => c.embedding), @@ -910,6 +943,10 @@ export default class DocsService { ); if (cacheHit) { + // If cache hit, refresh the submenu items for docs + this.messenger?.send("refreshSubmenuItems", { + providers: ["docs"], + }); // If cache hit, retry the search once return await this.retrieveChunks(startUrl, vector, nRetrieve, true); } @@ -987,8 +1024,7 @@ export default class DocsService { const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed - // TODO if only favicon and title change, only update, don't embed - // Otherwise anything found in new config that isn't in sqlite should be added/indexed + // Anything found in new config that isn't in sqlite should be added/indexed const addedDocs: SiteIndexingConfig[] = []; const changedDocs: SiteIndexingConfig[] = []; for (const doc of newConfigDocs) { @@ -999,12 +1035,26 @@ export default class DocsService { (d) => d.startUrl === doc.startUrl, ); + // TODO: Changes to the docs config made while Continue isn't running won't be caught if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) { - changedDocs.push(doc); + // When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing + if ( + siteIndexingConfigsAreEqualExceptTitleAndFavicon( + oldConfigDoc, + doc, + ) + ) { + await this.updateMetadataInSqlite(doc); + } else { + changedDocs.push(doc); + } } else { if (forceReindex) { changedDocs.push(doc); } else { + // This is a temperary fix to catch the changes to the docs config that were made when Continue isn't running + // We only update title and faviconUrl here + await this.updateMetadataInSqlite(doc); // if get's here, not changed, no update needed, mark as complete this.handleStatusUpdate({ type: "docs", @@ -1036,6 +1086,10 @@ export default class DocsService { console.error("Error syncing docs index on config update", e); } finally { this.isSyncing = false; + // Refresh the submenu items for docs + this.messenger?.send("refreshSubmenuItems", { + providers: ["docs"], + }); } } @@ -1182,6 +1236,27 @@ export default class DocsService { ); } + private async updateMetadataInSqlite(siteIndexingConfig: SiteIndexingConfig) { + const { startUrl, title, faviconUrl } = siteIndexingConfig; + const favicon = faviconUrl || (await fetchFavicon(new URL(startUrl))); + if (!this.config.selectedModelByRole.embed) { + console.warn( + `Attempting to add metadata for ${startUrl} without embeddings provider specified`, + ); + return; + } + + const db = await this.getOrCreateSqliteDb(); + + await db.run( + `UPDATE ${DocsService.sqlitebTableName} SET title = ?, favicon = ? WHERE startUrl = ? AND embeddingsProviderId = ?`, + title, + favicon, + startUrl, + this.config.selectedModelByRole.embed.embeddingId, + ); + } + private addToConfig(siteIndexingConfig: SiteIndexingConfig) { // Handles the case where a user has manually added the doc to config.json // so it already exists in the file @@ -1286,5 +1361,6 @@ export default class DocsService { this.messenger?.send("refreshSubmenuItems", { providers: ["docs"], }); + this.statuses.delete(startUrl); } } diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 9a3d37af9..a220b5dbd 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -46,6 +46,7 @@ import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js"; const PROVIDER_HANDLES_TEMPLATING: string[] = [ "lmstudio", "openai", + "nvidia", "ollama", "together", "novita", diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index a6b3afc6c..b4ecf8e91 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -51,7 +51,7 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ You are in chat mode. If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically. - If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. + If needed concisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. ${CODEBLOCK_FORMATTING_INSTRUCTIONS} ${EDIT_CODE_INSTRUCTIONS} diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 1a956cf76..c3c2c9bf4 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,4 +1,4 @@ -import { GoogleAuth } from "google-auth-library"; +import { AuthClient, GoogleAuth, JWT, auth } from "google-auth-library"; import { streamResponse, streamSse } from "@continuedev/fetch"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; @@ -14,30 +14,40 @@ class VertexAI extends BaseLLM { declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown"; declare anthropicInstance: Anthropic; declare geminiInstance: Gemini; + static AUTH_SCOPES = "https://www.googleapis.com/auth/cloud-platform"; static defaultOptions: Partial | undefined = { maxEmbeddingBatchSize: 250, region: "us-central1", }; - private clientPromise = new GoogleAuth({ - scopes: "https://www.googleapis.com/auth/cloud-platform", - }) - .getClient() - .catch((e) => { - console.warn(`Failed to load credentials for Vertex AI: ${e.message}`); - }); + private clientPromise: Promise; - private static getDefaultApiBaseFrom(options: LLMOptions) { - const { region, projectId } = options; - if (!region || !projectId) { - throw new Error( - "region and projectId must be defined if apiBase is not provided", - ); - } - return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`; - } + /* + Vertex Supports 3 different URL formats + 1. Standard VertexAI: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/google/models/{model}:streamGenerateContent + 2. Tuned model: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint}:streamGenerateContent + 3. Express mode: e.g. https://aiplatform.googleapis.com/v1/publishers/google/models/{model}:streamGenerateContent?key={API_KEY} // see https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview + Authentication can be done using the following + 2. Access token obtained using Google Auth client, passed to endpoint that includes full model path with project id and region + 1. API Key (express mode), region and projectId will be ignored + + In all cases we have defined apiBase to be up to everything including the location. + Standard api base: https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/ + Express api base: https://aiplatform.googleapis.com/v1/ + TODO endpoints is not currently supported (api base is same as standard but we don't have a way to add endpoint name yet + + Note that VertexAI uses the term "service endpoint" and "model", like: + {service-endpoint}/v1/{model}:streamGenerateContent + So "model" includes the project, location, publisher, etc + + Express mode has limited support + and CRITICALLY is only available to NEW users who had NOT used cloud services before. + However it is pretty common as gemini becomes more popular. + Only Gemini models are supported for now + https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models + */ constructor(_options: LLMOptions) { if (_options.region !== "us-central1") { // Any region outside of us-central1 has a max batch size of 5. @@ -47,7 +57,7 @@ class VertexAI extends BaseLLM { ); } super(_options); - this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options); + this.vertexProvider = _options.model.includes("mistral") || _options.model.includes("codestral") || @@ -58,24 +68,130 @@ class VertexAI extends BaseLLM { : _options.model.includes("gemini") ? "gemini" : "unknown"; + + // Set client authentication promise + const { apiKey, region, projectId, env } = _options; + const keyFile = env?.keyFile; + const keyJson = env?.keyJson; + + // Acceptable authentication methods: + // apiKey only + // region and projectId AND (keyFile OR keyJson OR nothing) + + if (apiKey) { + // Consider warning here instead of throwing error + if (region || projectId || keyFile || keyJson) { + throw new Error( + "Vertex in express mode (api key only) cannot be configured with region, projectId, keyFile, or keyJson", + ); + // console.warn( + // "Region, projectId, and key path/file are ignored when apiKey is set. See VertexAI Express Mode docs https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview", + // ); + } + if (this.vertexProvider !== "gemini") { + throw new Error( + "VertexAI: only gemini models are supported in express (apiKey) mode. See https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models", + ); + } + } else { + if (!region && !projectId) { + throw new Error( + "region and projectId are required for VertexAI (when not using express/apiKey mode)", + ); + } + if (keyFile && keyJson) { + throw new Error( + "VertexAI credentials can be configured with either keyFile or keyJson but not both", + ); + } + } + + if (keyJson) { + // Loading keys from manually set JSON + if (typeof keyJson !== "string") { + throw new Error("VertexAI: keyJson must be a JSON string"); + } + try { + const parsed = JSON.parse(keyJson); + if (!parsed?.private_key) { + throw new Error("VertexAI: keyJson must contain a valid private key"); + } + parsed.private_key = parsed.private_key.replace(/\\n/g, "\n"); + const jsonClient = auth.fromJSON(parsed); + if (jsonClient instanceof JWT) { + jsonClient.scopes = [VertexAI.AUTH_SCOPES]; + } else { + throw new Error("VertexAI: keyJson must be a valid JWT"); + } + this.clientPromise = Promise.resolve(jsonClient); + } catch (e) { + throw new Error("VertexAI: Failed to parse keyJson"); + } + } else if (keyFile) { + // Loading keys from manually set file path + if (typeof keyFile !== "string") { + throw new Error("VertexAI: keyFile must be a string"); + } + this.clientPromise = new GoogleAuth({ + scopes: VertexAI.AUTH_SCOPES, + keyFile, + }) + .getClient() + .catch((e) => { + console.warn( + `Failed to load credentials for Vertex AI: ${e.message}`, + ); + }); + } else { + // Loading keys from local credentials or environment variable + this.clientPromise = new GoogleAuth({ + scopes: VertexAI.AUTH_SCOPES, + }) + .getClient() + .catch((e) => { + console.warn( + `Failed to load credentials for Vertex AI: ${e.message}`, + ); + }); + } + + // Set api base + if (!this.apiBase) { + if (apiKey) { + // Express mode + this.apiBase = `https://aiplatform.googleapis.com/v1/`; + } else { + this.apiBase = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`; + } + } + + // Uses instances of other LLMs since underlying functionality is the same this.anthropicInstance = new Anthropic(_options); this.geminiInstance = new Gemini(_options); } - async fetch(url: RequestInfo | URL, init?: RequestInit) { - const client = await this.clientPromise; - const result = await client?.getAccessToken(); - if (!result?.token) { - throw new Error( - "Could not get an access token. Set up your Google Application Default Credentials.", - ); + async fetch(url: URL, init?: RequestInit) { + const headers: Record = { + "Content-Type": "application/json", + }; + if (this.apiKey) { + url.searchParams.set("key", this.apiKey); + } else { + const client = await this.clientPromise; + const result = await client?.getAccessToken(); + if (!result?.token) { + throw new Error( + "Could not get an access token. Set up your Google Application Default Credentials.", + ); + } + headers.Authorization = `Bearer ${result.token}`; } + return await super.fetch(url, { ...init, headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${result.token}`, ...init?.headers, + ...headers, }, }); } @@ -85,6 +201,10 @@ class VertexAI extends BaseLLM { const convertedArgs = this.anthropicInstance.convertArgs(options); // Remove the `model` property and add `anthropic_version` + // For claude 4 models + // anthropic_version is a required parameter and must be set to "vertex-2024-10-22". + + // const const { model, ...finalOptions } = convertedArgs; return { ...finalOptions, @@ -104,6 +224,8 @@ class VertexAI extends BaseLLM { this.cacheBehavior?.cacheSystemMessage && systemMessage ); + // /v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict + const apiURL = new URL( `publishers/anthropic/models/${options.model}:streamRawPredict`, this.apiBase, diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index f017f24fd..39a30e34d 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -324,6 +324,10 @@ export const getApplicableRules = ( return applicableRules; }; +export function getRuleId(rule: RuleWithSource): string { + return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source; +} + export const getSystemMessageWithRules = ({ baseSystemMessage, userMessage, diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 9c3db3e74..ccaf906ce 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -19,6 +19,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "claude-3-7", "claude-3.7", "claude-sonnet-4", + "claude-4-sonnet", "gpt-4", "o3", "gemini", @@ -33,6 +34,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "claude-3-7", "claude-3.7", "claude-sonnet-4", + "claude-4-sonnet", "claude-opus-4", ].some((part) => model.toLowerCase().startsWith(part)) ) { @@ -95,6 +97,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "claude-3-7-sonnet", "claude-3.7-sonnet", "claude-sonnet-4", + "claude-4-sonnet", "claude-opus-4", "nova-lite", "nova-pro", diff --git a/core/nextEdit/context/aggregateEdits.ts b/core/nextEdit/context/aggregateEdits.ts index 4443b1d9e..b4a9bbd9e 100644 --- a/core/nextEdit/context/aggregateEdits.ts +++ b/core/nextEdit/context/aggregateEdits.ts @@ -482,12 +482,13 @@ export class EditAggregator { return; } - const diff = createDiff( - beforeContent, - afterContent, - filePath, - DiffFormatType.Unified, - ); // Used for checks, not for final output + const diff = createDiff({ + beforeContent: beforeContent, + afterContent: afterContent, + filePath: filePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }); // Used for checks, not for final output // Skip diffs with too many changed lines const changedLineCount = this.countChangedLines(diff); diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts index 6d892dee7..465a7106f 100644 --- a/core/nextEdit/context/diffFormatting.ts +++ b/core/nextEdit/context/diffFormatting.ts @@ -12,15 +12,29 @@ export type BeforeAfterDiff = { afterContent: string; }; -export const createDiff = ( - beforeContent: string, - afterContent: string, - filePath: string, - diffType: DiffFormatType, -) => { +export interface CreateDiffArgs { + beforeContent: string; + afterContent: string; + filePath: string; + diffType: DiffFormatType; + contextLines: number; +} + +export const createDiff = ({ + beforeContent, + afterContent, + filePath, + diffType, + contextLines, +}: CreateDiffArgs) => { switch (diffType) { case DiffFormatType.Unified: - return createUnifiedDiff(beforeContent, afterContent, filePath); + return createUnifiedDiff( + beforeContent, + afterContent, + filePath, + contextLines, + ); case DiffFormatType.TokenLineDiff: return createTokenLineDiff(beforeContent, afterContent, filePath); } @@ -31,6 +45,7 @@ const createUnifiedDiff = ( beforeContent: string, afterContent: string, filePath: string, + contextLines: number, ) => { const normalizedBefore = beforeContent.endsWith("\n") ? beforeContent @@ -45,7 +60,7 @@ const createUnifiedDiff = ( normalizedAfter, "before", "after", - { context: 3 }, + { context: contextLines }, ); return patch; diff --git a/core/nextEdit/context/processNextEditData.ts b/core/nextEdit/context/processNextEditData.ts index cb514f1e6..aaa89d33a 100644 --- a/core/nextEdit/context/processNextEditData.ts +++ b/core/nextEdit/context/processNextEditData.ts @@ -2,7 +2,7 @@ import { IDE, Position } from "../.."; import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types"; import { GetLspDefinitionsFunction } from "../../autocomplete/types"; import { ConfigHandler } from "../../config/ConfigHandler"; -// import { DataLogger } from "../../data/log"; +import { DataLogger } from "../../data/log"; import { RecentlyEditedRange } from "../types"; import { getAutocompleteContext } from "./autocompleteContextFetching"; import { createDiff, DiffFormatType } from "./diffFormatting"; @@ -108,31 +108,32 @@ export const processNextEditData = async ({ ); } - // if (filenamesAndDiffs.length > 0) { - // // if there are previous edits, log - // void DataLogger.getInstance().logDevData({ - // name: "nextEditWithHistory", - // data: { - // previousEdits: filenamesAndDiffs, - // fileURI: filePath, - // workspaceDirURI: workspaceDir, - // beforeContent, - // afterContent, - // beforeCursorPos: cursorPosBeforeEdit, - // afterCursorPos: cursorPosAfterPrevEdit, - // context: autocompleteContext, - // }, - // }); - // } + if (filenamesAndDiffs.length > 0) { + // if there are previous edits, log + void DataLogger.getInstance().logDevData({ + name: "nextEditWithHistory", + data: { + previousEdits: filenamesAndDiffs, + fileURI: filePath, + workspaceDirURI: workspaceDir, + beforeContent, + afterContent, + beforeCursorPos: cursorPosBeforeEdit, + afterCursorPos: cursorPosAfterPrevEdit, + context: autocompleteContext, + }, + }); + } // add current edit to history const thisEdit: prevEdit = { - unidiff: createDiff( - beforeContent, - afterContent, - filePath, - DiffFormatType.Unified, - ), + unidiff: createDiff({ + beforeContent: beforeContent, + afterContent: afterContent, + filePath: filePath, + diffType: DiffFormatType.Unified, + contextLines: 25, // storing many context lines for downstream trimming + }), fileUri: filePath, workspaceUri: workspaceDir, timestamp: timestamp, diff --git a/core/nextEdit/context/processSmallEdit.ts b/core/nextEdit/context/processSmallEdit.ts index 18ed9d544..5824191b3 100644 --- a/core/nextEdit/context/processSmallEdit.ts +++ b/core/nextEdit/context/processSmallEdit.ts @@ -15,12 +15,13 @@ export const processSmallEdit = async ( ide: IDE, ) => { NextEditProvider.getInstance().addDiffToContext( - createDiff( - beforeAfterdiff.beforeContent, - beforeAfterdiff.afterContent, - beforeAfterdiff.filePath, - DiffFormatType.Unified, - ), + createDiff({ + beforeContent: beforeAfterdiff.beforeContent, + afterContent: beforeAfterdiff.afterContent, + filePath: beforeAfterdiff.filePath, + diffType: DiffFormatType.Unified, + contextLines: 3, // NOTE: This can change depending on experiments! + }), ); // Get the current context data from the most recent message diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts index b654f9c32..f4c601009 100644 --- a/core/tools/definitions/searchAndReplaceInFile.ts +++ b/core/tools/definitions/searchAndReplaceInFile.ts @@ -56,7 +56,11 @@ Critical rules: * Include just the changing lines, and a few surrounding lines if needed for uniqueness. * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks. * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures. -4. Special operations: +4. Splitting up tool calls: + * When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls + * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls + * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call] +5. Special operations: * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) * To delete code: Use empty REPLACE section diff --git a/core/tools/index.ts b/core/tools/index.ts index b2d4722ad..1246c937f 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -39,14 +39,13 @@ export const getConfigDependentToolDefinitions = ( params: ConfigDependentToolParams, ): Tool[] => [ requestRuleTool(params), + // Search and replace is now generally available + searchAndReplaceInFileTool, + // Keep edit file tool available for models that need it + editFileTool, ...(params.enableExperimentalTools - ? [ - searchAndReplaceInFileTool, - viewRepoMapTool, - viewSubdirectoryTool, - codebaseTool, - ] - : [editFileTool]), + ? [viewRepoMapTool, viewSubdirectoryTool, codebaseTool] + : []), ]; export const getToolsForIde = async (ide: IDE): Promise => diff --git a/core/tools/parseArgs.ts b/core/tools/parseArgs.ts index 86ee26cb1..8ee794eb5 100644 --- a/core/tools/parseArgs.ts +++ b/core/tools/parseArgs.ts @@ -6,9 +6,9 @@ export function safeParseToolCallArgs( try { return JSON.parse(toolCall.function?.arguments?.trim() || "{}"); } catch (e) { - console.error( - `Failed to parse tool call arguments:\nTool call: ${toolCall.function?.name + " " + toolCall.id}\nArgs:${toolCall.function?.arguments}\n`, - ); + //console.error( + // `Failed to parse tool call arguments:\nTool call: ${toolCall.function?.name + " " + toolCall.id}\nArgs:${toolCall.function?.arguments}\n`, + //); return {}; } } diff --git a/core/util/paths.ts b/core/util/paths.ts index 1123b7eda..315053413 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; +import * as URI from "uri-js"; import * as YAML from "yaml"; import { ConfigYaml, DevEventName } from "@continuedev/config-yaml"; @@ -466,3 +467,38 @@ export function getDiffsDirectoryPath(): string { } return diffsPath; } + +export const isFileWithinFolder = ( + fileUri: string, + folderPath: string, +): boolean => { + try { + if (!fileUri || !folderPath) { + return false; + } + + const fileUriParsed = URI.parse(fileUri); + const fileScheme = fileUriParsed.scheme || "file"; + let filePath = fileUriParsed.path || ""; + filePath = decodeURIComponent(filePath); + + let folderWithScheme = folderPath; + if (!folderPath.includes("://")) { + folderWithScheme = `${fileScheme}://${folderPath.startsWith("/") ? "" : "/"}${folderPath}`; + } + const folderUriParsed = URI.parse(folderWithScheme); + + let folderPathClean = folderUriParsed.path || ""; + folderPathClean = decodeURIComponent(folderPathClean); + + filePath = filePath.replace(/\/$/, ""); + folderPathClean = folderPathClean.replace(/\/$/, ""); + + return ( + filePath === folderPathClean || filePath.startsWith(`${folderPathClean}/`) + ); + } catch (error) { + console.error("Error in isFileWithinFolder:", error); + return false; + } +}; diff --git a/core/util/shellPath.ts b/core/util/shellPath.ts index f2ade2443..a33eeb45e 100644 --- a/core/util/shellPath.ts +++ b/core/util/shellPath.ts @@ -1,7 +1,8 @@ -import { execSync } from "child_process"; -import { homedir } from "os"; +import { exec } from "child_process"; +import { promisify } from "util"; -export function getEnvPathFromUserShell(): string | undefined { +const execAsync = promisify(exec); +export async function getEnvPathFromUserShell(): Promise { if (process.platform === "win32") { console.warn(`${getEnvPathFromUserShell.name} not implemented for Windows`); return undefined; @@ -15,7 +16,7 @@ export function getEnvPathFromUserShell(): string | undefined { // Source common profile files const command = `${process.env.SHELL} -l -c 'for f in ~/.zprofile ~/.zshrc ~/.bash_profile ~/.bashrc; do [ -f "$f" ] && source "$f" 2>/dev/null; done; echo $PATH'`; - const stdout = execSync(command, { + const { stdout } = await execAsync(command, { encoding: "utf8", }); diff --git a/docs/docs/customization/mcp-tools.mdx b/docs/docs/customization/mcp-tools.mdx index 098835c59..9b4d35519 100644 --- a/docs/docs/customization/mcp-tools.mdx +++ b/docs/docs/customization/mcp-tools.mdx @@ -19,22 +19,3 @@ Model Context Protocol servers provide specialized functionality: ## Learn More Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details. -description: Model Context Protocol servers provide specialized functionality -keywords: [mcp, blocks, model context protocol, integrations, tools] -sidebar_position: 4 - ---- - -Model Context Protocol servers provide specialized functionality: - -- Enable integration with external tools and systems -- Create extensible interfaces for custom capabilities -- Support more complex interactions with your development environment -- Allow partners to contribute specialized functionality -- Database Connectors: Understand schema and data models during development - -![MCP Blocks Overview](/img/mcp-blocks-overview.png) - -## Learn More - -Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details. diff --git a/docs/docs/customize/custom-providers.mdx b/docs/docs/customize/custom-providers.mdx index 1061ea12a..8ea5b7b7d 100644 --- a/docs/docs/customize/custom-providers.mdx +++ b/docs/docs/customize/custom-providers.mdx @@ -987,6 +987,33 @@ The response 200 OK should be a JSON object with the following structure: "description": "", "content": "" } + +// For response context items with hyperlinks + +[ + { + "name": "", + "description": "", + "content": "", + "uri": { + "type": "file" or "url", + "value": "file:///path/to/file" or "https://example.com", + } + } +] + +// OR + +{ + "name": "", + "description": "", + "content": "", + "uri": { + "type": "file" or "url", + "value": "file:///path/to/file" or "https://example.com", + } +} + ``` ### `@Commits` diff --git a/docs/docs/customize/deep-dives/mcp.mdx b/docs/docs/customize/deep-dives/mcp.mdx index 589b04798..eb95d66f5 100644 --- a/docs/docs/customize/deep-dives/mcp.mdx +++ b/docs/docs/customize/deep-dives/mcp.mdx @@ -140,7 +140,7 @@ mcpServers: - "@modelcontextprotocol/server-sqlite" - "./database.db" cwd: "/path/to/project" - + - name: Local Project Server command: npm args: diff --git a/docs/docs/customize/model-providers/top-level/vertexai.mdx b/docs/docs/customize/model-providers/top-level/vertexai.mdx index 2863acc31..383e404f1 100644 --- a/docs/docs/customize/model-providers/top-level/vertexai.mdx +++ b/docs/docs/customize/model-providers/top-level/vertexai.mdx @@ -114,3 +114,33 @@ We recommend configuring **text-embedding-004** as your embeddings model. Vertex AI currently does not offer any reranking models. [Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. + +## Express mode + +You can use VertexAI in [express mode](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview) by only providing an API Key. Only some Gemini models are supported in express mode for now. + + + + ```yaml title="config.yaml" + models: + - name: Gemini 2.5 Flash - VertexAI + provider: vertexai + model: gemini-2.5-flash + apiKey: ${{ secrets.GOOGLE_CLOUD_API_KEY }} + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Gemini 2.5 Flash - VertexAI", + "provider": "vertexai", + "model": "gemini-2.5-flash", + "apiKey": "[YOUR_GOOGLE_CLOUD_API_KEY]", + } + ] + } + ``` + + diff --git a/docs/docs/features/agent/context-selection.mdx b/docs/docs/features/agent/context-selection.mdx new file mode 100644 index 000000000..57efd4711 --- /dev/null +++ b/docs/docs/features/agent/context-selection.mdx @@ -0,0 +1,3 @@ +You can use the same methods to manually add context as [Chat](/features/chat/context-selection). + +Tool call responses are automatically included as context items. This enables Agent mode to see the result of the previous action and decide what to do next. diff --git a/docs/docs/features/agent/how-to-customize.mdx b/docs/docs/features/agent/how-to-customize.mdx new file mode 100644 index 000000000..a912292d2 --- /dev/null +++ b/docs/docs/features/agent/how-to-customize.mdx @@ -0,0 +1,27 @@ +## Add Rules Blocks + +Adding Rules can be done in your assistant locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details. + +## Add MCP Tools + +You can add MCP servers to your assistant to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details. + +## Tool Policies + +You can adjust the Agent's tool usage behavior to three options: + +- **Ask First (default)**: Request user permission with "Cancel" and "Continue" buttons +- **Automatic**: Automatically call the tool without requesting permission +- **Excluded**: Do not send the tool to the model + +:::warning +Be careful setting tools to "automatic" if their behavior is not read-only. +::: + +To manage tool policies: + +1. Click the tools icon in the input toolbar +2. View and change policies by clicking on the policy text +3. You can also toggle groups of tools on/off + +Tool policies are stored locally per user. diff --git a/docs/docs/features/agent/model-setup.mdx b/docs/docs/features/agent/model-setup.mdx new file mode 100644 index 000000000..c4a30c526 --- /dev/null +++ b/docs/docs/features/agent/model-setup.mdx @@ -0,0 +1,14 @@ +We recommend **Claude 3.5 Sonnet** from Anthropic for the best Agent experience. + +- [Add Claude 3.5 Sonnet to your assistant from the hub](https://hub.continue.dev/anthropic/claude-3-5-sonnet-20241022) +- Get your API key from the [Anthropic console](https://console.anthropic.com/) + +## Other recommended models + +- [Claude Sonnet 4 from Anthropic](https://hub.continue.dev/anthropic) +- [GPT-4o from OpenAI](https://hub.continue.dev/openai/gpt-4o) +- [Gemini 2.0 Pro from Google](https://hub.continue.dev/google/gemini-2.0-pro) + +Agent can be used with models that support tool use through Continue. The best chat models generally support tool use. + +For more information on models, check out [our recommended chat models](/features/chat/model-setup). diff --git a/docs/docs/features/autocomplete/context-selection.mdx b/docs/docs/features/autocomplete/context-selection.mdx new file mode 100644 index 000000000..66cd4694e --- /dev/null +++ b/docs/docs/features/autocomplete/context-selection.mdx @@ -0,0 +1,19 @@ +# Context Selection + +Autocomplete will automatically determine context based on the current cursor position. We use the following techniques to determine what to include in the prompt: + +## File prefix/suffix + +We will always include the code from your file prior to and after the cursor position. + +## Definitions from the Language Server Protocol + +Similar to how you can use cmd/ctrl + click in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type. + +## Imported files + +Because there are often many imports, we can't include all of them. Instead, we look for symbols around your cursor that have matching imports and use that as context. + +## Recent files + +We automatically consider recently opened or edited files and include snippets that are relevant to the current completion. diff --git a/docs/docs/features/autocomplete/how-to-customize.mdx b/docs/docs/features/autocomplete/how-to-customize.mdx new file mode 100644 index 000000000..ddd028933 --- /dev/null +++ b/docs/docs/features/autocomplete/how-to-customize.mdx @@ -0,0 +1,5 @@ +# How to Customize Autocomplete + +Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings. + +For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete). diff --git a/docs/docs/features/autocomplete/model-setup.mdx b/docs/docs/features/autocomplete/model-setup.mdx new file mode 100644 index 000000000..9acece878 --- /dev/null +++ b/docs/docs/features/autocomplete/model-setup.mdx @@ -0,0 +1,29 @@ +# Autocomplete Model Setup + +Setting up the right model for autocomplete is crucial for a smooth coding experience. Here are our top recommendations: + +## Recommended Models + +### Hosted-Based (Best Performance) + +For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral. This model is specifically designed for code completion and offers excellent performance across multiple programming languages. + +**Quick Setup:** + +1. [Add Codestral from the hub](https://hub.continue.dev/mistral/codestral) +2. Get your API key from the [Mistral Platform](https://console.mistral.ai/codestral) +3. Configure it in your Continue settings + +### Local/Offline (Privacy First) + +For a fully local autocomplete experience that doesn't send your code to external servers, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)** running on Ollama. This model provides good suggestions while keeping your code completely private. + +**Quick Setup:** + +1. Install [Ollama](https://ollama.ai/) +2. [Add Qwen 2.5 Coder from the hub](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) +3. Configure it in your Continue settings + +## Need Help? + +If you're not seeing any completions or need more detailed configuration options, check out our comprehensive [autocomplete deep dive guide](/customize/deep-dives/autocomplete). diff --git a/docs/docs/features/chat/context-selection.mdx b/docs/docs/features/chat/context-selection.mdx new file mode 100644 index 000000000..04041b689 --- /dev/null +++ b/docs/docs/features/chat/context-selection.mdx @@ -0,0 +1,39 @@ +## Input + +Typing a question or instructions into the input box is the only required context. + +## Highlighted Code + +The highlighted code you've selected by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) will be included in your prompt. + +## Active File + +You can include the currently open file as context by pressing opt/alt + enter when you send your request. + +## Specific File + +You can include a specific file in your current workspace by typing '@Files' and selecting the file. + +## Specific Folder + +You can include a folder in your current workspace by typing '@Folder' and selecting the directory. + +## Codebase Search + +You can automatically include relevant files from your codebase by typing '@Codebase'. + +## Documentation Site + +You can include a documentation site as context by typing '@Docs' and selecting the site. + +## Terminal Contents + +You can include the contents of the terminal in your IDE by typing '@Terminal'. + +## Git Diff + +You can include all of the changes you've made to your current branch by typing '@Git Diff'. + +## Other Context + +You can see a full list of built-in context providers [here](/customize/custom-providers) and learn about how to create your own context provider [here](/guides/build-your-own-context-provider). diff --git a/docs/docs/features/chat/how-to-customize.mdx b/docs/docs/features/chat/how-to-customize.mdx new file mode 100644 index 000000000..2692f7837 --- /dev/null +++ b/docs/docs/features/chat/how-to-customize.mdx @@ -0,0 +1,7 @@ +There are a number of different ways to customize Chat: + +- Add a `rules` block to give the model persistent instructions through the system prompt +- Configure `@Codebase` +- Configure `@Docs` +- [Build your own context provider](/guides/build-your-own-context-provider) +- [Create a custom code RAG](/guides/custom-code-rag) diff --git a/docs/docs/features/chat/model-setup.mdx b/docs/docs/features/chat/model-setup.mdx new file mode 100644 index 000000000..2b762ec64 --- /dev/null +++ b/docs/docs/features/chat/model-setup.mdx @@ -0,0 +1,19 @@ +We recommend setting up a model for the best experience. + +## Recommended Models + +Here's our primary model recommendation: + +**Claude 3.5 Sonnet** from Anthropic + +- [Add Claude 3.5 Sonnet to your assistant from the hub](https://hub.continue.dev/anthropic/claude-3-5-sonnet-20241022) +- Get your API key from the [Anthropic console](https://console.anthropic.com/) + +Other top models to consider: + +- [GPT-4o from OpenAI](https://hub.continue.dev/openai/gpt-4o) +- [Grok-2 from xAI](https://hub.continue.dev/xai/grok-2) +- [Gemini 2.0 Flash from Google](https://hub.continue.dev/google/gemini-2.0-flash) +- [Llama 3.1 8b from Meta (local)](https://hub.continue.dev/ollama/llama3.1) + +For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model). diff --git a/docs/docs/features/edit/context-selection.mdx b/docs/docs/features/edit/context-selection.mdx new file mode 100644 index 000000000..a7c3459c9 --- /dev/null +++ b/docs/docs/features/edit/context-selection.mdx @@ -0,0 +1,11 @@ +## Input + +The input you provide is included in the prompt. + +## Code to Edit + +The **entire contents** of each file (the current file for Jetbrains inline Edit, the `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges. + +## Context Providers + +In VS Code Edit mode, you can use `@` to add context using [Context Providers](/customize/custom-providers), similar to [Chat](/features/chat/context-selection). Some context providers may be disabled in Edit mode. diff --git a/docs/docs/features/edit/how-to-customize.mdx b/docs/docs/features/edit/how-to-customize.mdx new file mode 100644 index 000000000..1375d7b9d --- /dev/null +++ b/docs/docs/features/edit/how-to-customize.mdx @@ -0,0 +1,9 @@ +## Setting active Edit/Apply model + +You can configure particular models from your Assistant to be used for Edit and Apply requests. + +1. Click the 3 dots above the main input +2. Click the cube icon to expand the "Models" section +3. Use the dropdowns to select models for Edit and Apply + +Learn more about the [Edit role](/customize/model-roles/edit) and [Apply role](/customize/model-roles/apply). diff --git a/docs/docs/features/edit/model-setup.mdx b/docs/docs/features/edit/model-setup.mdx new file mode 100644 index 000000000..05160853b --- /dev/null +++ b/docs/docs/features/edit/model-setup.mdx @@ -0,0 +1,14 @@ +By default, Edit uses the same model as Chat. We recommend **Claude 3.5 Sonnet** from Anthropic. + +[Explore other Edit models on the Continue Hub →](https://hub.continue.dev) + +## Apply Model + +We also recommend setting up an Apply model for the best Edit experience. + +**Recommended Apply models:** + +- [Morph v0 Fast Apply](https://hub.continue.dev) +- [Relace Instant Apply](https://hub.continue.dev) + +[Explore other Apply models on the Continue Hub →](https://hub.continue.dev) diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index a48bd4707..3e146343d 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -636,6 +636,18 @@ const config = { to: "/features/autocomplete/how-it-works", from: "/autocomplete/how-it-works", }, + { + to: "/features/autocomplete/model-setup", + from: "/autocomplete/model-setup", + }, + { + to: "/features/autocomplete/how-to-customize", + from: "/autocomplete/how-to-customize", + }, + { + to: "/features/autocomplete/context-selection", + from: "/autocomplete/context-selection", + }, { to: "/features/edit/how-it-works", from: "/edit/how-it-works", @@ -656,6 +668,43 @@ const config = { to: "/customize/json-reference", from: ["/json-reference", "/advanced/json-reference"], }, + // New feature page redirects + { + to: "/features/chat/model-setup", + from: "/chat/model-setup", + }, + { + to: "/features/chat/how-to-customize", + from: "/chat/how-to-customize", + }, + { + to: "/features/chat/context-selection", + from: "/chat/context-selection", + }, + { + to: "/features/edit/model-setup", + from: "/edit/model-setup", + }, + { + to: "/features/edit/how-to-customize", + from: "/edit/how-to-customize", + }, + { + to: "/features/edit/context-selection", + from: "/edit/context-selection", + }, + { + to: "/features/agent/model-setup", + from: "/agent/model-setup", + }, + { + to: "/features/agent/how-to-customize", + from: "/agent/how-to-customize", + }, + { + to: "/features/agent/context-selection", + from: "/agent/context-selection", + }, ], }, ], diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 6ed879f4b..0b4bb6f53 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=1.0.27 +pluginVersion=1.0.28 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt index 863bbec56..c6df8eddd 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt @@ -7,6 +7,12 @@ import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileEditorManager +class RestartContinueProcess : AnAction() { + override fun actionPerformed(e: AnActionEvent) { + val pluginService = getContinuePluginService(e.project) ?: return + pluginService.coreMessengerManager?.restart() + } +} class AcceptDiffAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index f4c3fd67f..4a84a202b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -185,18 +185,17 @@ class AutocompleteService(private val project: Project) { return } - ApplicationManager.getApplication().invokeLater { - WriteAction.run { - // Clear existing completions - hideCompletions(editor) + invokeLater { + // Clear existing completions + hideCompletions(editor) - val properties = InlayProperties() - properties.relatesToPrecedingText(true) - properties.disableSoftWrapping(true) + val properties = InlayProperties() + properties.relatesToPrecedingText(true) + properties.disableSoftWrapping(true) - val lines = completion.lines() - pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n")) - editor.addInlayElement(lines, offset, properties) + val lines = completion.lines() + pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n")) + editor.addInlayElement(lines, offset, properties) // val attributes = TextAttributes().apply { // backgroundColor = JBColor.GREEN @@ -204,7 +203,6 @@ class AutocompleteService(private val project: Project) { // val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE") // key.let { editor.colorsScheme.setAttributes(it, attributes) } // editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST) - } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 0d8e071e4..c53b4bc6e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -2,7 +2,7 @@ package com.github.continuedev.continueintellijextension.constants class MessageTypes { companion object { - val ideMessageTypes = listOf( + val IDE_MESSAGE_TYPES = listOf( "readRangeInFile", "isTelemetryEnabled", "getUniqueId", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index d419e2f7c..8ccb07838 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -1,51 +1,40 @@ package com.github.continuedev.continueintellijextension.`continue` import com.github.continuedev.continueintellijextension.constants.MessageTypes -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.github.continuedev.continueintellijextension.`continue`.process.ContinueBinaryProcess +import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler +import com.github.continuedev.continueintellijextension.`continue`.process.ContinueSocketProcess import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.services.TelemetryService import com.github.continuedev.continueintellijextension.utils.uuid import com.google.gson.Gson import com.intellij.openapi.components.service import com.intellij.openapi.project.Project -import java.io.* -import java.net.Socket -import java.nio.charset.StandardCharsets -import java.nio.file.Files -import java.nio.file.Paths -import java.nio.file.attribute.PosixFilePermission import kotlinx.coroutines.* class CoreMessenger( private val project: Project, - continueCorePath: String, private val ideProtocolClient: IdeProtocolClient, - val coroutineScope: CoroutineScope + val coroutineScope: CoroutineScope, + private val onExit: () -> Unit ) { - private var writer: Writer? = null - private var reader: BufferedReader? = null - private var process: Process? = null private val gson = Gson() private val responseListeners = mutableMapOf Unit>() - private val useTcp: Boolean = System.getenv("USE_TCP")?.toBoolean() ?: false - - private fun write(message: String) { - try { - writer?.write(message + "\r\n") - writer?.flush() - } catch (e: Exception) { - println("Error writing to Continue core: $e") - } - } + private val process = startContinueProcess() fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) { val id = messageId ?: uuid() - val message = - gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data)) + val message = gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data)) responseListeners[id] = onResponse - coroutineScope.launch(Dispatchers.IO) { - write(message) - } + process.write(message) + } + + private fun startContinueProcess(): ContinueProcessHandler { + val isTcp = System.getenv("USE_TCP")?.toBoolean() ?: false + val process = if (isTcp) + ContinueSocketProcess() + else + ContinueBinaryProcess(onExit) + return ContinueProcessHandler(coroutineScope, process, ::handleMessage) } private fun handleMessage(json: String) { @@ -55,13 +44,10 @@ class CoreMessenger( val data = responseMap["data"] // IDE listeners - if (MessageTypes.ideMessageTypes.contains(messageType)) { + if (MessageTypes.IDE_MESSAGE_TYPES.contains(messageType)) { ideProtocolClient.handleMessage(json) { data -> - val message = - gson.toJson( - mapOf("messageId" to messageId, "messageType" to messageType, "data" to data) - ) - write(message) + val message = gson.toJson(mapOf("messageId" to messageId, "messageType" to messageType, "data" to data)) + process.write(message) } } @@ -82,148 +68,7 @@ class CoreMessenger( } } - private fun setPermissions(destination: String) { - val osName = System.getProperty("os.name").toLowerCase() - if (osName.contains("mac") || osName.contains("darwin")) { - ProcessBuilder("xattr", "-dr", "com.apple.quarantine", destination).start().waitFor() - setFilePermissions(destination, "rwxr-xr-x") - } else if (osName.contains("nix") || osName.contains("nux")) { - setFilePermissions(destination, "rwxr-xr-x") - } - } - - private fun setFilePermissions(path: String, posixPermissions: String) { - val perms = HashSet() - if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ) - if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE) - if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE) - Files.setPosixFilePermissions(Paths.get(path), perms) - } - - private val exitCallbacks: MutableList<() -> Unit> = mutableListOf() - - fun onDidExit(callback: () -> Unit) { - exitCallbacks.add(callback) - } - - init { - if (useTcp) { - try { - val socket = Socket("127.0.0.1", 3000) - val writer = PrintWriter(socket.getOutputStream(), true) - this.writer = writer - val reader = BufferedReader(InputStreamReader(socket.getInputStream())) - this.reader = reader - - Thread { - try { - while (true) { - val line = reader.readLine() - if (line != null && line.isNotEmpty()) { - try { - handleMessage(line) - } catch (e: Exception) { - println("Error handling message: $line") - println(e) - } - } else { - Thread.sleep(100) - } - } - } catch (e: IOException) { - e.printStackTrace() - } finally { - try { - reader.close() - writer.close() - } catch (e: IOException) { - e.printStackTrace() - } - } - } - .start() - } catch (e: Exception) { - println("TCP Connection Error: Unable to connect to 127.0.0.1:3000") - println("Reason: ${e.message}") - e.printStackTrace() - } - } else { - // Set proper permissions synchronously - runBlocking(Dispatchers.IO) { - setPermissions(continueCorePath) - } - - // Start the subprocess - val processBuilder = - ProcessBuilder(continueCorePath).directory(File(continueCorePath).parentFile) - process = processBuilder.start() - - val outputStream = process!!.outputStream - val inputStream = process!!.inputStream - - writer = OutputStreamWriter(outputStream, StandardCharsets.UTF_8) - reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) - - process!!.onExit().thenRun { - exitCallbacks.forEach { it() } - var err = process?.errorStream?.bufferedReader()?.readText()?.trim() - if (err != null) { - // There are often "⚡️Done in Xms" messages, and we want everything after the last one - val delimiter = "⚡ Done in" - val doneIndex = err.lastIndexOf(delimiter) - if (doneIndex != -1) { - err = err.substring(doneIndex + delimiter.length) - } - } - - println("Core process exited with output: $err") - - // Log the cause of the failure - val telemetryService = service() - telemetryService.capture("jetbrains_core_exit", mapOf("error" to err)) - - // Clean up all resources - writer?.close() - reader?.close() - process?.destroy() - } - - coroutineScope.launch(Dispatchers.IO) { - try { - while (true) { - val line = reader?.readLine() - if (line != null && line.isNotEmpty()) { - try { - handleMessage(line) - } catch (e: Exception) { - println("Error handling message: $line") - println(e) - } - } else { - delay(100) - } - } - } catch (e: IOException) { - e.printStackTrace() - } finally { - try { - reader?.close() - writer?.close() - outputStream.close() - inputStream.close() - process?.destroy() - } catch (e: IOException) { - e.printStackTrace() - } - } - } - } - } - fun killSubProcess() { - process?.isAlive?.let { - exitCallbacks.clear() - process?.destroy() - } + process.close() } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt index 7f1272dbf..3dbf9c2d5 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt @@ -2,53 +2,50 @@ package com.github.continuedev.continueintellijextension.`continue` import com.github.continuedev.continueintellijextension.services.TelemetryService import com.github.continuedev.continueintellijextension.utils.castNestedOrNull -import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID import com.intellij.openapi.components.service +import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project -import kotlinx.coroutines.* +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch class CoreMessengerManager( private val project: Project, private val ideProtocolClient: IdeProtocolClient, private val coroutineScope: CoroutineScope ) { - - var coreMessenger: CoreMessenger? = null + var coreMessenger: CoreMessenger = createCoreMessenger() private var lastBackoffInterval = 0.5 + private val log = Logger.getInstance(CoreMessengerManager::class.java) init { + setupAnonymousTelemetry() + } + + fun restart() { coroutineScope.launch { - val continueBinaryPath = getContinueBinaryPath() - setupCoreMessenger(continueBinaryPath) + try { + coreMessenger.killSubProcess() + lastBackoffInterval *= 2 + log.warn("Continue process exited, retrying in $lastBackoffInterval seconds") + delay((lastBackoffInterval * 1000).toLong()) + coreMessenger = createCoreMessenger() + } catch (e: Exception) { + service().capture("jetbrains_core_start_error", mapOf("error" to e)) + } } } - private fun setupCoreMessenger(continueCorePath: String) { - try { - coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope) + private fun createCoreMessenger() = + CoreMessenger(project, ideProtocolClient, coroutineScope, ::restart) - coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> - val allowAnonymousTelemetry = response.castNestedOrNull("content", "result", "config", "allowAnonymousTelemetry") - - val telemetryService = service() - if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) { - telemetryService.setup(getMachineUniqueID()) - } - } - - // On exit, use exponential backoff to create another CoreMessenger - coreMessenger?.onDidExit { - lastBackoffInterval *= 2 - println("CoreMessenger exited, retrying in $lastBackoffInterval seconds") - Thread.sleep((lastBackoffInterval * 1000).toLong()) - setupCoreMessenger(continueCorePath) - } - } catch (err: Throwable) { - val telemetryService = service() - telemetryService.capture("jetbrains_core_start_error", mapOf("error" to err)) - - err.printStackTrace() + private fun setupAnonymousTelemetry() { + coreMessenger.request("config/getSerializedProfileInfo", null, null) { response -> + val allowAnonymousTelemetry = + response.castNestedOrNull("content", "result", "config", "allowAnonymousTelemetry") + if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) + service().setup(getMachineUniqueID()) } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 2dfc3e3e1..e1b6624d1 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -495,7 +495,7 @@ class IntelliJIDE( // Create the list of IndexTag objects return workspaceDirs.mapIndexed { index, directory -> - IndexTag(directory, branches[index], artifactId) + IndexTag(artifactId, branches[index], directory) } } @@ -622,4 +622,5 @@ class IntelliJIDE( return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray() } -} \ No newline at end of file +} + diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt new file mode 100644 index 000000000..eb45cc4da --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt @@ -0,0 +1,81 @@ +package com.github.continuedev.continueintellijextension.`continue`.process + +import com.github.continuedev.continueintellijextension.services.TelemetryService +import com.github.continuedev.continueintellijextension.utils.OS +import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath +import com.github.continuedev.continueintellijextension.utils.getOS +import com.intellij.openapi.components.service +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import java.io.File +import java.io.InputStream +import java.io.OutputStream +import java.nio.file.Files +import java.nio.file.Paths +import java.nio.file.attribute.PosixFilePermission + +class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess { + + private val process = startBinaryProcess() + override val input: InputStream = process.inputStream + override val output: OutputStream = process.outputStream + + override fun close() = + process.destroy() + + private fun startBinaryProcess(): Process { + val path = getContinueBinaryPath() + runBlocking(Dispatchers.IO) { + setPermissions() + } + return ProcessBuilder(path).directory(File(path).parentFile) + .start() + .apply { onExit().thenRun(onExit).thenRun { reportErrorTelemetry() } } + } + + + private fun reportErrorTelemetry() { + var err = process.errorStream?.bufferedReader()?.readText()?.trim() + if (err != null) { + // There are often "⚡️Done in Xms" messages, and we want everything after the last one + val delimiter = "⚡ Done in" + val doneIndex = err.lastIndexOf(delimiter) + if (doneIndex != -1) { + err = err.substring(doneIndex + delimiter.length) + } + } + + println("Core process exited with output: $err") + + val telemetryService = service() + telemetryService.capture("jetbrains_core_exit", mapOf("error" to err)) + } + + private companion object { + + private fun setPermissions() { + val os = getOS() + when (os) { + OS.MAC -> setMacOsPermissions() + OS.WINDOWS -> {} + OS.LINUX -> elevatePermissions() + } + } + + private fun setMacOsPermissions() { + ProcessBuilder("xattr", "-dr", "com.apple.quarantine", getContinueBinaryPath()).start().waitFor() + elevatePermissions() + } + + private fun elevatePermissions() { + val path = getContinueBinaryPath() + val permissions = setOf( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE + ) + Files.setPosixFilePermissions(Paths.get(path), permissions) + } + } + +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcess.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcess.kt new file mode 100644 index 000000000..3e80f6bc0 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcess.kt @@ -0,0 +1,13 @@ +package com.github.continuedev.continueintellijextension.`continue`.process + +import java.io.InputStream +import java.io.OutputStream + +interface ContinueProcess { + + val input: InputStream + val output: OutputStream + + fun close() + +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt new file mode 100644 index 000000000..68ec83bf6 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt @@ -0,0 +1,61 @@ +package com.github.continuedev.continueintellijextension.`continue`.process + +import com.github.continuedev.continueintellijextension.error.ContinueErrorService +import com.intellij.openapi.components.service +import kotlinx.coroutines.* +import kotlinx.coroutines.channels.Channel +import java.io.BufferedReader +import java.io.IOException +import java.io.InputStreamReader +import java.io.OutputStreamWriter + +class ContinueProcessHandler( + parentScope: CoroutineScope, + private val process: ContinueProcess, + handleMessage: (String) -> (Unit) +) { + private val innerJob = Job() + private val scope = CoroutineScope(parentScope.coroutineContext + innerJob) + private val pendingWrites = Channel(Channel.UNLIMITED) + private val writer = OutputStreamWriter(process.output) + private val reader = BufferedReader(InputStreamReader(process.input)) + + init { + scope.launch(Dispatchers.IO) { + try { + while (isActive) { + val line = reader.readLine() + if (line != null && line.isNotEmpty()) { + try { + handleMessage(line) + } catch (e: Exception) { + service().report(e, "Error handling message: $line") + } + } else + delay(100) + } + } catch (e: IOException) { + service().report(e) + } + } + scope.launch(Dispatchers.IO) { + for (message in pendingWrites) { + writer.write(message) + writer.write("\r\n") + writer.flush() + } + } + } + + fun write(message: String) = + pendingWrites.trySend(message) + + fun close() { + innerJob.cancel() + scope.launch(Dispatchers.IO) { + reader.close() + writer.close() + process.close() + } + } +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueSocketProcess.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueSocketProcess.kt new file mode 100644 index 000000000..343566841 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueSocketProcess.kt @@ -0,0 +1,16 @@ +package com.github.continuedev.continueintellijextension.`continue`.process + +import java.io.InputStream +import java.io.OutputStream +import java.net.Socket + +class ContinueSocketProcess : ContinueProcess { + + private val socket = Socket("127.0.0.1", 3000) + override val input: InputStream = socket.inputStream + override val output: OutputStream = socket.outputStream + + override fun close() = + socket.close() + +} diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index aa9a81989..a0ec2afe7 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -70,6 +70,13 @@ + + + + diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueProcessHandlerTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueProcessHandlerTest.kt new file mode 100644 index 000000000..09678ae43 --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueProcessHandlerTest.kt @@ -0,0 +1,51 @@ +package com.github.continuedev.continueintellijextension.unit + +import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcess +import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.joinAll +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.RepeatedTest +import java.io.InputStream +import java.io.OutputStream + +class ContinueProcessHandlerTest { + + @RepeatedTest(5) + fun `test concurrent writes with queue`() = runTest { + val process = StringContinueProcess() + val handler = ContinueProcessHandler(this, process) {} + + (0..100).map { i -> launch(Dispatchers.Default) { handler.write("message number $i") } } + .joinAll() + + handler.close() + + // assert all message lines are present (order is not important) + val lines = process.string.split("\r\n").filter { it.isNotBlank() } + for (i in 0..100) + Assertions.assertTrue(lines.contains("message number $i")) + + // note: this test will fail if the handler writes messages directly to the output stream + // this problem can be easily reproduced by removing the channel from the handler code + } + + class StringContinueProcess : ContinueProcess { + val string = StringBuilder() + override val input: InputStream = InputStream.nullInputStream() + override val output: OutputStream = object : OutputStream() { + override fun write(b: Int) { + string.append(b.toChar()) + } + + override fun write(b: ByteArray, off: Int, len: Int) { + string.append(String(b, off, len)) + } + } + + override fun close() { + } + } +} diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index a709266ec..8eae48307 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -357,20 +357,6 @@ describe("GUI Test", () => { await messageInput.sendKeys(Key.ENTER); await messageInput.sendKeys(Key.ENTER); - // Open the context items peek - const contextItemsPeek = await GUISelectors.getContextItemsPeek(view); - await contextItemsPeek.click(); - - await TestUtils.waitForSuccess(async () => { - const firstContextItemInPeek = - await GUISelectors.getFirstContextItemsPeekItem(view); - await firstContextItemInPeek.click(); - - // Check that item is there with correct name - const description = await firstContextItemInPeek.getText(); - expect(description).to.include("Terminal"); - }); - // Check that the contents match what we expect (repeated back by the mock LLM) await TestUtils.waitForSuccess(() => { return GUISelectors.getThreadMessageByText( diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 0f87e013c..6936cc88b 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.55", + "version": "1.1.59", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.55", + "version": "1.1.59", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -173,6 +173,8 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", + "@shikijs/colorized-brackets": "^3.7.0", + "@shikijs/transformers": "^3.7.0", "@types/diff": "^7.0.1", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 7d5c2a12a..f7c6b6ea5 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.57", + "version": "1.1.60", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/scripts/package-all.js b/extensions/vscode/scripts/package-all.js index 0a49403d2..440924bed 100644 --- a/extensions/vscode/scripts/package-all.js +++ b/extensions/vscode/scripts/package-all.js @@ -11,7 +11,7 @@ const PLATFORMS = [ const args = process.argv.slice(2); const isPreRelease = args.includes("--pre-release"); -(async () => { +void (async () => { for (const i in PLATFORMS) { const platform = PLATFORMS[i]; const pkgCommand = isPreRelease @@ -23,4 +23,5 @@ const isPreRelease = args.includes("--pre-release"); }); execSync(pkgCommand, { stdio: "inherit" }); } + process.exit(0); })(); diff --git a/extensions/vscode/scripts/prepackage-cross-platform.js b/extensions/vscode/scripts/prepackage-cross-platform.js index cb3c3c582..640a81380 100644 --- a/extensions/vscode/scripts/prepackage-cross-platform.js +++ b/extensions/vscode/scripts/prepackage-cross-platform.js @@ -6,14 +6,17 @@ const fs = require("fs"); const path = require("path"); + const { rimrafSync } = require("rimraf"); + const { validateFilesPresent, autodetectPlatformAndArch, } = require("../../../scripts/util/index"); + +const { generateAndCopyConfigYamlSchema } = require("./generate-copy-config"); +const { npmInstall } = require("./npm-install"); const { - copyConfigSchema, - installNodeModules, buildGui, copyOnnxRuntimeFromNodeModules, copyTreeSitterWasms, @@ -48,10 +51,10 @@ if (args[2] === "--target") { let os; let arch; -if (!target) { - [os, arch] = autodetectPlatformAndArch(); -} else { +if (target) { [os, arch] = target.split("-"); +} else { + [os, arch] = autodetectPlatformAndArch(); } if (os === "alpine") { @@ -71,26 +74,14 @@ function ghAction() { return !!process.env.GITHUB_ACTIONS; } -function isArm() { - return ( - target === "darwin-arm64" || - target === "linux-arm64" || - target === "win32-arm64" - ); -} - -function isWin() { - return target?.startsWith("win"); -} - async function package(target, os, arch, exe) { console.log("[info] Packaging extension for target ", target); // Copy config_schema to intellij - copyConfigSchema(); + await generateAndCopyConfigYamlSchema(); // Install node_modules - installNodeModules(); + await npmInstall(); // Build gui and copy to extensions await buildGui(ghAction()); @@ -214,4 +205,5 @@ async function package(target, os, arch, exe) { void (async () => { await package(target, os, arch, exe); + process.exit(0); })(); diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 68c3436e8..339f9e84b 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -174,9 +174,12 @@ export class VerticalDiffHandler implements vscode.Disposable { // Clear deletion buffer await this.insertDeletionBuffer(); - await this.reapplyWithMyersDiff(diffLines); + const myersDiffs = await this.reapplyWithMyersDiff(diffLines); - const range = new vscode.Range(this.startLine, 0, this.startLine, 0); + // Scroll to the first diff + const scrollToLine = + this.getFirstChangedLine(myersDiffs) ?? this.startLine; + const range = new vscode.Range(scrollToLine, 0, scrollToLine, 0); this.editor.revealRange(range, vscode.TextEditorRevealType.Default); this.options.onStatusUpdate( @@ -370,6 +373,8 @@ export class VerticalDiffHandler implements vscode.Disposable { this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks); this.refreshCodeLens(); + + return myersDiffs; } private async insertDeletionBuffer() { @@ -550,4 +555,17 @@ export class VerticalDiffHandler implements vscode.Disposable { this.refreshCodeLens(); } + + /** + * Gets the first line number that was changed in a diff + */ + private getFirstChangedLine(diff: DiffLine[]): number | null { + for (let i = 0; i < diff.length; i++) { + const item = diff[i]; + if (item.type === "old" || item.type === "new") { + return this.startLine + i; + } + } + return null; + } } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index b59abe665..f8914f31e 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -77,6 +77,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { { promise: Promise; cancel: EventEmitter } >(); private _refreshInterval: NodeJS.Timeout | null = null; + private _isRefreshing = false; private static EXPIRATION_TIME_MS = 1000 * 60 * 15; // 15 minutes private static REFRESH_INTERVAL_MS = 1000 * 60 * 10; // 10 minutes @@ -100,11 +101,11 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { this.secretStorage = new SecretStorage(context); // Immediately refresh any existing sessions - this.refreshSessions(); + void this.refreshSessions(); // Set up a regular interval to refresh tokens this._refreshInterval = setInterval(() => { - this.refreshSessions(); + void this.refreshSessions(); }, WorkOsAuthProvider.REFRESH_INTERVAL_MS); } @@ -182,10 +183,18 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { } async refreshSessions() { + // Prevent concurrent refresh operations + if (this._isRefreshing) { + return; + } + try { + this._isRefreshing = true; await this._refreshSessions(); } catch (e) { console.error(`Error refreshing sessions: ${e}`); + } finally { + this._isRefreshing = false; } } @@ -198,12 +207,9 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { const finalSessions = []; for (const session of sessions) { try { - // For expired tokens, don't use retries - if refresh fails, we drop the session - const refreshMethod = this.jwtIsExpiredOrInvalid(session.accessToken) - ? this._refreshSession.bind(this) // Direct refresh for expired tokens - : this._refreshSessionWithRetry.bind(this); // Retry for valid tokens - - const newSession = await refreshMethod(session.refreshToken); + const newSession = await this._refreshSessionWithRetry( + session.refreshToken, + ); finalSessions.push({ ...session, accessToken: newSession.accessToken, @@ -232,7 +238,6 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { private async _refreshSessionWithRetry( refreshToken: string, attempt = 1, - maxAttempts = 3, baseDelay = 1000, ): Promise<{ accessToken: string; @@ -242,30 +247,25 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { try { return await this._refreshSession(refreshToken); } catch (error: any) { - // Don't retry for auth errors (401 Unauthorized) or if we've reached max attempts + // Don't retry for auth errors if ( error.message?.includes("401") || error.message?.includes("Invalid refresh token") || - error.message?.includes("Unauthorized") || - attempt >= maxAttempts + error.message?.includes("Unauthorized") ) { throw error; } // For network errors or transient server issues, retry with backoff // Calculate exponential backoff delay with jitter - const delay = - baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5); + const delay = Math.min( + baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5), + 2 * 60 * 1000, // 2 minutes + ); - // Schedule retry after delay return new Promise((resolve, reject) => { setTimeout(() => { - this._refreshSessionWithRetry( - refreshToken, - attempt + 1, - maxAttempts, - baseDelay, - ) + this._refreshSessionWithRetry(refreshToken, attempt + 1, baseDelay) .then(resolve) .catch(reject); }, delay); @@ -360,7 +360,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { return session; } catch (e) { - window.showErrorMessage(`Sign in failed: ${e}`); + void window.showErrorMessage(`Sign in failed: ${e}`); throw e; } } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts index 55cac92df..f0a7b746d 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts @@ -641,7 +641,7 @@ it("should preserve valid tokens during network errors by retrying", async () => } }); -it("should remove expired tokens when refresh fails", async () => { +it("should remove expired tokens when refresh fails with a 401 error", async () => { // Mock Date.now to return a time that makes tokens appear expired const originalDateNow = Date.now; const futureTime = Date.now() + 7200000; // 2 hours in the future @@ -675,7 +675,7 @@ it("should remove expired tokens when refresh fails", async () => { global.setInterval = vi.fn().mockReturnValue(123 as any); // Refresh will fail with network error - fetchMock.mockRejectedValueOnce(new Error("Network error")); + fetchMock.mockRejectedValueOnce(new Error("401")); // Setup storage mockSecretStorageGet.mockResolvedValue(JSON.stringify([expiredSession])); diff --git a/extensions/vscode/src/util/editLoggingUtils.ts b/extensions/vscode/src/util/editLoggingUtils.ts index 90992db2e..4ef1fabc6 100644 --- a/extensions/vscode/src/util/editLoggingUtils.ts +++ b/extensions/vscode/src/util/editLoggingUtils.ts @@ -3,6 +3,9 @@ import { AutocompleteCodeSnippet } from "core/autocomplete/snippets/types"; import { GetLspDefinitionsFunction } from "core/autocomplete/types"; import { ConfigHandler } from "core/config/ConfigHandler"; import { RecentlyEditedRange } from "core/nextEdit/types"; +import { getContinueGlobalPath, isFileWithinFolder } from "core/util/paths"; +import fs from "fs"; +import { resolve } from "path"; import * as vscode from "vscode"; import { ContinueCompletionProvider } from "../autocomplete/completionProvider"; @@ -18,23 +21,33 @@ export const getBeforeCursorPos = (range: Range, activePos: Position) => { } }; -const getWorkspaceDirInfo = async ( - event: vscode.TextDocumentChangeEvent, - ide: IDE, -) => { - // gets the workspace dir uri and checks if it's the open-source continue repo +const isEditLoggingAllowed = async (editedFileURI: string) => { + const globalContinuePath = getContinueGlobalPath(); + const editLogDirsPath = resolve(globalContinuePath, ".editlogdirs"); + + try { + const fileContent = await fs.promises.readFile(editLogDirsPath, "utf-8"); + const stringItems = fileContent + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0); + + return stringItems.some((dir) => isFileWithinFolder(editedFileURI, dir)); + } catch (error) { + return false; + } +}; + +const getWorkspaceDirUri = async (event: vscode.TextDocumentChangeEvent) => { const workspaceFolder = vscode.workspace.getWorkspaceFolder( event.document.uri, ); if (!workspaceFolder) { return false; } + const workspaceDirUri = workspaceFolder.uri.toString(); - const repoName = await ide.getRepoName(workspaceDirUri); - return { - workspaceDirUri: workspaceDirUri, - isContinueRepo: repoName === "continuedev/continue", - }; + return workspaceDirUri; }; export const handleTextDocumentChange = async ( @@ -52,10 +65,10 @@ export const handleTextDocumentChange = async ( if (!editor) return; if (event.contentChanges.length === 0) return; - // Ensure that loggin will only happen in the open-source continue repo - const workspaceDirInfo = await getWorkspaceDirInfo(event, ide); - if (!workspaceDirInfo) return; - // if (!workspaceDirInfo.isContinueRepo) return; + // Ensure that logging will only happen in the open-source continue repo + const workspaceDirUri = await getWorkspaceDirUri(event); + if (!workspaceDirUri) return; + if (!(await isEditLoggingAllowed(event.document.uri.toString()))) return; const activeCursorPos = editor.selection.active; const editActions: RangeInFileWithNextEditInfo[] = changes.map((change) => ({ @@ -68,7 +81,7 @@ export const handleTextDocumentChange = async ( editText: change.text, beforeCursorPos: getBeforeCursorPos(change.range, activeCursorPos), afterCursorPos: activeCursorPos as Position, - workspaceDir: workspaceDirInfo.workspaceDirUri, + workspaceDir: workspaceDirUri, })); let recentlyEditedRanges: RecentlyEditedRange[] = []; diff --git a/gui/package-lock.json b/gui/package-lock.json index 8c53ca7ce..d611543e2 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -10,6 +10,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", + "@panzoom/panzoom": "^4.6.0", "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", "@tiptap/extension-document": "^2.3.2", @@ -34,6 +35,7 @@ "handlebars": "^4.7.8", "lodash": "^4.17.21", "lowlight": "^3.3.0", + "mermaid": "^11.6.0", "minisearch": "^7.0.2", "mustache": "^4.2.0", "posthog-js": "^1.130.1", @@ -182,6 +184,8 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", + "@shikijs/colorized-brackets": "^3.7.0", + "@shikijs/transformers": "^3.7.0", "@types/diff": "^7.0.1", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", @@ -216,7 +220,7 @@ }, "../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.0.95", + "version": "1.0.96", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -281,6 +285,34 @@ "node": ">=6.0.0" } }, + "node_modules/@antfu/install-pkg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-1.1.0.tgz", + "integrity": "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==", + "license": "MIT", + "dependencies": { + "package-manager-detector": "^1.3.0", + "tinyexec": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@antfu/install-pkg/node_modules/tinyexec": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.1.tgz", + "integrity": "sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw==", + "license": "MIT" + }, + "node_modules/@antfu/utils": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/@antfu/utils/-/utils-8.1.1.tgz", + "integrity": "sha512-Mex9nXf9vR6AhcXmMrlz/HVgYYZpVGJ6YlPgwl7UnaFpnshXs6EK/oa5Gpf3CzENMjkvEx2tQtntGnb7UtSTOQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, "node_modules/@babel/code-frame": { "version": "7.26.2", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz", @@ -591,6 +623,51 @@ "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", "dev": true }, + "node_modules/@braintree/sanitize-url": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-7.1.1.tgz", + "integrity": "sha512-i1L7noDNxtFyL5DmZafWy1wRVhGehQmzZaz1HiN5e7iylJMSZR7ekOV7NsIqa5qBldlLrsKv4HbgFUVlQrz8Mw==", + "license": "MIT" + }, + "node_modules/@chevrotain/cst-dts-gen": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-11.0.3.tgz", + "integrity": "sha512-BvIKpRLeS/8UbfxXxgC33xOumsacaeCKAjAeLyOn7Pcp95HiRbrpl14S+9vaZLolnbssPIUuiUd8IvgkRyt6NQ==", + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/gast": "11.0.3", + "@chevrotain/types": "11.0.3", + "lodash-es": "4.17.21" + } + }, + "node_modules/@chevrotain/gast": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-11.0.3.tgz", + "integrity": "sha512-+qNfcoNk70PyS/uxmj3li5NiECO+2YKZZQMbmjTqRI3Qchu8Hig/Q9vgkHpI3alNjr7M+a2St5pw5w5F6NL5/Q==", + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/types": "11.0.3", + "lodash-es": "4.17.21" + } + }, + "node_modules/@chevrotain/regexp-to-ast": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-11.0.3.tgz", + "integrity": "sha512-1fMHaBZxLFvWI067AVbGJav1eRY7N8DDvYCTwGBiE/ytKBgP8azTdgyrKyWZ9Mfh09eHWb5PgTSO8wi7U824RA==", + "license": "Apache-2.0" + }, + "node_modules/@chevrotain/types": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-11.0.3.tgz", + "integrity": "sha512-gsiM3G8b58kZC2HaWR50gu6Y1440cHiJ+i3JUvcp/35JchYejb2+5MVeJK0iKThYpAa/P2PYFV4hoi44HD+aHQ==", + "license": "Apache-2.0" + }, + "node_modules/@chevrotain/utils": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-11.0.3.tgz", + "integrity": "sha512-YslZMgtJUyuMbZ+aKvfF3x1f5liK4mWNxghFRv7jqRR9C3R3fAOGTTKvxXDa2Y1s9zSbcpuO0cAxDYsc9SrXoQ==", + "license": "Apache-2.0" + }, "node_modules/@continuedev/config-yaml": { "resolved": "../packages/config-yaml", "link": true @@ -1279,6 +1356,57 @@ "deprecated": "Use @eslint/object-schema instead", "dev": true }, + "node_modules/@iconify/types": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz", + "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==", + "license": "MIT" + }, + "node_modules/@iconify/utils": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@iconify/utils/-/utils-2.3.0.tgz", + "integrity": "sha512-GmQ78prtwYW6EtzXRU1rY+KwOKfz32PD7iJh6Iyqw68GiKuoZ2A6pRtzWONz5VQJbp50mEjXh/7NkumtrAgRKA==", + "license": "MIT", + "dependencies": { + "@antfu/install-pkg": "^1.0.0", + "@antfu/utils": "^8.1.0", + "@iconify/types": "^2.0.0", + "debug": "^4.4.0", + "globals": "^15.14.0", + "kolorist": "^1.8.0", + "local-pkg": "^1.0.0", + "mlly": "^1.7.4" + } + }, + "node_modules/@iconify/utils/node_modules/debug": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@iconify/utils/node_modules/globals": { + "version": "15.15.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-15.15.0.tgz", + "integrity": "sha512-7ACyT3wmyp3I61S4fG682L0VA2RGD9otkqGJIwNUMF1SWUombIIk+af1unuDYgMm082aHYwD+mzJvv9Iu8dsgg==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", @@ -1430,6 +1558,15 @@ "unist-util-is": "^3.0.0" } }, + "node_modules/@mermaid-js/parser": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-0.6.0.tgz", + "integrity": "sha512-7DNESgpyZ5WG1SIkrYafVBhWmImtmQuoxOO1lawI3gQYWxBX3v1FW3IyuuRfKJAO06XrZR71W0Kif5VEGGd4VA==", + "license": "MIT", + "dependencies": { + "langium": "3.3.1" + } + }, "node_modules/@mole-inc/bin-wrapper": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/@mole-inc/bin-wrapper/-/bin-wrapper-8.0.1.tgz", @@ -1772,6 +1909,12 @@ "node": ">= 8" } }, + "node_modules/@panzoom/panzoom": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@panzoom/panzoom/-/panzoom-4.6.0.tgz", + "integrity": "sha512-3KxkY1lNKFn98fW5ZFR6vV0YzsXj3I4EQDyFWSXME6/cic86eSS7VjuqIjrA3PEpySo0r5fFtlX8eYCt4JPUFQ==", + "license": "MIT" + }, "node_modules/@pkgjs/parseargs": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", @@ -3137,6 +3280,259 @@ "@types/responselike": "^1.0.0" } }, + "node_modules/@types/d3": { + "version": "7.4.3", + "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz", + "integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==", + "license": "MIT", + "dependencies": { + "@types/d3-array": "*", + "@types/d3-axis": "*", + "@types/d3-brush": "*", + "@types/d3-chord": "*", + "@types/d3-color": "*", + "@types/d3-contour": "*", + "@types/d3-delaunay": "*", + "@types/d3-dispatch": "*", + "@types/d3-drag": "*", + "@types/d3-dsv": "*", + "@types/d3-ease": "*", + "@types/d3-fetch": "*", + "@types/d3-force": "*", + "@types/d3-format": "*", + "@types/d3-geo": "*", + "@types/d3-hierarchy": "*", + "@types/d3-interpolate": "*", + "@types/d3-path": "*", + "@types/d3-polygon": "*", + "@types/d3-quadtree": "*", + "@types/d3-random": "*", + "@types/d3-scale": "*", + "@types/d3-scale-chromatic": "*", + "@types/d3-selection": "*", + "@types/d3-shape": "*", + "@types/d3-time": "*", + "@types/d3-time-format": "*", + "@types/d3-timer": "*", + "@types/d3-transition": "*", + "@types/d3-zoom": "*" + } + }, + "node_modules/@types/d3-array": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.1.tgz", + "integrity": "sha512-Y2Jn2idRrLzUfAKV2LyRImR+y4oa2AntrgID95SHJxuMUrkNXmanDSed71sRNZysveJVt1hLLemQZIady0FpEg==", + "license": "MIT" + }, + "node_modules/@types/d3-axis": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz", + "integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==", + "license": "MIT", + "dependencies": { + "@types/d3-selection": "*" + } + }, + "node_modules/@types/d3-brush": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz", + "integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==", + "license": "MIT", + "dependencies": { + "@types/d3-selection": "*" + } + }, + "node_modules/@types/d3-chord": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz", + "integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==", + "license": "MIT" + }, + "node_modules/@types/d3-color": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", + "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", + "license": "MIT" + }, + "node_modules/@types/d3-contour": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz", + "integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==", + "license": "MIT", + "dependencies": { + "@types/d3-array": "*", + "@types/geojson": "*" + } + }, + "node_modules/@types/d3-delaunay": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.4.tgz", + "integrity": "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==", + "license": "MIT" + }, + "node_modules/@types/d3-dispatch": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.6.tgz", + "integrity": "sha512-4fvZhzMeeuBJYZXRXrRIQnvUYfyXwYmLsdiN7XXmVNQKKw1cM8a5WdID0g1hVFZDqT9ZqZEY5pD44p24VS7iZQ==", + "license": "MIT" + }, + "node_modules/@types/d3-drag": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz", + "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==", + "license": "MIT", + "dependencies": { + "@types/d3-selection": "*" + } + }, + "node_modules/@types/d3-dsv": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz", + "integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==", + "license": "MIT" + }, + "node_modules/@types/d3-ease": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz", + "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==", + "license": "MIT" + }, + "node_modules/@types/d3-fetch": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz", + "integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==", + "license": "MIT", + "dependencies": { + "@types/d3-dsv": "*" + } + }, + "node_modules/@types/d3-force": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz", + "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==", + "license": "MIT" + }, + "node_modules/@types/d3-format": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz", + "integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==", + "license": "MIT" + }, + "node_modules/@types/d3-geo": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz", + "integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==", + "license": "MIT", + "dependencies": { + "@types/geojson": "*" + } + }, + "node_modules/@types/d3-hierarchy": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz", + "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==", + "license": "MIT" + }, + "node_modules/@types/d3-interpolate": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", + "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", + "license": "MIT", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@types/d3-path": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz", + "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==", + "license": "MIT" + }, + "node_modules/@types/d3-polygon": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz", + "integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==", + "license": "MIT" + }, + "node_modules/@types/d3-quadtree": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz", + "integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==", + "license": "MIT" + }, + "node_modules/@types/d3-random": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.3.tgz", + "integrity": "sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==", + "license": "MIT" + }, + "node_modules/@types/d3-scale": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz", + "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==", + "license": "MIT", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@types/d3-scale-chromatic": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz", + "integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==", + "license": "MIT" + }, + "node_modules/@types/d3-selection": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz", + "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==", + "license": "MIT" + }, + "node_modules/@types/d3-shape": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz", + "integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==", + "license": "MIT", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@types/d3-time": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz", + "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==", + "license": "MIT" + }, + "node_modules/@types/d3-time-format": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-4.0.3.tgz", + "integrity": "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==", + "license": "MIT" + }, + "node_modules/@types/d3-timer": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz", + "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==", + "license": "MIT" + }, + "node_modules/@types/d3-transition": { + "version": "3.0.9", + "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz", + "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==", + "license": "MIT", + "dependencies": { + "@types/d3-selection": "*" + } + }, + "node_modules/@types/d3-zoom": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz", + "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==", + "license": "MIT", + "dependencies": { + "@types/d3-interpolate": "*", + "@types/d3-selection": "*" + } + }, "node_modules/@types/debug": { "version": "4.1.12", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz", @@ -3168,6 +3564,12 @@ "@types/estree": "*" } }, + "node_modules/@types/geojson": { + "version": "7946.0.16", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "license": "MIT" + }, "node_modules/@types/hast": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", @@ -3337,6 +3739,13 @@ "csstype": "^3.0.2" } }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT", + "optional": true + }, "node_modules/@types/unist": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", @@ -3702,7 +4111,6 @@ "version": "8.14.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", - "dev": true, "bin": { "acorn": "bin/acorn" }, @@ -4483,6 +4891,32 @@ "node": ">= 16" } }, + "node_modules/chevrotain": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-11.0.3.tgz", + "integrity": "sha512-ci2iJH6LeIkvP9eJW6gpueU8cnZhv85ELY8w8WiFtNjMHA5ad6pQLaJo9mEly/9qUyCpvqX8/POVUTf18/HFdw==", + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/cst-dts-gen": "11.0.3", + "@chevrotain/gast": "11.0.3", + "@chevrotain/regexp-to-ast": "11.0.3", + "@chevrotain/types": "11.0.3", + "@chevrotain/utils": "11.0.3", + "lodash-es": "4.17.21" + } + }, + "node_modules/chevrotain-allstar": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/chevrotain-allstar/-/chevrotain-allstar-0.3.1.tgz", + "integrity": "sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==", + "license": "MIT", + "dependencies": { + "lodash-es": "^4.17.21" + }, + "peerDependencies": { + "chevrotain": "^11.0.0" + } + }, "node_modules/chokidar": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", @@ -4572,6 +5006,12 @@ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", "dev": true }, + "node_modules/confbox": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.2.tgz", + "integrity": "sha512-1NB+BKqhtNipMsov4xI/NnhCKp9XG9NamYp5PVm9klAT0fsrNPjaFICsCFhNhwZJKNh7zB/3q8qXz0E9oaMNtQ==", + "license": "MIT" + }, "node_modules/content-disposition": { "version": "0.5.4", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", @@ -4594,6 +5034,15 @@ "resolved": "../core", "link": true }, + "node_modules/cose-base": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-1.0.3.tgz", + "integrity": "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==", + "license": "MIT", + "dependencies": { + "layout-base": "^1.0.0" + } + }, "node_modules/crelt": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz", @@ -4668,6 +5117,514 @@ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==" }, + "node_modules/cytoscape": { + "version": "3.32.0", + "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.32.0.tgz", + "integrity": "sha512-5JHBC9n75kz5851jeklCPmZWcg3hUe6sjqJvyk3+hVqFaKcHwHgxsjeN1yLmggoUc6STbtm9/NQyabQehfjvWQ==", + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/cytoscape-cose-bilkent": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cytoscape-cose-bilkent/-/cytoscape-cose-bilkent-4.1.0.tgz", + "integrity": "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==", + "license": "MIT", + "dependencies": { + "cose-base": "^1.0.0" + }, + "peerDependencies": { + "cytoscape": "^3.2.0" + } + }, + "node_modules/cytoscape-fcose": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cytoscape-fcose/-/cytoscape-fcose-2.2.0.tgz", + "integrity": "sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==", + "license": "MIT", + "dependencies": { + "cose-base": "^2.2.0" + }, + "peerDependencies": { + "cytoscape": "^3.2.0" + } + }, + "node_modules/cytoscape-fcose/node_modules/cose-base": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-2.2.0.tgz", + "integrity": "sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==", + "license": "MIT", + "dependencies": { + "layout-base": "^2.0.0" + } + }, + "node_modules/cytoscape-fcose/node_modules/layout-base": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-2.0.1.tgz", + "integrity": "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==", + "license": "MIT" + }, + "node_modules/d3": { + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz", + "integrity": "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==", + "license": "ISC", + "dependencies": { + "d3-array": "3", + "d3-axis": "3", + "d3-brush": "3", + "d3-chord": "3", + "d3-color": "3", + "d3-contour": "4", + "d3-delaunay": "6", + "d3-dispatch": "3", + "d3-drag": "3", + "d3-dsv": "3", + "d3-ease": "3", + "d3-fetch": "3", + "d3-force": "3", + "d3-format": "3", + "d3-geo": "3", + "d3-hierarchy": "3", + "d3-interpolate": "3", + "d3-path": "3", + "d3-polygon": "3", + "d3-quadtree": "3", + "d3-random": "3", + "d3-scale": "4", + "d3-scale-chromatic": "3", + "d3-selection": "3", + "d3-shape": "3", + "d3-time": "3", + "d3-time-format": "4", + "d3-timer": "3", + "d3-transition": "3", + "d3-zoom": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-array": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-axis": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.0.tgz", + "integrity": "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-brush": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz", + "integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-drag": "2 - 3", + "d3-interpolate": "1 - 3", + "d3-selection": "3", + "d3-transition": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-chord": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.1.tgz", + "integrity": "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==", + "license": "ISC", + "dependencies": { + "d3-path": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-contour": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz", + "integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==", + "license": "ISC", + "dependencies": { + "d3-array": "^3.2.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-delaunay": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz", + "integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==", + "license": "ISC", + "dependencies": { + "delaunator": "5" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-dispatch": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz", + "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-drag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz", + "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-selection": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-dsv": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz", + "integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==", + "license": "ISC", + "dependencies": { + "commander": "7", + "iconv-lite": "0.6", + "rw": "1" + }, + "bin": { + "csv2json": "bin/dsv2json.js", + "csv2tsv": "bin/dsv2dsv.js", + "dsv2dsv": "bin/dsv2dsv.js", + "dsv2json": "bin/dsv2json.js", + "json2csv": "bin/json2dsv.js", + "json2dsv": "bin/json2dsv.js", + "json2tsv": "bin/json2dsv.js", + "tsv2csv": "bin/dsv2dsv.js", + "tsv2json": "bin/dsv2json.js" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-dsv/node_modules/commander": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", + "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/d3-ease": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", + "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-fetch": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.1.tgz", + "integrity": "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==", + "license": "ISC", + "dependencies": { + "d3-dsv": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-force": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz", + "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-quadtree": "1 - 3", + "d3-timer": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz", + "integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-geo": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz", + "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2.5.0 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-hierarchy": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz", + "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-path": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz", + "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-polygon": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.1.tgz", + "integrity": "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-quadtree": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz", + "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-random": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz", + "integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-sankey": { + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/d3-sankey/-/d3-sankey-0.12.3.tgz", + "integrity": "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==", + "license": "BSD-3-Clause", + "dependencies": { + "d3-array": "1 - 2", + "d3-shape": "^1.2.0" + } + }, + "node_modules/d3-sankey/node_modules/d3-array": { + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-2.12.1.tgz", + "integrity": "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==", + "license": "BSD-3-Clause", + "dependencies": { + "internmap": "^1.0.0" + } + }, + "node_modules/d3-sankey/node_modules/d3-path": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz", + "integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==", + "license": "BSD-3-Clause" + }, + "node_modules/d3-sankey/node_modules/d3-shape": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz", + "integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==", + "license": "BSD-3-Clause", + "dependencies": { + "d3-path": "1" + } + }, + "node_modules/d3-sankey/node_modules/internmap": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-1.0.1.tgz", + "integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==", + "license": "ISC" + }, + "node_modules/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "license": "ISC", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale-chromatic": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz", + "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3", + "d3-interpolate": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-selection": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz", + "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-shape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz", + "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==", + "license": "ISC", + "dependencies": { + "d3-path": "^3.1.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "license": "ISC", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-timer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", + "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-transition": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz", + "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3", + "d3-dispatch": "1 - 3", + "d3-ease": "1 - 3", + "d3-interpolate": "1 - 3", + "d3-timer": "1 - 3" + }, + "engines": { + "node": ">=12" + }, + "peerDependencies": { + "d3-selection": "2 - 3" + } + }, + "node_modules/d3-zoom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz", + "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-drag": "2 - 3", + "d3-interpolate": "1 - 3", + "d3-selection": "2 - 3", + "d3-transition": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/dagre-d3-es": { + "version": "7.0.11", + "resolved": "https://registry.npmjs.org/dagre-d3-es/-/dagre-d3-es-7.0.11.tgz", + "integrity": "sha512-tvlJLyQf834SylNKax8Wkzco/1ias1OPw8DcUMDE7oUIoSEW25riQVuiu/0OWEFqT0cxHT3Pa9/D82Jr47IONw==", + "license": "MIT", + "dependencies": { + "d3": "^7.9.0", + "lodash-es": "^4.17.21" + } + }, "node_modules/data-urls": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", @@ -4732,6 +5689,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/dayjs": { + "version": "1.11.13", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz", + "integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==", + "license": "MIT" + }, "node_modules/debug": { "version": "4.3.7", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", @@ -4856,6 +5819,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/delaunator": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.0.1.tgz", + "integrity": "sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw==", + "license": "ISC", + "dependencies": { + "robust-predicates": "^3.0.2" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -4928,9 +5900,13 @@ "dev": true }, "node_modules/dompurify": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.1.6.tgz", - "integrity": "sha512-cTOAhc36AalkjtBpfG6O8JimdTMWNXjiePT2xQH/ppBGi/4uIpmj8eKyIkMJErXWARyINV/sB38yf8JCLF5pbQ==" + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.2.6.tgz", + "integrity": "sha512-/2GogDQlohXPZe6D6NOgQvXLPSYBqIWMnZ8zzOhn09REE4eyAzb+Hed3jhoM9OkuaJ8P6ZGTTVWQKAi8ieIzfQ==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } }, "node_modules/downshift": { "version": "7.6.2", @@ -5749,6 +6725,12 @@ "node": ">=4" } }, + "node_modules/exsolve": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.7.tgz", + "integrity": "sha512-VO5fQUzZtI6C+vx4w/4BWJpg3s/5l+6pRQEHzFRM8WFi4XffSP1Z+4qi7GbjWbvRQEbdIco5mIMq+zX4rPuLrw==", + "license": "MIT" + }, "node_modules/ext-list": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/ext-list/-/ext-list-2.2.2.tgz", @@ -6305,6 +7287,12 @@ "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", "dev": true }, + "node_modules/hachure-fill": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/hachure-fill/-/hachure-fill-0.5.2.tgz", + "integrity": "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==", + "license": "MIT" + }, "node_modules/handlebars": { "version": "4.7.8", "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.8.tgz", @@ -7000,7 +7988,6 @@ "version": "0.6.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" }, @@ -7116,6 +8103,15 @@ "node": ">= 0.4" } }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/is-alphabetical": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", @@ -7855,6 +8851,39 @@ "json-buffer": "3.0.1" } }, + "node_modules/khroma": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/khroma/-/khroma-2.1.0.tgz", + "integrity": "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==" + }, + "node_modules/kolorist": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/kolorist/-/kolorist-1.8.0.tgz", + "integrity": "sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==", + "license": "MIT" + }, + "node_modules/langium": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/langium/-/langium-3.3.1.tgz", + "integrity": "sha512-QJv/h939gDpvT+9SiLVlY7tZC3xB2qK57v0J04Sh9wpMb6MP1q8gB21L3WIo8T5P1MSMg3Ep14L7KkDCFG3y4w==", + "license": "MIT", + "dependencies": { + "chevrotain": "~11.0.3", + "chevrotain-allstar": "~0.3.0", + "vscode-languageserver": "~9.0.1", + "vscode-languageserver-textdocument": "~1.0.11", + "vscode-uri": "~3.0.8" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/layout-base": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-1.0.2.tgz", + "integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==", + "license": "MIT" + }, "node_modules/levn": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", @@ -7891,6 +8920,23 @@ "uc.micro": "^2.0.0" } }, + "node_modules/local-pkg": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-1.1.1.tgz", + "integrity": "sha512-WunYko2W1NcdfAFpuLUoucsgULmgDBRkdxHxWQ7mK0cQqwPiy8E1enjuRBrhLtZkB5iScJ1XIPdhVEFK8aOLSg==", + "license": "MIT", + "dependencies": { + "mlly": "^1.7.4", + "pkg-types": "^2.0.1", + "quansync": "^0.2.8" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -7911,6 +8957,12 @@ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" }, + "node_modules/lodash-es": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz", + "integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==", + "license": "MIT" + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -8050,6 +9102,18 @@ "markdown-it": "bin/markdown-it.mjs" } }, + "node_modules/marked": { + "version": "15.0.12", + "resolved": "https://registry.npmjs.org/marked/-/marked-15.0.12.tgz", + "integrity": "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/mdast-util-definitions": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/mdast-util-definitions/-/mdast-util-definitions-4.0.0.tgz", @@ -8285,6 +9349,47 @@ "node": ">= 8" } }, + "node_modules/mermaid": { + "version": "11.8.0", + "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.8.0.tgz", + "integrity": "sha512-uAZUwnBiqREZcUrFw3G5iQ5Pj3hTYUP95EZc3ec/nGBzHddJZydzYGE09tGZDBS1VoSoDn0symZ85FmypSTo5g==", + "license": "MIT", + "dependencies": { + "@braintree/sanitize-url": "^7.0.4", + "@iconify/utils": "^2.1.33", + "@mermaid-js/parser": "^0.6.0", + "@types/d3": "^7.4.3", + "cytoscape": "^3.29.3", + "cytoscape-cose-bilkent": "^4.1.0", + "cytoscape-fcose": "^2.2.0", + "d3": "^7.9.0", + "d3-sankey": "^0.12.3", + "dagre-d3-es": "7.0.11", + "dayjs": "^1.11.13", + "dompurify": "^3.2.5", + "katex": "^0.16.9", + "khroma": "^2.1.0", + "lodash-es": "^4.17.21", + "marked": "^15.0.7", + "roughjs": "^4.6.6", + "stylis": "^4.3.6", + "ts-dedent": "^2.2.0", + "uuid": "^11.1.0" + } + }, + "node_modules/mermaid/node_modules/uuid": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, "node_modules/micromark": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.0.tgz", @@ -8832,6 +9937,41 @@ "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.1.0.tgz", "integrity": "sha512-tv7c/uefWdEhcu6hvrfTihflgeEi2tN6VV7HJnCjK6VxM75QQJh4t9FwJCsA2EsRS8LCnu3W87CuGPWMocOLCA==" }, + "node_modules/mlly": { + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.7.4.tgz", + "integrity": "sha512-qmdSIPC4bDJXgZTCR7XosJiNKySV7O215tsPtDN9iEO/7q/76b/ijtgRu/+epFXSJhijtTCCGp3DWS549P3xKw==", + "license": "MIT", + "dependencies": { + "acorn": "^8.14.0", + "pathe": "^2.0.1", + "pkg-types": "^1.3.0", + "ufo": "^1.5.4" + } + }, + "node_modules/mlly/node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "license": "MIT" + }, + "node_modules/mlly/node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "license": "MIT" + }, + "node_modules/mlly/node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, "node_modules/mrmime": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.0.tgz", @@ -9182,6 +10322,12 @@ "integrity": "sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw==", "dev": true }, + "node_modules/package-manager-detector": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.3.0.tgz", + "integrity": "sha512-ZsEbbZORsyHuO00lY1kV3/t72yp6Ysay6Pd17ZAlNGuGwmWDLCJxFpRs0IzfXfj1o4icJOkUEioexFHzyPurSQ==", + "license": "MIT" + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -9229,6 +10375,12 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, + "node_modules/path-data-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/path-data-parser/-/path-data-parser-0.1.0.tgz", + "integrity": "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==", + "license": "MIT" + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -9355,6 +10507,39 @@ "@napi-rs/nice": "^1.0.1" } }, + "node_modules/pkg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.2.0.tgz", + "integrity": "sha512-2SM/GZGAEkPp3KWORxQZns4M+WSeXbC2HEvmOIJe3Cmiv6ieAJvdVhDldtHqM5J1Y7MrR1XhkBT/rMlhh9FdqQ==", + "license": "MIT", + "dependencies": { + "confbox": "^0.2.2", + "exsolve": "^1.0.7", + "pathe": "^2.0.3" + } + }, + "node_modules/pkg-types/node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "license": "MIT" + }, + "node_modules/points-on-curve": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/points-on-curve/-/points-on-curve-0.2.0.tgz", + "integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==", + "license": "MIT" + }, + "node_modules/points-on-path": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/points-on-path/-/points-on-path-0.2.1.tgz", + "integrity": "sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==", + "license": "MIT", + "dependencies": { + "path-data-parser": "0.1.0", + "points-on-curve": "0.2.0" + } + }, "node_modules/possible-typed-array-names": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", @@ -9819,6 +11004,22 @@ "node": ">=6" } }, + "node_modules/quansync": { + "version": "0.2.10", + "resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.10.tgz", + "integrity": "sha512-t41VRkMYbkHyCYmOvx/6URnN80H7k4X0lLdBMGsz+maAwrJQYB1djpV6vHrQIBE0WBSGqhtEHrK9U3DWWH8v7A==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/antfu" + }, + { + "type": "individual", + "url": "https://github.com/sponsors/sxzz" + } + ], + "license": "MIT" + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", @@ -10937,6 +12138,12 @@ "node": "*" } }, + "node_modules/robust-predicates": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.2.tgz", + "integrity": "sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg==", + "license": "Unlicense" + }, "node_modules/rollup": { "version": "4.40.0", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.40.0.tgz", @@ -10981,6 +12188,18 @@ "resolved": "https://registry.npmjs.org/rope-sequence/-/rope-sequence-1.3.4.tgz", "integrity": "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==" }, + "node_modules/roughjs": { + "version": "4.6.6", + "resolved": "https://registry.npmjs.org/roughjs/-/roughjs-4.6.6.tgz", + "integrity": "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==", + "license": "MIT", + "dependencies": { + "hachure-fill": "^0.5.2", + "path-data-parser": "^0.1.0", + "points-on-curve": "^0.2.0", + "points-on-path": "^0.2.1" + } + }, "node_modules/rrweb-cssom": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.7.1.tgz", @@ -11010,6 +12229,12 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/rw": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz", + "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==", + "license": "BSD-3-Clause" + }, "node_modules/safe-array-concat": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz", @@ -11068,8 +12293,7 @@ "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, "node_modules/saxes": { "version": "6.0.0", @@ -11648,6 +12872,12 @@ "react-is": ">= 16.8.0" } }, + "node_modules/stylis": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.3.6.tgz", + "integrity": "sha512-yQ3rwFWRfwNUY7H5vpU0wfdkNSnvnJinhF9830Swlaxl03zsOjCfmX0ugac+3LtK0lYSgwL/KXc8oYL3mG4YFQ==", + "license": "MIT" + }, "node_modules/sucrase": { "version": "3.35.0", "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.0.tgz", @@ -12050,6 +13280,15 @@ "typescript": ">=4.2.0" } }, + "node_modules/ts-dedent": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz", + "integrity": "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==", + "license": "MIT", + "engines": { + "node": ">=6.10" + } + }, "node_modules/ts-interface-checker": { "version": "0.1.13", "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", @@ -12203,6 +13442,12 @@ "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==" }, + "node_modules/ufo": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.1.tgz", + "integrity": "sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==", + "license": "MIT" + }, "node_modules/uglify-js": { "version": "3.19.3", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", @@ -13621,6 +14866,55 @@ } } }, + "node_modules/vscode-jsonrpc": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz", + "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/vscode-languageserver": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-9.0.1.tgz", + "integrity": "sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==", + "license": "MIT", + "dependencies": { + "vscode-languageserver-protocol": "3.17.5" + }, + "bin": { + "installServerIntoExtension": "bin/installServerIntoExtension" + } + }, + "node_modules/vscode-languageserver-protocol": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz", + "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==", + "license": "MIT", + "dependencies": { + "vscode-jsonrpc": "8.2.0", + "vscode-languageserver-types": "3.17.5" + } + }, + "node_modules/vscode-languageserver-textdocument": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz", + "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==", + "license": "MIT" + }, + "node_modules/vscode-languageserver-types": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", + "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", + "license": "MIT" + }, + "node_modules/vscode-uri": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.0.8.tgz", + "integrity": "sha512-AyFQ0EVmsOZOlAnxoFOGOq1SQDWAB7C6aqMGS23svWAllfOaxbuFvcT8D1i8z3Gyn8fraVeZNNmN6e9bxxXkKw==", + "license": "MIT" + }, "node_modules/w3c-keyname": { "version": "2.2.8", "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", diff --git a/gui/package.json b/gui/package.json index f98c4499f..ce5cbb29f 100644 --- a/gui/package.json +++ b/gui/package.json @@ -19,6 +19,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", + "@panzoom/panzoom": "^4.6.0", "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", "@tiptap/extension-document": "^2.3.2", @@ -43,6 +44,7 @@ "handlebars": "^4.7.8", "lodash": "^4.17.21", "lowlight": "^3.3.0", + "mermaid": "^11.6.0", "minisearch": "^7.0.2", "mustache": "^4.2.0", "posthog-js": "^1.130.1", diff --git a/gui/public/logos/sambanova.png b/gui/public/logos/sambanova.png index 6f95c6a58..a3016db0b 100644 Binary files a/gui/public/logos/sambanova.png and b/gui/public/logos/sambanova.png differ diff --git a/gui/src/components/StyledMarkdownPreview/MermaidBlock.tsx b/gui/src/components/StyledMarkdownPreview/MermaidBlock.tsx new file mode 100644 index 000000000..b855d5e15 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/MermaidBlock.tsx @@ -0,0 +1,177 @@ +import { + ArrowPathRoundedSquareIcon, + MagnifyingGlassMinusIcon, + MagnifyingGlassPlusIcon, +} from "@heroicons/react/24/outline"; +// @ts-ignore +import Panzoom from "@panzoom/panzoom"; +// @ts-ignore +import mermaid from "mermaid"; +import { useEffect, useId, useRef, useState } from "react"; +import { useDebouncedEffect } from "../find/useDebounce"; +import { ToolTip } from "../gui/Tooltip"; + +const MINIMUM_ZOOM_STEP = 0.05; + +const MERMAID_THEME_COLORS = { + background: "#1e1e1e", + primaryColor: "#4d8bf0", + primaryTextColor: "#ffffff", + primaryBorderColor: "#4d8bf0", + secondaryColor: "#3a6db3", + secondaryTextColor: "#ffffff", + secondaryBorderColor: "#3a6db3", + tertiaryColor: "#59bc89", + tertiaryTextColor: "#ffffff", + tertiaryBorderColor: "#59bc89", + noteBkgColor: "#2d2d2d", + noteTextColor: "#e6e6e6", + noteBorderColor: "#555555", + lineColor: "#8c8c8c", + textColor: "#e6e6e6", + mainBkg: "#252525", + errorBkgColor: "#f44336", + errorTextColor: "#ffffff", + nodeBorder: "#555555", + clusterBkg: "#2a2a2a", + clusterBorder: "#555555", + defaultLinkColor: "#8c8c8c", + titleColor: "#e6e6e6", + edgeLabelBackground: "#252525", + activeTaskBkgColor: "#4caf50", + activeTaskBorderColor: "#388e3c", + doneTaskBkgColor: "#388e3c", + doneTaskBorderColor: "#2e7d32", + critBkgColor: "#f44336", + critBorderColor: "#d32f2f", + taskTextColor: "#e6e6e6", + taskTextOutsideColor: "#e6e6e6", + taskTextLightColor: "#b3b3b3", + sectionBkgColor: "#2a2a2a", + altSectionBkgColor: "#303030", + sectionBkgColor2: "#252525", + excludeBkgColor: "#2d2d2d", + fillType0: "#264f78", + fillType1: "#3a6db3", + fillType2: "#59bc89", + fillType3: "#4d8bf0", + fillType4: "#3a6db3", + fillType5: "#264f78", + fillType6: "#59bc89", + fillType7: "#4d8bf0", +}; + +mermaid.initialize({ + startOnLoad: false, + securityLevel: "loose", + theme: "dark", + themeVariables: { + ...MERMAID_THEME_COLORS, + fontSize: "14px", + fontFamily: "var(--vscode-font-family)", + }, +}); + +export default function MermaidDiagram({ code }: { code: string }) { + const mermaidRenderContainerRef = useRef(null); + const zoomInButtonRef = useRef(null); + const zoomOutButtonRef = useRef(null); + const resetZoomButtonRef = useRef(null); + + const zoomInButtonId = useId(); + const zoomOutButtonId = useId(); + const resetZoomButtonId = useId(); + + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(""); + + useEffect(() => { + setIsLoading(true); + }, [code]); + + useDebouncedEffect( + () => { + if (mermaidRenderContainerRef.current) { + mermaidRenderContainerRef.current.innerHTML = ""; + } + const diagramId = `mermaid-id-${Math.random().toString(36).substring(2)}`; + void (async () => { + if (!mermaidRenderContainerRef.current) return; + try { + await mermaid.parse(code); + const renderedSVG = await mermaid.render(diagramId, code); + mermaidRenderContainerRef.current.innerHTML = renderedSVG.svg; + setError(""); + const panzoom = Panzoom(mermaidRenderContainerRef.current, { + step: MINIMUM_ZOOM_STEP, + }); + zoomInButtonRef.current?.addEventListener("click", () => + panzoom.zoomIn({ step: MINIMUM_ZOOM_STEP * 4 }), + ); + zoomOutButtonRef.current?.addEventListener("click", () => + panzoom.zoomOut({ step: MINIMUM_ZOOM_STEP * 4 }), + ); + resetZoomButtonRef.current?.addEventListener("click", () => + panzoom.reset(), + ); + mermaidRenderContainerRef.current.parentElement?.addEventListener( + "wheel", + (event) => { + if (!event.shiftKey) return; + panzoom.zoomWithWheel(event); + }, + ); + } catch (err: any) { + if (err.message) { + setError(err.message); + } else { + setError( + "Unknown error when parsing or rendering the Mermaid diagram.", + ); + } + } + setIsLoading(false); + })(); + }, + 500, + [code], + ); + + return ( + <> + {isLoading && ( +
Generating diagram...
+ )} + {!!error ? ( +
{error}
+ ) : ( +
+
+ + Zoom In + + Zoom Out + + Reset Zoom +
+
+
+ )} + + ); +} diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx index 58f05ef0c..f8293cd50 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx @@ -1,6 +1,5 @@ import { ReactNode, useMemo } from "react"; -import { Tooltip } from "react-tooltip"; -import { getFontSize } from "../../../util"; +import { ToolTip } from "../../gui/Tooltip"; interface ToolbarButtonWithTooltipProps { onClick: () => void; @@ -22,20 +21,20 @@ export function ToolbarButtonWithTooltip({ return ( <> - - +
+ {tooltipContent} - + ); } diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index 1d252dbdb..03aa1c4f5 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -219,7 +219,6 @@ export function StepContainerPreToolbar({ if (isGeneratingCodeBlock) { return ( - {!isExpanded ? `${numLines} line${plural}` : "Generating"}{" "}
diff --git a/gui/src/components/StyledMarkdownPreview/index.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx index 908a1642d..aed35e735 100644 --- a/gui/src/components/StyledMarkdownPreview/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/index.tsx @@ -21,6 +21,7 @@ import { ToolTip } from "../gui/Tooltip"; import FilenameLink from "./FilenameLink"; import "./katex.css"; import "./markdown.css"; +import MermaidBlock from "./MermaidBlock"; import { rehypeHighlightPlugin } from "./rehypeHighlightPlugin"; import { StepContainerPreToolbar } from "./StepContainerPreToolbar"; import SymbolLink from "./SymbolLink"; @@ -333,6 +334,10 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( } } } + if (codeProps.className?.includes("language-mermaid")) { + const codeText = String(codeProps.children || ""); + return ; + } return {codeProps.children}; }, }, diff --git a/gui/src/components/dialogs/FeedbackDialog.tsx b/gui/src/components/dialogs/FeedbackDialog.tsx deleted file mode 100644 index d8da4e93b..000000000 --- a/gui/src/components/dialogs/FeedbackDialog.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import { usePostHog } from "posthog-js/react"; -import { setDialogMessage } from "../../redux/slices/uiSlice"; -import { useAppDispatch } from "../../redux/hooks"; - -export default function FeedbackDialog() { - const posthog = usePostHog(); - const dispatch = useAppDispatch(); - - return ( -
- 👋 Thanks for using Continue. We are always trying to improve and love - hearing from users. If you're interested in speaking, enter your name and - email. We won't use this information for anything other than reaching out. -
-
-
{ - e.preventDefault(); - posthog?.capture("user_interest_form", { - name: e.target.elements[0].value, - email: e.target.elements[1].value, - }); - dispatch( - setDialogMessage( -
- Thanks! We'll be in touch soon. -
, - ), - ); - }} - style={{ - display: "flex", - flexDirection: "column", - gap: "10px", - }} - > - - - -
-
- ); -} diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index f5badfe41..53376b9e6 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -18,7 +18,7 @@ import { SearchMatch, searchWithinContainer, } from "./findWidgetSearch"; -import useDebounceValue from "./useDebounce"; +import { useDebounceValue } from "./useDebounce"; import { useElementSize } from "./useElementSize"; interface HighlightOverlayProps { diff --git a/gui/src/components/find/useDebounce.ts b/gui/src/components/find/useDebounce.ts index 8a9898429..0ab483fd4 100644 --- a/gui/src/components/find/useDebounce.ts +++ b/gui/src/components/find/useDebounce.ts @@ -1,6 +1,6 @@ -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; -function useDebounceValue(value: T, delay: number = 500): T { +export function useDebounceValue(value: T, delay: number = 500): T { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { @@ -16,4 +16,32 @@ function useDebounceValue(value: T, delay: number = 500): T { return debouncedValue; } -export default useDebounceValue; +export function useDebouncedEffect( + effect: () => void, + delay: number, + deps: unknown[], +) { + const timeoutRef = useRef(null); + const callBackRef = useRef(() => {}); + + useEffect(() => { + // do not want the timeout to reset on effect dep change + callBackRef.current = effect; + }, [effect]); + + useEffect(() => { + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + } + + timeoutRef.current = setTimeout(() => { + callBackRef.current(); + }, delay); + + return () => { + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + } + }; + }, [delay, ...deps]); +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx index b1424ffe4..8e36e64cf 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx @@ -28,7 +28,7 @@ export function EditToolbar() { Back to {mode.charAt(0).toUpperCase() + mode.slice(1)}
- Editing{" "} + Editing:{" "} {getEditFilenameAndRangeText(codeToEdit)} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx index ef7d7d1bd..21d74f02c 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx @@ -36,8 +36,8 @@ const isCancelToolCallShortcut = ( }; export function LumpToolbar() { - const ideMessenger = useContext(IdeMessengerContext); const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); const ttsActive = useAppSelector((state) => state.ui.ttsActive); const isStreaming = useAppSelector((state) => state.session.isStreaming); const isInEdit = useAppSelector((state) => state.session.isInEdit); @@ -71,7 +71,6 @@ export function LumpToolbar() { } else if (isCancelToolCallShortcut(event, jetbrains)) { event.preventDefault(); event.stopPropagation(); - void dispatch( cancelToolCall({ toolCallId: firstPendingToolCall.toolCallId, diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index cf3939c48..b82c36b6c 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -29,6 +29,14 @@ const MINISEARCH_OPTIONS = { const MAX_LENGTH = 70; +// Enhanced search result interface for intelligent sorting +interface EnhancedSearchResult + extends SearchResult, + Omit { + sortPriority: number; + matchQuality: number; +} + interface SubtextContextProvidersContextType { getSubmenuContextItems: ( providerTitle: string | undefined, @@ -43,6 +51,91 @@ const initialContextProviders: SubtextContextProvidersContextType = { const SubmenuContextProvidersContext = createContext(initialContextProviders); +// Helper functions for intelligent file sorting +function hasExactWordMatch(text: string, query: string): boolean { + const words = text.split(/[^a-zA-Z0-9]+/); + return words.some((word) => word === query); +} + +function isCommonDevFile(fileName: string): boolean { + const commonExtensions = [ + ".ts", + ".tsx", + ".js", + ".jsx", + ".py", + ".java", + ".cpp", + ".c", + ".h", + ".vue", + ".svelte", + ]; + const commonNames = [ + "index", + "main", + "app", + "component", + "service", + "util", + "helper", + "config", + "types", + ]; + + const extension = fileName.substring(fileName.lastIndexOf(".")); + const baseName = fileName + .substring(0, fileName.lastIndexOf(".")) + .toLowerCase(); + + return commonExtensions.includes(extension) || commonNames.includes(baseName); +} + +function isInCommonDirectory(filePath: string): boolean { + const commonDirs = [ + "src/", + "lib/", + "components/", + "utils/", + "helpers/", + "services/", + "pages/", + "views/", + "hooks/", + "store/", + "types/", + "interfaces/", + "models/", + "api/", + ]; + return commonDirs.some((dir) => filePath.includes(dir)); +} + +function matchesCamelCaseOrAbbreviation( + fileName: string, + query: string, +): boolean { + // Extract capital letters for camel case matching + const capitals = fileName.match(/[A-Z]/g)?.join("").toLowerCase() || ""; + + // Check if query matches the capital letters pattern + if (capitals.length > 0 && capitals.includes(query)) { + return true; + } + + // Check for abbreviation matches (first letters of words) + const words = fileName.split(/[^a-zA-Z0-9]+/).filter((w) => w.length > 0); + if (words.length > 1) { + const abbreviation = words + .map((word) => word[0]) + .join("") + .toLowerCase(); + return abbreviation.includes(query); + } + + return false; +} + export const SubmenuContextProvidersProvider = ({ children, }: { @@ -128,6 +221,98 @@ export const SubmenuContextProvidersProvider = ({ new Map(), ).current; + const calculateFileSortPriority = useCallback( + ( + result: SearchResult & ContextSubmenuItemWithProvider, + query: string, + openFiles: ContextSubmenuItemWithProvider[], + ): number => { + const fileName = result.title.toLowerCase(); + const filePath = result.description.toLowerCase(); + const queryLower = query.toLowerCase(); + + // Priority 1: Exact filename match + if (fileName === queryLower) { + return 1; + } + + // Priority 2: Recently opened files + if (openFiles.some((f) => f.id === result.id)) { + return 2; + } + + // Priority 3: Filename starts with query + if (fileName.startsWith(queryLower)) { + return 3; + } + + // Priority 4: Exact word match in filename + if (hasExactWordMatch(fileName, queryLower)) { + return 4; + } + + // Priority 5: Common development files + if (isCommonDevFile(fileName)) { + return 5; + } + + // Priority 6: Files in common directories + if (isInCommonDirectory(filePath)) { + return 6; + } + + // Priority 7: CamelCase/abbreviation matches + if (matchesCamelCaseOrAbbreviation(fileName, queryLower)) { + return 7; + } + + // Priority 8: Path starts with query + if (filePath.startsWith(queryLower)) { + return 8; + } + + // Priority 9: Default + return 9; + }, + [], + ); + + const calculateMatchQuality = useCallback( + ( + result: SearchResult & ContextSubmenuItemWithProvider, + query: string, + ): number => { + const fileName = result.title.toLowerCase(); + const queryLower = query.toLowerCase(); + let quality = 0; + + // Exact match bonus + if (fileName === queryLower) quality += 100; + + // Prefix match bonus + if (fileName.startsWith(queryLower)) quality += 50; + + // Contains match bonus + if (fileName.includes(queryLower)) quality += 25; + + // Shorter filename bonus (prefer concise names) + quality += Math.max(0, 50 - fileName.length); + + // Extension preference (common dev files) + if ( + fileName.endsWith(".ts") || + fileName.endsWith(".tsx") || + fileName.endsWith(".js") || + fileName.endsWith(".jsx") + ) { + quality += 10; + } + + return quality; + }, + [], + ); + const getSubmenuContextItems = useCallback( ( providerTitle: string | undefined, @@ -168,9 +353,57 @@ export const SubmenuContextProvidersProvider = ({ }); } } - searchResults.sort((a, b) => b.score - a.score); - // 2. Add fallback results if no search results + // 2. Enhanced sorting for file provider + if ( + providerTitle === "file" || + (!providerTitle && + searchResults.some((r) => r.providerTitle === "file")) + ) { + const enhancedResults: EnhancedSearchResult[] = searchResults.map( + (result): EnhancedSearchResult => ({ + ...result, + id: result.id, + title: result.title, + description: result.description, + providerTitle: result.providerTitle, + sortPriority: calculateFileSortPriority( + result, + query, + lastOpenFilesRef.current, + ), + matchQuality: calculateMatchQuality(result, query), + }), + ); + + // Sort by multiple criteria + enhancedResults.sort((a, b) => { + // Primary: Sort priority (lower = better) + if (a.sortPriority !== b.sortPriority) { + return a.sortPriority - b.sortPriority; + } + + // Secondary: Match quality (higher = better) + if (a.matchQuality !== b.matchQuality) { + return b.matchQuality - a.matchQuality; + } + + // Tertiary: MiniSearch relevance score (higher = better) + if (a.score !== b.score) { + return b.score - a.score; + } + + // Quaternary: Path length (shorter = better) + return a.description.length - b.description.length; + }); + + searchResults = enhancedResults; + } else { + // Default sorting for non-file providers + searchResults.sort((a, b) => b.score - a.score); + } + + // 3. Add fallback results if no search results if (searchResults.length === 0) { const fallbackItems = ( providerTitle ? (fallbackResults[providerTitle] ?? []) : [] @@ -223,7 +456,12 @@ export const SubmenuContextProvidersProvider = ({ return []; } }, - [fallbackResults, minisearches], + [ + fallbackResults, + minisearches, + calculateFileSortPriority, + calculateMatchQuality, + ], ); const loadSubmenuItems = useCallback( diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 6b2699aae..98fe87dd4 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -16,7 +16,6 @@ import { import { ErrorBoundary } from "react-error-boundary"; import styled from "styled-components"; import { Button, lightGray, vscBackground } from "../../components"; -import FeedbackDialog from "../../components/dialogs/FeedbackDialog"; import { useFindWidget } from "../../components/find/FindWidget"; import TimelineItem from "../../components/gui/TimelineItem"; import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton"; @@ -38,11 +37,6 @@ import { newSession, updateToolCallOutput, } from "../../redux/slices/sessionSlice"; -import { - setDialogEntryOn, - setDialogMessage, - setShowDialog, -} from "../../redux/slices/uiSlice"; import { streamEditThunk } from "../../redux/thunks/edit"; import { loadLastSession } from "../../redux/thunks/session"; import { streamResponseThunk } from "../../redux/thunks/streamResponse"; @@ -50,7 +44,6 @@ import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { ToolCallDiv } from "./ToolCallDiv"; import { cancelStream } from "../../redux/thunks/cancelStream"; -import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { useAutoScroll } from "./useAutoScroll"; @@ -222,19 +215,6 @@ export function Chat() { editorToClearOnSend.commands.clearContent(); } } - - // Increment localstorage counter for popup - const currentCount = getLocalStorage("mainTextEntryCounter"); - if (currentCount) { - setLocalStorage("mainTextEntryCounter", currentCount + 1); - if (currentCount === 300) { - dispatch(setDialogMessage()); - dispatch(setDialogEntryOn(false)); - dispatch(setShowDialog(true)); - } - } else { - setLocalStorage("mainTextEntryCounter", 1); - } }, [ history, diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 27b093799..dae07c549 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -6,15 +6,14 @@ type EditToolCallProps = { changes: string; historyIndex: number; toolCallId?: string; - expandCodeblocks?: boolean; }; export function EditFile(props: EditToolCallProps) { - if (!props.relativeFilePath || !props.changes) { + if (!props.relativeFilePath) { return null; } - const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.changes}\n\`\`\``; + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath)} ${props.relativeFilePath}\n${props.changes}\n\`\`\``; return ( { - const argsTooltipId = useMemo(() => { - return "args-hover-" + toolCallId; - }, [toolCallId]); - return ( - <> -
{ - e.stopPropagation(); - setIsShowing(!isShowing); - }} - className={`hover:description-muted/30 cursor-pointer select-none rounded px-1 py-0.5 hover:opacity-80 ${isShowing ? "bg-description-muted/30" : "bg-transparent"}`} - > - -
- - {isShowing ? "Hide args" : "Show args"} - - + { + setIsShowing(!isShowing); + }} + > + + ); }; diff --git a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx index 12000042d..d28cd9328 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx @@ -19,9 +19,11 @@ export function ToolTruncateHistoryIcon({ }, [history]); const dispatch = useAppDispatch(); const { mainEditor } = useMainEditor(); + if (historyIndex === lastMessageIndex) { return null; } + return ( ); diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 94ea296c5..e9c725dbd 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -107,6 +107,7 @@ export function ToolCallDiv({ ); } + return (
{toolCallStates.map((toolCallState) => ( diff --git a/gui/src/pages/gui/chat-tests/Chat.test.tsx b/gui/src/pages/gui/chat-tests/Chat.test.tsx index acd17bf55..c915a0523 100644 --- a/gui/src/pages/gui/chat-tests/Chat.test.tsx +++ b/gui/src/pages/gui/chat-tests/Chat.test.tsx @@ -15,7 +15,7 @@ test("should render input box", async () => { test("should be able to toggle modes", async () => { await renderWithProviders(); - await getElementByText("Chat"); + await getElementByText("Agent"); // Simulate cmd+. keyboard shortcut to toggle modes act(() => { @@ -27,6 +27,18 @@ test("should be able to toggle modes", async () => { ); }); + // Check that it switched to Chat mode + await getElementByText("Chat"); + + act(() => { + document.dispatchEvent( + new KeyboardEvent("keydown", { + key: ".", + metaKey: true, // cmd key on Mac + }), + ); + }); + // Check that it switched to Plan mode await getElementByText("Plan"); @@ -39,19 +51,7 @@ test("should be able to toggle modes", async () => { ); }); - // Check that it switched to Agent mode await getElementByText("Agent"); - - act(() => { - document.dispatchEvent( - new KeyboardEvent("keydown", { - key: ".", - metaKey: true, // cmd key on Mac - }), - ); - }); - - await getElementByText("Chat"); }); test("should send a message and receive a response", async () => { diff --git a/gui/src/pages/gui/chat-tests/ParallelToolCalls.test.tsx b/gui/src/pages/gui/chat-tests/ParallelToolCalls.test.tsx index a5971e529..a6cceed28 100644 --- a/gui/src/pages/gui/chat-tests/ParallelToolCalls.test.tsx +++ b/gui/src/pages/gui/chat-tests/ParallelToolCalls.test.tsx @@ -9,111 +9,22 @@ describe("Parallel Tool Calls", () => { const PARALLEL_TOOL_CALL_RESPONSE: ChatMessage[] = [ { role: "assistant", - content: - "I'll call the get_weather function in parallel for both San Francisco and Monterey, California.", + content: "I'll call both tools in parallel.", toolCalls: [ { - id: "toolu_0112JmA95qW6WhAsvkKb7Avp", + id: "tool-call-1", type: "function", function: { - name: "get_weather", - arguments: JSON.stringify({ - location: "San Francisco, CA", - }), + name: "read_file", + arguments: JSON.stringify({ filepath: "test.js" }), }, }, { - id: "toolu_01UFK4ZUmbpkeFJGg7mdoT6T", + id: "tool-call-2", type: "function", function: { - name: "get_weather", - arguments: JSON.stringify({ - location: "Monterey, CA", - }), - }, - }, - ], - }, - ]; - - // Simulate real streaming behavior with deltas - const PARALLEL_TOOL_CALL_STREAMING_RESPONSE: ChatMessage[] = [ - // Initial assistant message with content - { - role: "assistant", - content: "I'll call the get_weather function in parallel for both San Francisco and Monterey, California.", - }, - // First tool call starts streaming - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "toolu_0112JmA95qW6WhAsvkKb7Avp", - type: "function", - function: { - name: "get_weather", - arguments: "", - }, - }, - ], - }, - // First tool call continues streaming - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "toolu_0112JmA95qW6WhAsvkKb7Avp", - type: "function", - function: { - name: "get_weather", - arguments: "{\"location\":", - }, - }, - ], - }, - // Second tool call starts streaming (while first is still incomplete) - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "toolu_01UFK4ZUmbpkeFJGg7mdoT6T", - type: "function", - function: { - name: "get_weather", - arguments: "", - }, - }, - ], - }, - // First tool call completes - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "toolu_0112JmA95qW6WhAsvkKb7Avp", - type: "function", - function: { - name: "get_weather", - arguments: " \"San Francisco, CA\"}", - }, - }, - ], - }, - // Second tool call completes - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "toolu_01UFK4ZUmbpkeFJGg7mdoT6T", - type: "function", - function: { - name: "get_weather", - arguments: "{\"location\": \"Monterey, CA\"}", + name: "write_file", + arguments: JSON.stringify({ filepath: "output.js", content: "test" }), }, }, ], @@ -123,1464 +34,56 @@ describe("Parallel Tool Calls", () => { test("should handle assistant message with multiple tool calls", async () => { const { ideMessenger, store } = await renderWithProviders(); - // Add and select mock LLM await act(async () => { addAndSelectMockLlm(store, ideMessenger); }); - const INPUT = "What's the weather in San Francisco and Monterey?"; - - // Send input with mocked parallel tool call response await sendInputWithMockedResponse( ideMessenger, - INPUT, + "Use both tools", PARALLEL_TOOL_CALL_RESPONSE, ); - // Wait for the message to be processed await act(async () => { await new Promise((resolve) => setTimeout(resolve, 100)); }); - // Currently this will fail because we only support one tool call - // but this test documents the expected behavior - }); - - test("should store multiple tool call states in Redux", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - const INPUT = "Get weather for both cities"; - - await sendInputWithMockedResponse( - ideMessenger, - INPUT, - PARALLEL_TOOL_CALL_RESPONSE, - ); - - // Wait for the message to be processed - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Wait for any state updates to complete - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Verify multiple tool calls are stored in Redux state const state = store.getState(); const history = state.session.history; - // Find the assistant message (might not be at index 1 if tool messages were created) + // Should have user message and assistant message + expect(history).toHaveLength(2); + + // Find assistant message with tool calls const assistantMessage = history.find( - (item) => - item.message.role === "assistant" && - (item.message as any).toolCalls?.length, + (item) => item.message.role === "assistant" && item.toolCallStates?.length ); expect(assistantMessage).toBeDefined(); - expect((assistantMessage!.message as any).toolCalls).toHaveLength(2); expect(assistantMessage!.toolCallStates).toHaveLength(2); - - // Verify each tool call has correct ID and function name - expect(assistantMessage!.toolCallStates![0].toolCallId).toBe( - "toolu_0112JmA95qW6WhAsvkKb7Avp", - ); - expect(assistantMessage!.toolCallStates![0].toolCall.function.name).toBe( - "get_weather", - ); - expect(assistantMessage!.toolCallStates![1].toolCallId).toBe( - "toolu_01UFK4ZUmbpkeFJGg7mdoT6T", - ); - expect(assistantMessage!.toolCallStates![1].toolCall.function.name).toBe( - "get_weather", - ); + expect(assistantMessage!.toolCallStates![0].toolCallId).toBe("tool-call-1"); + expect(assistantMessage!.toolCallStates![1].toolCallId).toBe("tool-call-2"); }); - test("should use utility functions for finding tool calls", async () => { + test("should handle individual tool call actions without breaking other calls", async () => { const { ideMessenger, store } = await renderWithProviders(); await act(async () => { addAndSelectMockLlm(store, ideMessenger); }); - const INPUT = "Get weather for both cities"; - - await sendInputWithMockedResponse( - ideMessenger, - INPUT, - PARALLEL_TOOL_CALL_RESPONSE, - ); - - // Wait for the message to be processed - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Test our utility functions work with the new state - const state = store.getState(); - - // Import the utility functions to test them - const { - findAllCurToolCalls: findCurrentToolCalls, - hasCurrentToolCalls, - findToolCallById: findToolCall, - } = await import("../../../redux/util"); - - // Test findCurrentToolCalls finds both tool calls - const currentToolCalls = findCurrentToolCalls(state.session.history); - expect(currentToolCalls).toHaveLength(2); - expect(currentToolCalls[0].toolCallId).toBe( - "toolu_0112JmA95qW6WhAsvkKb7Avp", - ); - expect(currentToolCalls[1].toolCallId).toBe( - "toolu_01UFK4ZUmbpkeFJGg7mdoT6T", - ); - - // Test hasCurrentToolCalls returns true - expect(hasCurrentToolCalls(state.session.history)).toBe(true); - - // Test findToolCall can find specific tool calls by ID - const toolCall1 = findToolCall( - state.session.history, - "toolu_0112JmA95qW6WhAsvkKb7Avp", - ); - const toolCall2 = findToolCall( - state.session.history, - "toolu_01UFK4ZUmbpkeFJGg7mdoT6T", - ); - expect(toolCall1?.toolCall.function.name).toBe("get_weather"); - expect(toolCall2?.toolCall.function.name).toBe("get_weather"); - expect(toolCall1?.toolCall.function.arguments).toContain("San Francisco"); - expect(toolCall2?.toolCall.function.arguments).toContain("Monterey"); - }); - - test("should complete streaming but hide ResponseActions when pending tool calls exist", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - const INPUT = "Read a file using the read_file tool"; - - await sendInputWithMockedResponse( - ideMessenger, - INPUT, - PARALLEL_TOOL_CALL_RESPONSE, - ); - - // Wait for the message to be processed - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Verify streaming is complete (so tool calls can be shown) - const state = store.getState(); - expect(state.session.isStreaming).toBe(false); - - // Verify we have pending tool calls - const { findAllCurToolCallsByStatus: findCurrentToolCallsByStatus } = - await import("../../../redux/util"); - const pendingToolCalls = findCurrentToolCallsByStatus( - state.session.history, - "generated", - ); - - expect(pendingToolCalls).toHaveLength(2); - - // Note: ResponseActions should be hidden by the hasPendingToolCalls condition in StepContainer - // The individual tool calls should now show with "Continue wants to..." text and accept/reject buttons - }); - - test("should show tool name in pending toolbar instead of generic text", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - // Test with single tool call to check the specific name display - // Use get_weather which should stay in generated status for this test - const SINGLE_TOOL_CALL_RESPONSE: ChatMessage[] = [ - { - role: "assistant", - content: "I'll check the weather for you.", - toolCalls: [ - { - id: "single-tool-call", - type: "function", - function: { - name: "get_weather", - arguments: JSON.stringify({ - location: "San Francisco, CA", - }), - }, - }, - ], - }, - ]; - - await sendInputWithMockedResponse( - ideMessenger, - "Check weather", - SINGLE_TOOL_CALL_RESPONSE, - ); - - // Wait for processing - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - const state = store.getState(); - const { findAllCurToolCallsByStatus: findCurrentToolCallsByStatus } = - await import("../../../redux/util"); - const pendingToolCalls = findCurrentToolCallsByStatus( - state.session.history, - "generated", - ); - - // Should have one pending tool call with the correct name - expect(pendingToolCalls).toHaveLength(1); - expect(pendingToolCalls[0].toolCall.function.name).toBe("get_weather"); - }); - - test("should show individual tool call UI with 'Continue wants to...' text", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - // Test with a tool that requires approval (not auto-executed) - const TOOL_CALL_RESPONSE: ChatMessage[] = [ - { - role: "assistant", - content: "I'll use a tool that requires approval.", - toolCalls: [ - { - id: "approval-required-tool-call", - type: "function", - function: { - name: "unknown_tool_requiring_approval", - arguments: JSON.stringify({ - param: "test.js", - }), - }, - }, - ], - }, - ]; - - await sendInputWithMockedResponse( - ideMessenger, - "Use a tool", - TOOL_CALL_RESPONSE, - ); - - // Wait for processing - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - const state = store.getState(); - - // Verify we have a pending tool call - const { findAllCurToolCallsByStatus: findCurrentToolCallsByStatus } = - await import("../../../redux/util"); - const pendingToolCalls = findCurrentToolCallsByStatus( - state.session.history, - "generated", - ); - expect(pendingToolCalls).toHaveLength(1); - expect(pendingToolCalls[0].toolCall.function.name).toBe( - "unknown_tool_requiring_approval", - ); - - // Verify the individual tool call UI should now show up in the DOM - // Since we fixed Chat.tsx to use toolCallStates instead of toolCallState, - // the ToolCallDiv components should now render - const state2 = store.getState(); - const history = state2.session.history; - - // Find the message with tool calls - const messageWithToolCalls = history.find( - (item) => - item.message.role === "assistant" && item.toolCallStates?.length, - ); - - // Verify that both condition parts are met for rendering in Chat.tsx: - // 1. item.message.toolCalls exists - // 2. item.toolCallStates exists - expect((messageWithToolCalls?.message as any).toolCalls).toBeDefined(); - expect(messageWithToolCalls?.toolCallStates).toBeDefined(); - expect(messageWithToolCalls?.toolCallStates).toHaveLength(1); - }); - - test("should show all pending tool calls requiring permissions simultaneously", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - // Test with multiple tools that require approval - const MULTIPLE_TOOL_CALLS_RESPONSE: ChatMessage[] = [ - { - role: "assistant", - content: "I'll use multiple tools that require approval.", - toolCalls: [ - { - id: "approval-required-tool-call-1", - type: "function", - function: { - name: "write_file", - arguments: JSON.stringify({ - file_path: "test1.js", - content: "console.log('test1');", - }), - }, - }, - { - id: "approval-required-tool-call-2", - type: "function", - function: { - name: "run_terminal_command", - arguments: JSON.stringify({ - command: "npm test", - }), - }, - }, - { - id: "approval-required-tool-call-3", - type: "function", - function: { - name: "edit_file", - arguments: JSON.stringify({ - file_path: "test2.js", - content: "console.log('test2');", - }), - }, - }, - ], - }, - ]; - await sendInputWithMockedResponse( ideMessenger, "Use multiple tools", - MULTIPLE_TOOL_CALLS_RESPONSE, - ); - - // Wait for processing - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - const state = store.getState(); - - // Verify we have multiple pending tool calls - const { findAllCurToolCallsByStatus: findCurrentToolCallsByStatus } = - await import("../../../redux/util"); - const pendingToolCalls = findCurrentToolCallsByStatus( - state.session.history, - "generated", - ); - expect(pendingToolCalls).toHaveLength(3); - - // Verify all tool calls are in "generated" status (requiring permissions) - expect(pendingToolCalls[0].toolCall.function.name).toBe("write_file"); - expect(pendingToolCalls[0].status).toBe("generated"); - expect(pendingToolCalls[1].toolCall.function.name).toBe( - "run_terminal_command", - ); - expect(pendingToolCalls[1].status).toBe("generated"); - expect(pendingToolCalls[2].toolCall.function.name).toBe("edit_file"); - expect(pendingToolCalls[2].status).toBe("generated"); - - // The key test: All pending tool calls should be visible in the toolbar simultaneously - // This verifies that the PendingToolCallToolbar shows all pending tools at once - // rather than prompting for permissions one at a time - - // Verify the PendingToolCallToolbar would show all three tool calls - // by checking that all three are in the "generated" state - const allGeneratedCalls = pendingToolCalls.filter( - (call) => call.status === "generated", - ); - expect(allGeneratedCalls).toHaveLength(3); - - // This test documents the expected behavior: all pending tool calls should - // be shown simultaneously in the UI, not one at a time - }); - - test("should keep parallel tool calls in same assistant message during streaming", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - await sendInputWithMockedResponse( - ideMessenger, - "Use both tools in parallel", PARALLEL_TOOL_CALL_RESPONSE, ); - // Wait for processing await act(async () => { await new Promise((resolve) => setTimeout(resolve, 100)); }); - const state = store.getState(); - const history = state.session.history; - - // Count assistant messages - const assistantMessages = history.filter(item => item.message.role === "assistant"); - console.log("Assistant messages:", assistantMessages.length); - - // Debug: log the assistant message structure - if (assistantMessages.length > 0) { - const assistantMessage = assistantMessages[0]; - console.log("Assistant message content:", assistantMessage.message.content); - console.log("Assistant message toolCallStates:", assistantMessage.toolCallStates); - console.log("Assistant message toolCalls:", (assistantMessage.message as any).toolCalls); - } - - // The CRITICAL test: there should be only ONE assistant message with BOTH tool calls - expect(assistantMessages).toHaveLength(1); - - const assistantMessage = assistantMessages[0]; - - // Check if toolCallStates exists and has the right length - if (assistantMessage.toolCallStates) { - expect(assistantMessage.toolCallStates).toHaveLength(2); - expect(assistantMessage.message.content).toContain("I'll call the get_weather function in parallel"); - - // Verify both tool calls are present - const toolCallIds = assistantMessage.toolCallStates.map(tc => tc.toolCallId); - expect(toolCallIds).toContain("toolu_0112JmA95qW6WhAsvkKb7Avp"); - expect(toolCallIds).toContain("toolu_01UFK4ZUmbpkeFJGg7mdoT6T"); - } else { - console.log("toolCallStates is undefined/null, this indicates the streaming logic isn't working correctly"); - // For now, just verify the message exists - expect(assistantMessage.message.content).toContain("I'll call the get_weather function in parallel"); - } - }); - - test("should handle real streaming deltas and preserve content", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - await sendInputWithMockedResponse( - ideMessenger, - "Use both tools in parallel with streaming", - PARALLEL_TOOL_CALL_STREAMING_RESPONSE, - ); - - // Wait for processing - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - const state = store.getState(); - const history = state.session.history; - - // Count assistant messages - const assistantMessages = history.filter(item => item.message.role === "assistant"); - - // Should still have only ONE assistant message after streaming - expect(assistantMessages).toHaveLength(1); - - const assistantMessage = assistantMessages[0]; - - // CRITICAL: Original content should be preserved - expect(assistantMessage.message.content).toContain("I'll call the get_weather function in parallel"); - - // Should have both tool calls after streaming completes - expect(assistantMessage.toolCallStates).toHaveLength(2); - - // Verify both tool calls are present and properly constructed - const toolCallIds = assistantMessage.toolCallStates!.map(tc => tc.toolCallId); - expect(toolCallIds).toContain("toolu_0112JmA95qW6WhAsvkKb7Avp"); - expect(toolCallIds).toContain("toolu_01UFK4ZUmbpkeFJGg7mdoT6T"); - - // Verify the arguments were properly assembled from deltas - const firstToolCall = assistantMessage.toolCallStates!.find(tc => tc.toolCallId === "toolu_0112JmA95qW6WhAsvkKb7Avp"); - const secondToolCall = assistantMessage.toolCallStates!.find(tc => tc.toolCallId === "toolu_01UFK4ZUmbpkeFJGg7mdoT6T"); - - expect(firstToolCall?.toolCall.function.arguments).toBe("{\"location\": \"San Francisco, CA\"}"); - expect(secondToolCall?.toolCall.function.arguments).toBe("{\"location\": \"Monterey, CA\"}"); - }); - - test("should show 'Performing N actions' UI for parallel tool calls", async () => { - const { ideMessenger, store, container } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - await sendInputWithMockedResponse( - ideMessenger, - "Use both tools in parallel", - PARALLEL_TOOL_CALL_RESPONSE, - ); - - // Wait for processing - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Look for the "Performing N actions" text in the DOM - const performingText = container.querySelector('[data-testid="performing-actions"]') || - container.querySelector(':contains("Performing")'); - - if (performingText) { - expect(performingText.textContent).toContain("Performing 2 actions"); - } else { - // If not found, log what we do have for debugging - console.log("DOM content:", container.innerHTML); - throw new Error("Could not find 'Performing N actions' text in DOM"); - } - }); - - test("should show 'Performing N actions' UI for streaming parallel tool calls", async () => { - const { ideMessenger, store, container } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - await sendInputWithMockedResponse( - ideMessenger, - "Use both tools in parallel with streaming", - PARALLEL_TOOL_CALL_STREAMING_RESPONSE, - ); - - // Wait for processing - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Look for the "Performing N actions" text in the DOM - const performingText = container.querySelector('[data-testid="performing-actions"]'); - - if (performingText) { - expect(performingText.textContent).toContain("Performing 2 actions"); - } else { - // If not found, log what we do have for debugging - console.log("DOM content:", container.innerHTML); - throw new Error("Could not find 'Performing N actions' text in DOM"); - } - }); - - test("should show assistant content AND tool calls in UI", async () => { - const { ideMessenger, store, container } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - await sendInputWithMockedResponse( - ideMessenger, - "Show both content and tool calls", - PARALLEL_TOOL_CALL_STREAMING_RESPONSE, - ); - - // Wait for processing - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - const domText = container.textContent || ""; - - // CRITICAL: Both the assistant content AND the tool calls should be visible - expect(domText).toContain("I'll call the get_weather function in parallel"); - expect(domText).toContain("Performing 2 actions"); - }); - - test("should reproduce the tool output matching failure", async () => { - // Create a direct test to reproduce the core error - // Hypothesis: The error occurs when tool output messages have IDs that don't match tool call IDs - - // Create history with intentional ID mismatch - const historyWithMismatch = [ - { - message: { - role: "user" as const, - content: "Test parallel tool calls", - }, - contextItems: [], - }, - { - message: { - role: "assistant" as const, - content: "I'll use both tools in parallel", - toolCalls: [ - { - id: "toolu_CORRECT_ID_A", - type: "function" as const, - function: { - name: "read_file", - arguments: '{"filepath": "test.js"}', - }, - }, - { - id: "toolu_CORRECT_ID_B", - type: "function" as const, - function: { - name: "ls", - arguments: '{"dirPath": "/"}', - }, - }, - ], - }, - contextItems: [], - toolCallStates: [ - { - toolCallId: "toolu_CORRECT_ID_A", - toolCall: { - id: "toolu_CORRECT_ID_A", - type: "function" as const, - function: { - name: "read_file", - arguments: '{"filepath": "test.js"}', - }, - }, - status: "done" as const, - parsedArgs: { filepath: "test.js" }, - }, - { - toolCallId: "toolu_CORRECT_ID_B", - toolCall: { - id: "toolu_CORRECT_ID_B", - type: "function" as const, - function: { - name: "ls", - arguments: '{"dirPath": "/"}', - }, - }, - status: "done" as const, - parsedArgs: { dirPath: "/" }, - }, - ], - }, - { - message: { - role: "tool" as const, - content: "File content here", - toolCallId: "toolu_WRONG_ID_A", // This ID doesn't match! - }, - contextItems: [], - }, - { - message: { - role: "tool" as const, - content: "Directory listing here", - toolCallId: "toolu_WRONG_ID_B", // This ID doesn't match! - }, - contextItems: [], - }, - ]; - - // Test constructMessages directly - try { - const { constructMessages } = await import("../../../redux/util/constructMessages"); - - console.log("TESTING: Direct constructMessages call with ID mismatch"); - - const { messages } = constructMessages( - historyWithMismatch, - "Test system message", - [], - {} - ); - - console.log("UNEXPECTED: constructMessages succeeded when it should have failed"); - console.log("Generated messages count:", messages.length); - console.log("Generated messages roles:", messages.map(m => m.role)); - - } catch (error) { - console.log("ERROR caught in constructMessages:", error); - if (error instanceof Error && error.message.includes("no tool call found to match tool output")) { - console.log("REPRODUCED THE ERROR!"); - console.log("Error message:", error.message); - throw error; // Re-throw to make test fail and show the error - } - } - - // Now test with core compileChatMessages directly to see if we can trigger the exact error - try { - console.log("TESTING: Direct call to core compileChatMessages"); - - // Import compileChatMessages from core - const { compileChatMessages } = await import("../../../../../core/llm/countTokens"); - - // Convert our history to the format expected by core - const coreMessages = historyWithMismatch.map(item => item.message); - - compileChatMessages({ - modelName: "test-model", - msgs: coreMessages, - contextLength: 8000, - maxTokens: 1000, - supportsImages: false, - }); - - console.log("UNEXPECTED: compileChatMessages succeeded when it should have failed"); - - } catch (error) { - console.log("ERROR caught in compileChatMessages:", error); - if (error instanceof Error && error.message.includes("no tool call found to match tool output")) { - console.log("REPRODUCED THE CORE ERROR!"); - console.log("Error message:", error.message); - - // This is the exact error we're trying to fix - let's analyze it - expect(error.message).toContain("no tool call found to match tool output for id"); - return; // Test passes if we reproduced the error - } - throw error; // Re-throw unexpected errors - } - - // If we get here, neither test reproduced the error - throw new Error("Failed to reproduce the tool output matching error"); - }); - - test("should reproduce the tool_result blocks error", async () => { - // This test reproduces the error: "tool_use ids were found without tool_result blocks immediately after" - // The error occurs when we have tool_use blocks but the corresponding tool_result blocks are missing - - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - // Test with parallel tool calls that should generate tool_result blocks - const PARALLEL_TOOL_CALLS: ChatMessage[] = [ - { - role: "assistant", - content: "I'll use both tools in parallel", - toolCalls: [ - { - id: "toolu_01PVG8miTDP6C3SsvVejKMTZ", - type: "function", - function: { name: "read_file", arguments: '{"filepath": "test.js"}' }, - }, - { - id: "toolu_02ABC123DEF456GHI789JKL", - type: "function", - function: { name: "write_file", arguments: '{"filepath": "output.js", "content": "test"}' }, - }, - ], - }, - ]; - - await sendInputWithMockedResponse( - ideMessenger, - "Use both tools", - PARALLEL_TOOL_CALLS, - ); - - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - const state = store.getState(); - const history = state.session.history; - - console.log("\nTesting tool_result blocks generation:"); - console.log("Number of history items:", history.length); - - // Check if we have the assistant message with tool calls - const assistantMessage = history.find( - (item) => item.message.role === "assistant" && item.toolCallStates?.length - ); - - if (assistantMessage) { - console.log("Assistant message found with tool calls:", assistantMessage.toolCallStates?.length); - console.log("Tool call IDs:", assistantMessage.toolCallStates?.map(s => s.toolCallId)); - } - - // Now trigger the core message compilation to see if it produces the error - try { - const { constructMessages } = await import("../../../redux/util/constructMessages"); - - const withoutMessageIds = history.map((item) => { - const { id, ...messageWithoutId } = item.message; - return { ...item, message: messageWithoutId }; - }); - - const { messages } = constructMessages( - withoutMessageIds, - "Test system message", - [], - {} - ); - - console.log("\nGenerated messages:"); - messages.forEach((msg, i) => { - console.log(` ${i}: ${msg.role} - ${msg.role === 'tool' ? `toolCallId: ${(msg as any).toolCallId}` : msg.role === 'assistant' ? `toolCalls: ${(msg as any).toolCalls?.map((tc: any) => tc.id).join(', ')}` : 'content'}`); - }); - - console.log("\nNow testing if this causes the tool_result error..."); - - // This should potentially cause the tool_result error if the message format is wrong - const { compileChatMessages } = await import("../../../../../core/llm/countTokens"); - - compileChatMessages({ - modelName: "claude-3-sonnet-20240229", // Using Claude model that expects tool_result format - msgs: messages, - contextLength: 8000, - maxTokens: 1000, - supportsImages: false, - }); - - console.log("No error occurred - tool_result blocks were generated correctly"); - - } catch (error) { - console.log("ERROR:", error); - if (error instanceof Error && error.message.includes("tool_result")) { - console.log("REPRODUCED THE tool_result ERROR!"); - console.log("This confirms the issue with missing tool_result blocks"); - expect(error.message).toContain("tool_result"); - } else { - throw error; // Re-throw unexpected errors - } - } - }); - - test("should test Claude API format conversion with parallel tool calls", async () => { - // This test checks if our message format is correct for Claude's API - // The error "tool_use ids were found without tool_result blocks immediately after" - // suggests the tool_use and tool_result blocks are not properly ordered - - // Create a direct test with the message format that would be sent to Claude - const messagesForClaude = [ - { - role: "user", - content: "Use both tools in parallel", - }, - { - role: "assistant", - content: "I'll use both tools", - toolCalls: [ - { - id: "toolu_01PVG8miTDP6C3SsvVejKMTZ", - type: "function", - function: { name: "read_file", arguments: '{"filepath": "test.js"}' }, - }, - { - id: "toolu_02ABC123DEF456GHI789JKL", - type: "function", - function: { name: "write_file", arguments: '{"filepath": "output.js", "content": "test"}' }, - }, - ], - }, - { - role: "tool", - content: "File content here", - toolCallId: "toolu_01PVG8miTDP6C3SsvVejKMTZ", - }, - { - role: "tool", - content: "File written successfully", - toolCallId: "toolu_02ABC123DEF456GHI789JKL", - }, - ]; - - console.log("\nTesting Claude API format conversion:"); - console.log("Original messages:"); - messagesForClaude.forEach((msg, i) => { - console.log(` ${i}: ${msg.role} - ${msg.role === 'tool' ? `toolCallId: ${(msg as any).toolCallId}` : msg.role === 'assistant' ? `toolCalls: ${(msg as any).toolCalls?.map((tc: any) => tc.id).join(', ')}` : 'content'}`); - }); - - // Test what happens when we pass this through compileChatMessages - try { - const { compileChatMessages } = await import("../../../../../core/llm/countTokens"); - - const result = compileChatMessages({ - modelName: "claude-3-sonnet-20240229", - msgs: messagesForClaude as any, - contextLength: 8000, - maxTokens: 1000, - supportsImages: false, - }); - - console.log("\nAfter compileChatMessages:"); - result.forEach((msg, i) => { - console.log(` ${i}: ${msg.role} - ${msg.role === 'tool' ? `toolCallId: ${(msg as any).toolCallId}` : msg.role === 'assistant' ? `toolCalls: ${(msg as any).toolCalls?.map((tc: any) => tc.id).join(', ')}` : 'content'}`); - }); - - // Now test what the Anthropic LLM would do with this - const anthropicMessages = result.map((msg) => { - if (msg.role === "tool") { - return { - role: "user", - content: [{ - type: "tool_result", - tool_use_id: (msg as any).toolCallId, - content: msg.content, - }], - }; - } else if (msg.role === "assistant" && (msg as any).toolCalls) { - return { - role: "assistant", - content: (msg as any).toolCalls.map((toolCall: any) => ({ - type: "tool_use", - id: toolCall.id, - name: toolCall.function?.name, - input: JSON.parse(toolCall.function?.arguments || '{}'), - })), - }; - } else { - return { - role: msg.role, - content: typeof msg.content === 'string' ? [{ type: "text", text: msg.content }] : msg.content, - }; - } - }); - - console.log("\nAnthropie API format:"); - anthropicMessages.forEach((msg, i) => { - console.log(` ${i}: ${msg.role}`); - if (Array.isArray(msg.content)) { - msg.content.forEach((content: any, j: number) => { - if (content.type === "tool_use") { - console.log(` ${j}: tool_use - id: ${content.id}, name: ${content.name}`); - } else if (content.type === "tool_result") { - console.log(` ${j}: tool_result - tool_use_id: ${content.tool_use_id}`); - } else { - console.log(` ${j}: ${content.type}`); - } - }); - } - }); - - // Check the problematic pattern - let hasToolUseWithoutImmediateResult = false; - for (let i = 0; i < anthropicMessages.length - 1; i++) { - const currentMsg = anthropicMessages[i]; - const nextMsg = anthropicMessages[i + 1]; - - if (currentMsg.role === "assistant" && - Array.isArray(currentMsg.content) && - currentMsg.content.some((c: any) => c.type === "tool_use")) { - - // Check if the next message contains tool_result blocks - const hasToolResult = nextMsg.role === "user" && - Array.isArray(nextMsg.content) && - nextMsg.content.some((c: any) => c.type === "tool_result"); - - if (!hasToolResult) { - hasToolUseWithoutImmediateResult = true; - console.log(`\nPROBLEM DETECTED: tool_use at index ${i} not immediately followed by tool_result`); - } - } - } - - if (hasToolUseWithoutImmediateResult) { - console.log("\nThis message structure would cause the Claude API error!"); - } else { - console.log("\nMessage structure looks correct for Claude API"); - } - - } catch (error) { - console.log("ERROR:", error); - throw error; - } - }); - - test("should test the problematic scenario with missing tool outputs", async () => { - // This test simulates what might happen in real usage: - // assistant message with tool calls but no tool output messages yet - - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - // Create a scenario where we have tool calls but no tool outputs yet - const TOOL_CALLS_WITHOUT_OUTPUTS: ChatMessage[] = [ - { - role: "assistant", - content: "I'll use both tools in parallel", - toolCalls: [ - { - id: "toolu_01PVG8miTDP6C3SsvVejKMTZ", - type: "function", - function: { name: "read_file", arguments: '{"filepath": "test.js"}' }, - }, - { - id: "toolu_02ABC123DEF456GHI789JKL", - type: "function", - function: { name: "write_file", arguments: '{"filepath": "output.js", "content": "test"}' }, - }, - ], - }, - // NOTE: No tool output messages - this might cause the error - ]; - - await sendInputWithMockedResponse( - ideMessenger, - "Use both tools", - TOOL_CALLS_WITHOUT_OUTPUTS, - ); - - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - const state = store.getState(); - const history = state.session.history; - - console.log("\nTesting scenario with missing tool outputs:"); - console.log("Number of history items:", history.length); - - // Check the state - const assistantMessage = history.find( - (item) => item.message.role === "assistant" && item.toolCallStates?.length - ); - - if (assistantMessage) { - console.log("Assistant message found with tool calls:", assistantMessage.toolCallStates?.length); - console.log("Tool call statuses:", assistantMessage.toolCallStates?.map(s => `${s.toolCallId}: ${s.status}`)); - } - - // Check if there are tool output messages - const toolMessages = history.filter(item => item.message.role === "tool"); - console.log("Tool output messages:", toolMessages.length); - - // Now test message construction - try { - const { constructMessages } = await import("../../../redux/util/constructMessages"); - - const withoutMessageIds = history.map((item) => { - const { id, ...messageWithoutId } = item.message; - return { ...item, message: messageWithoutId }; - }); - - const { messages } = constructMessages( - withoutMessageIds, - "Test system message", - [], - {} - ); - - console.log("\nGenerated messages:"); - messages.forEach((msg, i) => { - console.log(` ${i}: ${msg.role} - ${msg.role === 'tool' ? `toolCallId: ${(msg as any).toolCallId}` : msg.role === 'assistant' ? `toolCalls: ${(msg as any).toolCalls?.map((tc: any) => tc.id).join(', ')}` : 'content'}`); - }); - - console.log("\nThis scenario shows:"); - console.log("- Assistant message with tool calls:", messages.some(m => m.role === 'assistant' && (m as any).toolCalls)); - console.log("- Tool result messages:", messages.filter(m => m.role === 'tool').length); - - // Test if this causes the error - const { compileChatMessages } = await import("../../../../../core/llm/countTokens"); - - compileChatMessages({ - modelName: "claude-3-sonnet-20240229", - msgs: messages, - contextLength: 8000, - maxTokens: 1000, - supportsImages: false, - }); - - console.log("No error occurred"); - - } catch (error) { - console.log("ERROR:", error); - if (error instanceof Error && (error.message.includes("tool_result") || error.message.includes("tool_use"))) { - console.log("REPRODUCED THE tool_result/tool_use ERROR!"); - console.log("This confirms the issue with missing tool_result blocks"); - expect(error.message).toMatch(/tool_(result|use)/); - } else { - throw error; // Re-throw unexpected errors - } - } - }); - - test("should isolate the synchronization issue", async () => { - // Test if our synchronization function is causing ID mismatches - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - // Stream in parallel tool calls - const PARALLEL_TOOL_CALLS: ChatMessage[] = [ - { - role: "assistant", - content: "I'll use both tools in parallel", - toolCalls: [ - { - id: "original_id_A", - type: "function", - function: { name: "tool_A", arguments: "{}" }, - }, - { - id: "original_id_B", - type: "function", - function: { name: "tool_B", arguments: "{}" }, - }, - ], - }, - // Tool outputs with matching IDs - { - role: "tool", - content: "Output A", - toolCallId: "original_id_A", - }, - { - role: "tool", - content: "Output B", - toolCallId: "original_id_B", - }, - ]; - - await sendInputWithMockedResponse( - ideMessenger, - "Test parallel tools", - PARALLEL_TOOL_CALLS, - ); - - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - const state = store.getState(); - const history = state.session.history; - - // Find the assistant message - const assistantMessage = history.find( - (item) => item.message.role === "assistant" && item.toolCallStates?.length - ); - - expect(assistantMessage).toBeDefined(); - - console.log("BEFORE TOOL EXECUTION:"); - console.log("- Tool call IDs from states:", assistantMessage!.toolCallStates?.map(s => s.toolCallId)); - console.log("- Tool call IDs from message:", (assistantMessage!.message as any).toolCalls?.map((tc: any) => tc.id)); - - // Now simulate what happens during tool execution - trigger tool state updates - const { setToolGenerated } = await import("../../../redux/slices/sessionSlice"); - - // Simulate tool execution state changes - await act(async () => { - store.dispatch(setToolGenerated({ - toolCallId: "original_id_A", - tools: [{ function: { name: "tool_A" } }] as any - })); - store.dispatch(setToolGenerated({ - toolCallId: "original_id_B", - tools: [{ function: { name: "tool_B" } }] as any - })); - }); - - // Check if IDs changed after tool state updates - const updatedState = store.getState(); - const updatedHistory = updatedState.session.history; - const updatedAssistantMessage = updatedHistory.find( - (item) => item.message.role === "assistant" && item.toolCallStates?.length - ); - - console.log("AFTER TOOL EXECUTION:"); - console.log("- Tool call IDs from states:", updatedAssistantMessage!.toolCallStates?.map(s => s.toolCallId)); - console.log("- Tool call IDs from message:", (updatedAssistantMessage!.message as any).toolCalls?.map((tc: any) => tc.id)); - - // Find tool output messages - const toolOutputs = updatedHistory.filter(item => item.message.role === "tool"); - console.log("- Tool output IDs:", toolOutputs.map(item => (item.message as any).toolCallId)); - - // Now test if constructMessages works with this state - try { - const { constructMessages } = await import("../../../redux/util/constructMessages"); - - const withoutMessageIds = updatedHistory.map((item) => { - const { id, ...messageWithoutId } = item.message; - return { ...item, message: messageWithoutId }; - }); - - const { messages } = constructMessages( - withoutMessageIds, - "Test system message", - [], - {} - ); - - console.log("constructMessages succeeded"); - - // Now test core compileChatMessages - const { compileChatMessages } = await import("../../../../../core/llm/countTokens"); - - const coreMessages = messages; - - compileChatMessages({ - modelName: "test-model", - msgs: coreMessages, - contextLength: 8000, - maxTokens: 1000, - supportsImages: false, - }); - - console.log("compileChatMessages succeeded"); - - } catch (error) { - console.log("ERROR during message processing:", error); - if (error instanceof Error && error.message.includes("no tool call found to match tool output")) { - console.log("REPRODUCED THE ERROR AFTER TOOL EXECUTION!"); - console.log("This proves the issue is in our synchronization during tool execution"); - throw error; - } - } - }); - - test("should demonstrate the core logic issue with parallel tool calls", async () => { - // This test directly demonstrates the issue in the core compileChatMessages function - // without involving the GUI layer - - // Create a message history that represents parallel tool calls - const coreMessages = [ - { - role: "user" as const, - content: "Use both tools in parallel", - }, - { - role: "assistant" as const, - content: "I'll use both tools", - toolCalls: [ - { - id: "tool_A_id", - type: "function" as const, - function: { name: "tool_A", arguments: "{}" }, - }, - { - id: "tool_B_id", - type: "function" as const, - function: { name: "tool_B", arguments: "{}" }, - }, - ], - }, - { - role: "tool" as const, - content: "Output from tool A", - toolCallId: "tool_A_id", - }, - { - role: "tool" as const, - content: "Output from tool B", - toolCallId: "tool_B_id", - }, - ]; - - console.log("\nTesting core compileChatMessages with parallel tool calls:"); - console.log("Message structure:"); - coreMessages.forEach((msg, i) => { - console.log(` ${i}: ${msg.role} - ${msg.role === 'tool' ? `toolCallId: ${(msg as any).toolCallId}` : msg.role === 'assistant' ? `toolCalls: ${msg.toolCalls?.map(tc => tc.id).join(', ')}` : 'content'}`); - }); - - console.log("\nThe issue: compileChatMessages processes messages in reverse order:"); - console.log(" 1. Pops tool message with ID 'tool_B_id' (last message)"); - console.log(" 2. Pops tool message with ID 'tool_A_id' (expecting assistant message)"); - console.log(" 3. Tries to match 'tool_B_id' with tool_A_id message (which has no toolCalls)"); - console.log(" 4. FAILS because tool messages don't have toolCalls arrays\n"); - - try { - const { compileChatMessages } = await import("../../../../../core/llm/countTokens"); - - compileChatMessages({ - modelName: "test-model", - msgs: coreMessages, - contextLength: 8000, - maxTokens: 1000, - supportsImages: false, - }); - - console.log("UNEXPECTED: compileChatMessages succeeded when it should have failed"); - - } catch (error) { - console.log("EXPECTED ERROR:", error); - if (error instanceof Error && error.message.includes("no tool call found to match tool output")) { - console.log("\nThis confirms the core issue: the reverse processing logic doesn't handle parallel tool calls correctly"); - // Don't throw - this is expected behavior we're documenting - expect(error.message).toContain("no tool call found to match tool output for id"); - } else { - throw error; // Unexpected error - } - } - }); - - test("should handle individual tool call accept/reject in multiple tool calls without breaking other calls", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - // Test with multiple tools that require approval - const MULTIPLE_TOOL_CALLS_RESPONSE: ChatMessage[] = [ - { - role: "assistant", - content: "I'll use multiple tools that require approval.", - toolCalls: [ - { - id: "tool-call-1", - type: "function", - function: { - name: "write_file", - arguments: JSON.stringify({ - file_path: "test1.js", - content: "console.log('test1');", - }), - }, - }, - { - id: "tool-call-2", - type: "function", - function: { - name: "write_file", - arguments: JSON.stringify({ - file_path: "test2.js", - content: "console.log('test2');", - }), - }, - }, - ], - }, - ]; - - await sendInputWithMockedResponse( - ideMessenger, - "Use multiple tools", - MULTIPLE_TOOL_CALLS_RESPONSE, - ); - - // Wait for processing - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - const { findAllCurToolCallsByStatus } = await import( - "../../../redux/util" - ); - const { callToolById } = await import( - "../../../redux/thunks/callToolById" - ); - - // Verify we have multiple pending tool calls - let state = store.getState(); - let pendingToolCalls = findAllCurToolCallsByStatus( - state.session.history, - "generated", - ); - expect(pendingToolCalls).toHaveLength(2); - expect(pendingToolCalls[0].toolCallId).toBe("tool-call-1"); - expect(pendingToolCalls[1].toolCallId).toBe("tool-call-2"); - - // Accept the first tool call - await act(async () => { - await store.dispatch(callToolById({ toolCallId: "tool-call-1" })); - }); - - // Wait for state update - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Check state after accepting first tool call - state = store.getState(); - pendingToolCalls = findAllCurToolCallsByStatus( - state.session.history, - "generated", - ); - - // The second tool call should still be pending - expect(pendingToolCalls).toHaveLength(1); - expect(pendingToolCalls[0].toolCallId).toBe("tool-call-2"); - - // The first tool call should now be in "done" status - const completedToolCalls = findAllCurToolCallsByStatus( - state.session.history, - "done", - ); - - expect(completedToolCalls).toHaveLength(1); - expect(completedToolCalls[0].toolCallId).toBe("tool-call-1"); - }); - - test("should handle individual tool call cancellation in multiple tool calls without breaking other calls", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - // Test with multiple tools that require approval - const MULTIPLE_TOOL_CALLS_RESPONSE: ChatMessage[] = [ - { - role: "assistant", - content: "I'll use multiple tools that require approval.", - toolCalls: [ - { - id: "tool-call-1", - type: "function", - function: { - name: "write_file", - arguments: JSON.stringify({ - file_path: "test1.js", - content: "console.log('test1');", - }), - }, - }, - { - id: "tool-call-2", - type: "function", - function: { - name: "write_file", - arguments: JSON.stringify({ - file_path: "test2.js", - content: "console.log('test2');", - }), - }, - }, - ], - }, - ]; - - await sendInputWithMockedResponse( - ideMessenger, - "Use multiple tools", - MULTIPLE_TOOL_CALLS_RESPONSE, - ); - - // Wait for processing - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - const { findAllCurToolCallsByStatus } = await import( - "../../../redux/util" - ); - const { cancelToolCall } = await import( - "../../../redux/slices/sessionSlice" - ); + const { findAllCurToolCallsByStatus } = await import("../../../redux/util"); + const { cancelToolCall } = await import("../../../redux/slices/sessionSlice"); // Verify we have multiple pending tool calls let state = store.getState(); @@ -1595,11 +98,6 @@ describe("Parallel Tool Calls", () => { store.dispatch(cancelToolCall({ toolCallId: "tool-call-1" })); }); - // Wait for state update - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - // Check state after canceling first tool call state = store.getState(); pendingToolCalls = findAllCurToolCallsByStatus( @@ -1611,7 +109,7 @@ describe("Parallel Tool Calls", () => { expect(pendingToolCalls).toHaveLength(1); expect(pendingToolCalls[0].toolCallId).toBe("tool-call-2"); - // The first tool call should now be in "canceled" status + // The first tool call should now be canceled const canceledToolCalls = findAllCurToolCallsByStatus( state.session.history, "canceled", @@ -1619,4 +117,92 @@ describe("Parallel Tool Calls", () => { expect(canceledToolCalls).toHaveLength(1); expect(canceledToolCalls[0].toolCallId).toBe("tool-call-1"); }); -}); + + test("should handle streaming deltas for multiple tool calls", async () => { + const { ideMessenger, store } = await renderWithProviders(); + + await act(async () => { + addAndSelectMockLlm(store, ideMessenger); + }); + + // Simulate streaming behavior with deltas + const STREAMING_RESPONSE: ChatMessage[] = [ + { + role: "assistant", + content: "I'll call both tools in parallel.", + }, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "read_file", + arguments: "", + }, + }, + ], + }, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "read_file", + arguments: '{"filepath": "test.js"}', + }, + }, + ], + }, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-call-2", + type: "function", + function: { + name: "write_file", + arguments: '{"filepath": "output.js", "content": "test"}', + }, + }, + ], + }, + ]; + + await sendInputWithMockedResponse( + ideMessenger, + "Use both tools with streaming", + STREAMING_RESPONSE, + ); + + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 100)); + }); + + const state = store.getState(); + const history = state.session.history; + + // Should have only one assistant message after streaming + const assistantMessages = history.filter(item => item.message.role === "assistant"); + expect(assistantMessages).toHaveLength(1); + + const assistantMessage = assistantMessages[0]; + + // Should preserve original content + expect(assistantMessage.message.content).toContain("I'll call both tools in parallel"); + + // Should have both tool calls after streaming completes + expect(assistantMessage.toolCallStates).toHaveLength(2); + + // Verify tool calls are properly constructed + const toolCallIds = assistantMessage.toolCallStates!.map(tc => tc.toolCallId); + expect(toolCallIds).toContain("tool-call-1"); + expect(toolCallIds).toContain("tool-call-2"); + }); +}); \ No newline at end of file diff --git a/gui/src/redux/slices/sessionSlice.test.ts b/gui/src/redux/slices/sessionSlice.test.ts new file mode 100644 index 000000000..21f01c271 --- /dev/null +++ b/gui/src/redux/slices/sessionSlice.test.ts @@ -0,0 +1,418 @@ +import { ChatMessage } from "core"; +import { renderChatMessage } from "core/util/messageContent"; +import { v4 as uuidv4 } from "uuid"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { addToolCallDeltaToState } from "../../util/toolCallState"; +import { ChatHistoryItemWithMessageId, sessionSlice } from "./sessionSlice"; + +// Mock dependencies +vi.mock("uuid"); +vi.mock("core/util/messageContent"); +vi.mock("../../util/toolCallState"); + +const mockUuidv4 = vi.mocked(uuidv4); +const mockRenderChatMessage = vi.mocked(renderChatMessage); +const mockAddToolCallDeltaToState = vi.mocked(addToolCallDeltaToState); + +describe("sessionSlice streamUpdate", () => { + beforeEach(() => { + // Reset mocks before each test + vi.clearAllMocks(); + + // Mock uuidv4 to return predictable values + let callCount = 0; + mockUuidv4.mockImplementation(() => `mock-uuid-${++callCount}`); + + // Mock renderChatMessage to return content as is + mockRenderChatMessage.mockImplementation((message: ChatMessage) => { + if (typeof message.content === "string") { + return message.content; + } + return ""; + }); + + // Mock addToolCallDeltaToState + mockAddToolCallDeltaToState.mockImplementation((delta, state) => { + return { + status: "generating" as const, + toolCall: { + id: delta.id || "mock-tool-id", + type: "function" as const, + function: { + name: delta.function?.name || "mock-function", + arguments: delta.function?.arguments || "{}", + }, + }, + toolCallId: delta.id || "mock-tool-id", + parsedArgs: {}, + }; + }); + }); + + const createInitialState = () => ({ + lastSessionId: undefined, + allSessionMetadata: [], + history: [ + { + message: { + role: "user" as const, + content: "This is a test.", + id: "initial-user-message", + }, + contextItems: [], + }, + ] as ChatHistoryItemWithMessageId[], + isStreaming: false, + title: "Test Session", + id: "test-session-id", + streamAborter: new AbortController(), + symbols: {}, + mode: "chat" as const, + isInEdit: false, + codeBlockApplyStates: { + states: [], + curIndex: 0, + }, + newestToolbarPreviewForInput: {}, + isSessionMetadataLoading: false, + }); + + describe("Basic Chat Message", () => { + it("should append assistant message to history", () => { + const initialState = createInitialState(); + const action = { + type: "session/streamUpdate", + payload: [ + { + role: "assistant" as const, + content: "Here is a response to your message without thinking.", + }, + ], + }; + + const newState = sessionSlice.reducer(initialState, action); + + expect(newState.history).toHaveLength(2); + expect(newState.history[1].message.role).toBe("assistant"); + expect(newState.history[1].message.content).toBe( + "Here is a response to your message without thinking.", + ); + expect(newState.history[1].message.id).toBe("mock-uuid-1"); + expect(newState.history[1].contextItems).toEqual([]); + }); + }); + + describe("Chat Message With Thinking", () => { + it("should split thinking and assistant content correctly", () => { + const initialState = createInitialState(); + const action = { + type: "session/streamUpdate", + payload: [ + { + role: "assistant" as const, + content: + "I should send the user a response. Here is a response to your message with thinking.", + }, + ], + }; + + const newState = sessionSlice.reducer(initialState, action); + + expect(newState.history).toHaveLength(2); + + // Check reasoning + expect(newState.history[0].reasoning?.text).toBe( + "I should send the user a response.", + ); + + // Check assistant message + expect(newState.history[1].message.role).toBe("assistant"); + expect(newState.history[1].message.content).toBe( + "Here is a response to your message with thinking.", + ); + expect(newState.history[1].message.id).toBe("mock-uuid-1"); + }); + }); + + describe("Tool Call With Response", () => { + it("should handle tool call followed by tool response and assistant message", () => { + const initialState = createInitialState(); + const toolCallAction = { + type: "session/streamUpdate", + payload: [ + { + role: "assistant" as const, + content: "I should use a tool call.", + toolCalls: [ + { + id: "1234", + type: "function" as const, + function: { + name: "builtin_ls", + arguments: '{"dirPath":".","recursive":false}', + }, + }, + ], + }, + ], + }; + + let newState = sessionSlice.reducer(initialState, toolCallAction); + expect(newState.history).toHaveLength(2); + + // Check reasoning + expect(newState.history[0].reasoning?.text).toBe( + "I should use a tool call.", + ); + + // Check generating message + expect(newState.history[1].message.role).toBe("assistant"); + expect(newState.history[1].message.content).toBe(""); + expect(newState.history[1].toolCallStates?.[0]?.status).toBe("generating"); + expect(newState.history[1].toolCallStates?.[0]?.toolCallId).toBe("1234"); + + const toolResponseAction = { + type: "session/streamUpdate", + payload: [ + { + role: "tool" as const, + toolCallId: "1234", + content: "foo.txt\nbar.txt\nexample.php", + }, + { + role: "assistant" as const, + content: "I see, the tool found 3 files.", + }, + ], + }; + newState = sessionSlice.reducer(newState, toolResponseAction); + expect(newState.history).toHaveLength(4); + + // Check tool message + expect(newState.history[2].message.role).toBe("tool"); + expect(newState.history[2].message.content).toBe( + "foo.txt\nbar.txt\nexample.php", + ); + expect((newState.history[2].message as any).toolCallId).toBe("1234"); + + // Check final assistant message + expect(newState.history[3].message.role).toBe("assistant"); + expect(newState.history[3].message.content).toBe( + "I see, the tool found 3 files.", + ); + }); + }); + + describe("Tool Call With Streaming Response", () => { + it("should handle streaming assistant response after tool call", () => { + const initialState = createInitialState(); + const toolCallAction = { + type: "session/streamUpdate", + payload: [ + { + role: "assistant" as const, + content: "I should use a tool call.", + toolCalls: [ + { + id: "1234", + type: "function" as const, + function: { + name: "builtin_ls", + arguments: '{"dirPath":".","recursive":false}', + }, + }, + ], + }, + ], + }; + + let newState = sessionSlice.reducer(initialState, toolCallAction); + expect(newState.history).toHaveLength(2); + + // Check reasoning + expect(newState.history[0].reasoning?.text).toBe( + "I should use a tool call.", + ); + + // Check generating message + expect(newState.history[1].message.role).toBe("assistant"); + expect(newState.history[1].message.content).toBe(""); + expect(newState.history[1].toolCallStates?.[0]?.status).toBe("generating"); + expect(newState.history[1].toolCallStates?.[0]?.toolCallId).toBe("1234"); + + const toolResponseAction = { + type: "session/streamUpdate", + payload: [ + { + role: "tool" as const, + toolCallId: "1234", + content: "foo.txt\nbar.txt\nexample.php", + }, + { + role: "assistant" as const, + content: "", + }, + { + role: "assistant" as const, + content: "Good, ", + }, + { + role: "assistant" as const, + content: "I received a list", + }, + { + role: "assistant" as const, + content: " of files.", + }, + { + role: "assistant" as const, + content: "", + }, + { + role: "assistant" as const, + content: "\n", + }, + { + role: "assistant" as const, + content: "I see, ", + }, + { + role: "assistant" as const, + content: "the tool ", + }, + { + role: "assistant" as const, + content: "found 3 ", + }, + { + role: "assistant" as const, + content: "files.", + }, + ], + }; + + newState = sessionSlice.reducer(newState, toolResponseAction); + + expect(newState.history).toHaveLength(4); + + // Check tool message + expect(newState.history[2].message.role).toBe("tool"); + expect(newState.history[2].message.content).toBe( + "foo.txt\nbar.txt\nexample.php", + ); + + // Check response message + expect(newState.history[3].message.role).toBe("assistant"); + expect(newState.history[3].message.content).toBe( + "I see, the tool found 3 files.", + ); + expect(newState.history[3].reasoning?.text).toBe( + "Good, I received a list of files.", + ); + expect(newState.history[3].reasoning?.active).toBe(false); + }); + }); + + describe("Edge Cases", () => { + it("should handle empty history gracefully", () => { + const initialState = createInitialState(); + initialState.history = []; + + const action = { + type: "session/streamUpdate", + payload: [ + { + role: "assistant" as const, + content: "Hello", + }, + ], + }; + + const newState = sessionSlice.reducer(initialState, action); + + // Should not crash and history should remain empty + expect(newState.history).toHaveLength(0); + }); + + it("should handle redacted thinking messages", () => { + const initialState = createInitialState(); + const action = { + type: "session/streamUpdate", + payload: [ + { + role: "thinking" as const, + content: "This should be hidden", + redactedThinking: true, + }, + ], + }; + + const newState = sessionSlice.reducer(initialState, action); + + expect(newState.history).toHaveLength(2); + expect(newState.history[1].message.role).toBe("thinking"); + expect(newState.history[1].message.content).toBe( + "internal reasoning is hidden due to safety reasons", + ); + expect((newState.history[1].message as any).redactedThinking).toBe(true); + }); + + it("should handle signature updates for thinking messages", () => { + const initialState = createInitialState(); + // First add a thinking message + initialState.history.push({ + message: { + role: "thinking", + content: "Some thinking", + id: "thinking-message", + }, + contextItems: [], + }); + + const action = { + type: "session/streamUpdate", + payload: [ + { + role: "thinking" as const, + signature: "test-signature", + }, + ], + }; + + const newState = sessionSlice.reducer(initialState, action); + + expect(newState.history).toHaveLength(2); + expect((newState.history[1].message as any).signature).toBe( + "test-signature", + ); + }); + + it("should accumulate content for same role messages", () => { + const initialState = createInitialState(); + // Add an assistant message first + initialState.history.push({ + message: { + role: "assistant", + content: "Hello ", + id: "assistant-message", + }, + contextItems: [], + }); + + const action = { + type: "session/streamUpdate", + payload: [ + { + role: "assistant" as const, + content: "world!", + }, + ], + }; + + const newState = sessionSlice.reducer(initialState, action); + + expect(newState.history).toHaveLength(2); + expect(newState.history[1].message.content).toBe("Hello world!"); + }); + }); +}); diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 093a10b0b..07098f003 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -8,6 +8,7 @@ import { import { JSONContent } from "@tiptap/react"; import { ApplyState, + AssistantChatMessage, ChatHistoryItem, ChatMessage, ContextItem, @@ -18,6 +19,7 @@ import { RuleWithSource, Session, SessionMetadata, + ThinkingChatMessage, Tool, ToolCallState, } from "core"; @@ -71,7 +73,7 @@ const initialState: SessionState = { id: uuidv4(), streamAborter: new AbortController(), symbols: {}, - mode: "chat", + mode: "agent", isInEdit: false, codeBlockApplyStates: { states: [], @@ -333,12 +335,10 @@ export const sessionSlice = createSlice({ streamUpdate: (state, action: PayloadAction) => { if (state.history.length) { for (const message of action.payload) { - const lastItem = state.history[state.history.length - 1]; - const lastMessage = lastItem.message; + let lastItem = state.history[state.history.length - 1]; + let lastMessage = lastItem.message; if (message.role === "thinking" && message.redactedThinking) { - console.log("add redacted_thinking blocks"); - state.history.push({ message: { role: "thinking", @@ -351,6 +351,67 @@ export const sessionSlice = createSlice({ continue; } + const messageContent = message.content + ? renderChatMessage(message) + : ""; + + // OpenAI-compatible models in agent mode sometimes send + // all of their data in one message, so we handle that case early. + if (messageContent) { + const thinkMatches = messageContent.match( + /([\s\S]*)<\/think>([\s\S]*)/, + ); + if (thinkMatches) { + // The order that they seem to consistently use is: + // + // Thinking text + // Text to show to the user + + lastItem.reasoning = { + text: thinkMatches[1].trim(), + startAt: Date.now(), + endAt: Date.now(), + active: false, + }; + + // This is the chat message that we should show to the user. + // We always need to push this even if it is empty, + // because we cannot attach tool calls to a Thinking message. + // That would break `messageHasToolCallId`. + state.history.push({ + message: { + role: "assistant", + content: thinkMatches[2].trim(), + id: uuidv4(), + }, + contextItems: [], + }); + lastItem = state.history[state.history.length - 1]; + lastMessage = lastItem.message; + + if ( + (message.role === "assistant" || message.role === "thinking") && + message.toolCalls?.length + ) { + // Handle multiple tool calls + lastItem.toolCallStates = message.toolCalls.map( + (toolCallDelta) => + addToolCallDeltaToState(toolCallDelta, undefined), + ); + // We know this is one of these two types because we just added it + const curMessage = lastMessage as + | AssistantChatMessage + | ThinkingChatMessage; + curMessage.toolCalls = lastItem.toolCallStates.map( + (state) => state.toolCall, + ); + } + + return; + } + } + + // The remainder of this function handles streaming messages if ( lastMessage.role !== message.role || message.role === "tool" // Tool messages should always create new messages @@ -371,104 +432,96 @@ export const sessionSlice = createSlice({ (toolCallDelta) => addToolCallDeltaToState(toolCallDelta, undefined), ); + // Set toolCalls on the message for compatibility + (historyItem.message as any).toolCalls = historyItem.toolCallStates.map( + (state) => state.toolCall, + ); } state.history.push(historyItem); - } else { - // Add to the existing message + lastItem = state.history[state.history.length - 1]; + lastMessage = lastItem.message; + } - // Handle tool calls being added to existing assistant message - if ( - message.role === "assistant" && - (message as any).toolCalls?.length && - !lastItem.toolCallStates + // Add to the existing message + if (messageContent) { + if (messageContent.includes("")) { + lastItem.reasoning = { + startAt: Date.now(), + active: true, + text: messageContent.replace("", "").trim(), + }; + } else if ( + lastItem.reasoning?.active && + messageContent.includes("") ) { - lastItem.toolCallStates = (message as any).toolCalls.map( - (toolCallDelta: any) => - addToolCallDeltaToState(toolCallDelta, undefined), - ); - (lastMessage as any).toolCalls = lastItem.toolCallStates?.map( - (state) => state.toolCall, - ); - } - - // CRITICAL: Always ensure message.toolCalls is synchronized with toolCallStates - if (lastItem.toolCallStates && lastItem.toolCallStates.length > 0) { - (lastMessage as any).toolCalls = lastItem.toolCallStates.map( - (state) => state.toolCall, - ); - } - - if (message.content) { - const messageContent = renderChatMessage(message); - if (messageContent.includes("")) { - lastItem.reasoning = { - startAt: Date.now(), - active: true, - text: messageContent.replace("", "").trim(), - }; - } else if ( - lastItem.reasoning?.active && - messageContent.includes("") + const [reasoningEnd, answerStart] = + messageContent.split(""); + lastItem.reasoning.text += reasoningEnd.trimEnd(); + lastItem.reasoning.active = false; + lastItem.reasoning.endAt = Date.now(); + lastMessage.content += answerStart.trimStart(); + } else if (lastItem.reasoning?.active) { + if ( + lastItem.reasoning.text.length > 0 || + messageContent.trim().length > 0 ) { - const [reasoningEnd, answerStart] = - messageContent.split(""); - lastItem.reasoning.text += reasoningEnd.trimEnd(); - lastItem.reasoning.active = false; - lastItem.reasoning.endAt = Date.now(); - lastMessage.content += answerStart.trimStart(); - } else if (lastItem.reasoning?.active) { lastItem.reasoning.text += messageContent; - } else { - // Note this only works because new message above - // was already rendered from parts to string + } + } else { + // Note this only works because new message above + // was already rendered from parts to string + if ( + lastMessage.content.length > 0 || + messageContent.trim().length > 0 + ) { lastMessage.content += messageContent; } - } else if (message.role === "thinking" && message.signature) { - if (lastMessage.role === "thinking") { - lastMessage.signature = message.signature; - } - } else if ( - message.role === "assistant" && - message.toolCalls?.length && - lastMessage.role === "assistant" - ) { - // Handle multiple tool calls in streaming updates - ID-based approach - const existingToolCallStates = lastItem.toolCallStates || []; - const updatedToolCallStates: ToolCallState[] = [ - ...existingToolCallStates, - ]; - - // Process each incoming tool call delta by ID - for (const toolCallDelta of message.toolCalls) { - // Find existing state by toolCallId - const existingStateIndex = updatedToolCallStates.findIndex( - (state) => state.toolCallId === toolCallDelta.id, - ); - - const existingState = - existingStateIndex >= 0 - ? updatedToolCallStates[existingStateIndex] - : undefined; - - const updatedState = addToolCallDeltaToState( - toolCallDelta, - existingState, - ); - - if (existingStateIndex >= 0) { - // Update existing state - updatedToolCallStates[existingStateIndex] = updatedState; - } else { - // Add new state - updatedToolCallStates.push(updatedState); - } - } - - lastItem.toolCallStates = updatedToolCallStates; - (lastMessage as any).toolCalls = updatedToolCallStates.map( - (state) => state.toolCall, - ); } + } else if (message.role === "thinking" && message.signature) { + if (lastMessage.role === "thinking") { + lastMessage.signature = message.signature; + } + } else if ( + message.role === "assistant" && + message.toolCalls?.length && + lastMessage.role === "assistant" + ) { + // Handle multiple tool calls in streaming updates - ID-based approach + const existingToolCallStates = lastItem.toolCallStates || []; + const updatedToolCallStates: ToolCallState[] = [ + ...existingToolCallStates, + ]; + + // Process each incoming tool call delta by ID + for (const toolCallDelta of message.toolCalls) { + // Find existing state by toolCallId + const existingStateIndex = updatedToolCallStates.findIndex( + (state) => state.toolCallId === toolCallDelta.id, + ); + + const existingState = + existingStateIndex >= 0 + ? updatedToolCallStates[existingStateIndex] + : undefined; + + const updatedState = addToolCallDeltaToState( + toolCallDelta, + existingState, + ); + + if (existingStateIndex >= 0) { + // Update existing state + updatedToolCallStates[existingStateIndex] = updatedState; + } else { + // Add new state + updatedToolCallStates.push(updatedState); + } + } + + lastItem.toolCallStates = updatedToolCallStates; + (lastMessage as any).toolCalls = updatedToolCallStates.map( + (state) => state.toolCall, + ); } } } diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 65350d7c8..f261ff892 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -83,12 +83,6 @@ export const uiSlice = createSlice({ ) => { state.dialogMessage = action.payload; }, - setDialogEntryOn: ( - state, - action: PayloadAction, - ) => { - state.dialogEntryOn = action.payload; - }, setShowDialog: (state, action: PayloadAction) => { state.showDialog = action.payload; }, @@ -98,9 +92,6 @@ export const uiSlice = createSlice({ ) => { state.isExploreDialogOpen = action.payload; }, - setHasDismissedExploreDialog: (state, action: PayloadAction) => { - state.hasDismissedExploreDialog = action.payload; - }, // Tools addTool: (state, action: PayloadAction) => { state.toolSettings[action.payload.function.name] = @@ -173,10 +164,8 @@ export const uiSlice = createSlice({ export const { setOnboardingCard, setDialogMessage, - setDialogEntryOn, setShowDialog, setIsExploreDialogOpen, - setHasDismissedExploreDialog, toggleToolSetting, setToolPolicy, clearToolPolicy, diff --git a/gui/src/redux/thunks/callToolById.ts b/gui/src/redux/thunks/callToolById.ts index a5bc4e7bd..6776c654e 100644 --- a/gui/src/redux/thunks/callToolById.ts +++ b/gui/src/redux/thunks/callToolById.ts @@ -7,6 +7,7 @@ import { selectSelectedChatModel } from "../slices/configSlice"; import { acceptToolCall, errorToolCall, + setInactive, setToolCallCalling, updateToolCallOutput, } from "../slices/sessionSlice"; @@ -30,7 +31,6 @@ export const callToolById = createAsyncThunk< return; } - const selectedChatModel = selectSelectedChatModel(state); if (!selectedChatModel) { @@ -146,5 +146,7 @@ export const callToolById = createAsyncThunk< }), ); unwrapResult(wrapped); + } else { + dispatch(setInactive()); } }); diff --git a/gui/src/redux/thunks/edit.ts b/gui/src/redux/thunks/edit.ts index 806b88fa7..700d49d55 100644 --- a/gui/src/redux/thunks/edit.ts +++ b/gui/src/redux/thunks/edit.ts @@ -133,6 +133,14 @@ export const enterEdit = createAsyncThunk< return; } + if (!state.editModeState.codeToEdit[0]) { + extra.ideMessenger.post("showToast", [ + "info", + "Please open a file to use Edit mode", + ]); + return; + } + dispatch(setMainEditorContentTrigger({})); dispatch(setPreviousModeEditorContent(editorContent)); @@ -148,9 +156,5 @@ export const enterEdit = createAsyncThunk< ); dispatch(setIsInEdit(true)); - - if (!state.editModeState.codeToEdit[0]) { - extra.ideMessenger.post("edit/addCurrentSelection", undefined); - } }, ); diff --git a/gui/src/redux/thunks/moveTerminalProcessToBackground.ts b/gui/src/redux/thunks/moveTerminalProcessToBackground.ts index d854046c2..07c43bf53 100644 --- a/gui/src/redux/thunks/moveTerminalProcessToBackground.ts +++ b/gui/src/redux/thunks/moveTerminalProcessToBackground.ts @@ -11,9 +11,10 @@ import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; /** * This thunk is used to move a terminal command to the background - * when the user clicks the "Continue" button in the UI + * when the user clicks the "Move to background" link in the UI * - * It marks the command as visually complete without stopping + * It preserves all existing terminal output, marks the command as + * visually complete, and stops listening to further output from * the already running process */ export const moveTerminalProcessToBackground = createAsyncThunk< @@ -32,6 +33,12 @@ export const moveTerminalProcessToBackground = createAsyncThunk< return; } + // Find existing terminal output to preserve it + const existingOutput = toolCall.output?.find( + (item) => item.name === "Terminal", + ); + const existingContent = existingOutput?.content || ""; + const status = "Command moved to background. Further output will be ignored."; @@ -39,7 +46,7 @@ export const moveTerminalProcessToBackground = createAsyncThunk< { name: "Terminal", description: "Terminal command output", - content: "\n" + status, + content: existingContent + (existingContent ? "\n\n" : "") + status, status: status, }, ]; diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts index 244b51fc6..a6d630e0a 100644 --- a/gui/src/util/localStorage.ts +++ b/gui/src/util/localStorage.ts @@ -6,7 +6,6 @@ type LocalStorageTypes = { hasDismissedExploreDialog: boolean; onboardingStatus?: OnboardingStatus; hasDismissedOnboardingCard: boolean; - mainTextEntryCounter: number; ide: "vscode" | "jetbrains"; vsCodeUriScheme: string; ftc: number; diff --git a/gui/src/util/toolCallState.test.ts b/gui/src/util/toolCallState.test.ts index 3207b606a..486f26c66 100644 --- a/gui/src/util/toolCallState.test.ts +++ b/gui/src/util/toolCallState.test.ts @@ -479,4 +479,104 @@ describe("addToolCallDeltaToState", () => { ); expect(currentState.parsedArgs).toEqual({ location: "Paris, France" }); }); + + it("should handle arguments streamed in full progressive chunks", () => { + // Test case where model streams args progressively but includes full prefix each time + // e.g. '{"query":"te' -> '{"query":"tes' -> '{"query":"test"}' + const currentState: ToolCallState = { + status: "generating", + toolCall: { + id: "call123", + type: "function", + function: { + name: "searchFiles", + arguments: '{"query":"te', + }, + }, + toolCallId: "call123", + parsedArgs: { query: "te" }, + }; + + const delta: ToolCallDelta = { + function: { + arguments: '{"query":"tes', + }, + }; + + const result = addToolCallDeltaToState(delta, currentState); + expect(result.toolCall.function.arguments).toBe('{"query":"tes'); + expect(result.parsedArgs).toEqual({ query: "tes" }); + + // Continue the streaming + const nextDelta: ToolCallDelta = { + function: { + arguments: '{"query":"test"}', + }, + }; + + const finalResult = addToolCallDeltaToState(nextDelta, result); + expect(finalResult.toolCall.function.arguments).toBe('{"query":"test"}'); + expect(finalResult.parsedArgs).toEqual({ query: "test" }); + }); + + it("should handle when args delta is a superset of current args", () => { + // Test case where model sends a subset of the current arguments + // This can happen in certain LLM implementations + const currentState: ToolCallState = { + status: "generating", + toolCall: { + id: "call123", + type: "function", + function: { + name: "searchFiles", + arguments: '{"query":"test"', + }, + }, + toolCallId: "call123", + parsedArgs: { query: "test" }, + }; + + const delta: ToolCallDelta = { + function: { + arguments: '{"query":"test","limit":10}', + }, + }; + + // The subset should be ignored, keeping the current state + const result = addToolCallDeltaToState(delta, currentState); + expect(result.toolCall.function.arguments).toBe( + '{"query":"test","limit":10}', + ); + expect(result.parsedArgs).toEqual({ query: "test", limit: 10 }); + }); + + it("should handle when args are complete JSON and new deltas arrive", () => { + // When args are already a valid JSON object, new deltas should not modify it + const currentState: ToolCallState = { + status: "generating", + toolCall: { + id: "call123", + type: "function", + function: { + name: "searchFiles", + arguments: '{"query":"test","limit":10}', + }, + }, + toolCallId: "call123", + parsedArgs: { query: "test", limit: 10 }, + }; + + const delta: ToolCallDelta = { + function: { + arguments: ',"sort":"asc"}', + }, + }; + + // The complete JSON should not be modified + const result = addToolCallDeltaToState(delta, currentState); + expect(result.toolCall.function.arguments).toBe( + '{"query":"test","limit":10}', + ); + expect(result.parsedArgs).toEqual({ query: "test", limit: 10 }); + }); }); diff --git a/gui/src/util/toolCallState.ts b/gui/src/util/toolCallState.ts index eb0274aed..ad9405798 100644 --- a/gui/src/util/toolCallState.ts +++ b/gui/src/util/toolCallState.ts @@ -26,15 +26,24 @@ export function addToolCallDeltaToState( if (nameDelta.startsWith(currentName)) { // Case where model progresssively streams name but full name each time e.g. "readFi" -> "readFil" -> "readFile" mergedName = nameDelta; - } else if (currentName.startsWith(nameDelta)) { - // Case where model streams in full name each time e.g. readFile -> readFile -> readFile - // do nothing - } else { - // Case where model streams in name in parts e.g. "read" -> "File" + } else if (!currentName.startsWith(nameDelta)) { mergedName = currentName + nameDelta; } - const mergedArgs = currentArgs + argsDelta; + // Similar logic for args, with an extra JSON check + let mergedArgs = currentArgs; + try { + // If args is JSON parseable, it is complete, don't add to it + JSON.parse(currentArgs); + } catch (e) { + if (argsDelta.startsWith(currentArgs)) { + // Case where model progresssively streams args but full args each time e.g. "{"file": "file1"}" -> "{"file": "file1", "line": 1}" + mergedArgs = argsDelta; + } else if (!currentArgs.startsWith(argsDelta)) { + // Case where model streams in args in parts e.g. "{"file": "file1"" -> ", "line": 1}" + mergedArgs = currentArgs + argsDelta; + } + } const [_, parsedArgs] = incrementalParseJson(mergedArgs || "{}"); diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 1424b2aea..7802be705 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -24,7 +24,7 @@ import { packageIdentifierToShorthandSlug, useProxyForUnrenderedSecrets, } from "./clientRender.js"; -import { getBlockType } from "./getBlockType.js"; +import { BlockType, getBlockType } from "./getBlockType.js"; export function parseConfigYaml(configYaml: string): ConfigYaml { try { @@ -322,12 +322,15 @@ export async function unrollBlocks( "name" | "version" | "rules" | "schema" | "metadata" >)[] = ["models", "context", "data", "mcpServers", "prompts", "docs"]; - // For each section, replace "uses/with" blocks with the real thing - for (const section of sections) { - if (assistant[section]) { - const sectionBlocks: any[] = []; + // Process all sections in parallel + const sectionPromises = sections.map(async (section) => { + if (!assistant[section]) { + return { section, blocks: null }; + } - for (const unrolledBlock of assistant[section]) { + // Process all blocks in this section in parallel + const blockPromises = assistant[section].map( + async (unrolledBlock, index) => { // "uses/with" block if ("uses" in unrolledBlock) { try { @@ -338,10 +341,13 @@ export async function unrollBlocks( ); const block = blockConfigYaml[section]?.[0]; if (block) { - sectionBlocks.push( - mergeOverrides(block, unrolledBlock.override ?? {}), - ); + return { + index, + block: mergeOverrides(block, unrolledBlock.override ?? {}), + error: null, + }; } + return { index, block: null, error: null }; } catch (err) { let msg = ""; if ( @@ -353,99 +359,190 @@ export async function unrollBlocks( msg = `${(err as Error).message}.\n> ${JSON.stringify(unrolledBlock.uses)}`; } - errors.push({ - fatal: false, - message: msg, - }); - console.error( `Failed to unroll block ${JSON.stringify(unrolledBlock.uses)}: ${(err as Error).message}`, ); - sectionBlocks.push(null); + + return { + index, + block: null, + error: { + fatal: false, + message: msg, + }, + }; } } else { // Normal block - sectionBlocks.push(unrolledBlock); + return { index, block: unrolledBlock, error: null }; } - } + }, + ); - unrolledAssistant[section] = sectionBlocks; + const blockResults = await Promise.all(blockPromises); + + // Collect errors and maintain order + const sectionBlocks: any[] = []; + const sectionErrors: ConfigValidationError[] = []; + + for (const result of blockResults) { + if (result.error) { + sectionErrors.push(result.error); + } + sectionBlocks[result.index] = result.block; + } + + return { section, blocks: sectionBlocks, errors: sectionErrors }; + }); + + // Process rules in parallel + const rulesPromise = assistant.rules + ? (async () => { + const rulePromises = assistant.rules!.map(async (rule, index) => { + if (typeof rule === "string" || !("uses" in rule)) { + return { index, rule, error: null }; + } else if ("uses" in rule) { + try { + const blockConfigYaml = await resolveBlock( + decodePackageIdentifier(rule.uses), + rule.with, + registry, + ); + const block = blockConfigYaml.rules?.[0]; + return { index, rule: block || null, error: null }; + } catch (err) { + console.error( + `Failed to unroll block ${rule.uses}: ${(err as Error).message}`, + ); + + return { + index, + rule: null, + error: { + fatal: false, + message: `${(err as Error).message}:\n${rule.uses}`, + }, + }; + } + } + return { index, rule: null, error: null }; + }); + + const ruleResults = await Promise.all(rulePromises); + + const rules: (Rule | null)[] = []; + const ruleErrors: ConfigValidationError[] = []; + + for (const result of ruleResults) { + if (result.error) { + ruleErrors.push(result.error); + } + rules[result.index] = result.rule; + } + + return { rules, errors: ruleErrors }; + })() + : Promise.resolve({ rules: undefined, errors: [] }); + + // Process injected blocks in parallel + const injectedBlocksPromise = injectBlocks + ? (async () => { + const injectedBlockPromises = injectBlocks.map(async (injectBlock) => { + try { + const blockConfigYaml = await registry.getContent(injectBlock); + const parsedBlock = parseMarkdownRuleOrConfigYaml( + blockConfigYaml, + injectBlock, + ); + const blockType = getBlockType(parsedBlock); + const resolvedBlock = await resolveBlock( + injectBlock, + undefined, + registry, + ); + + return { + blockType, + resolvedBlock, + error: null, + }; + } catch (err) { + let msg = ""; + if (injectBlock.uriType === "file") { + msg = `${(err as Error).message}.\n> ${injectBlock.filePath}`; + } else { + msg = `${(err as Error).message}.\n> ${injectBlock.fullSlug}`; + } + + console.error( + `Failed to unroll block ${JSON.stringify(injectBlock)}: ${(err as Error).message}`, + ); + + return { + blockType: null, + resolvedBlock: null, + error: { + fatal: false, + message: msg, + }, + }; + } + }); + + const injectedResults = await Promise.all(injectedBlockPromises); + const injectedErrors: ConfigValidationError[] = []; + const injectedBlocks: { blockType: string; resolvedBlock: any }[] = []; + + for (const result of injectedResults) { + if (result.error) { + injectedErrors.push(result.error); + } else if (result.blockType && result.resolvedBlock) { + injectedBlocks.push({ + blockType: result.blockType, + resolvedBlock: result.resolvedBlock, + }); + } + } + + return { injectedBlocks, errors: injectedErrors }; + })() + : Promise.resolve({ injectedBlocks: [], errors: [] }); + + // Wait for all parallel operations to complete + const [sectionResults, rulesResult, injectedResult] = await Promise.all([ + Promise.all(sectionPromises), + rulesPromise, + injectedBlocksPromise, + ]); + + // Collect all errors + for (const sectionResult of sectionResults) { + if (sectionResult.errors) { + errors.push(...sectionResult.errors); + } + } + errors.push(...rulesResult.errors); + errors.push(...injectedResult.errors); + + // Assign section results + for (const sectionResult of sectionResults) { + if (sectionResult.blocks) { + unrolledAssistant[sectionResult.section] = sectionResult.blocks; } } - // Rules are a bit different because they can be strings, so handle separately - if (assistant.rules) { - const rules: (Rule | null)[] = []; - for (const rule of assistant.rules) { - if (typeof rule === "string" || !("uses" in rule)) { - rules.push(rule); - } else if ("uses" in rule) { - try { - const blockConfigYaml = await resolveBlock( - decodePackageIdentifier(rule.uses), - rule.with, - registry, - ); - const block = blockConfigYaml.rules?.[0]; - if (block) { - rules.push(block); - } - } catch (err) { - errors.push({ - fatal: false, - message: `${(err as Error).message}:\n${rule.uses}`, - }); - - console.error( - `Failed to unroll block ${rule.uses}: ${(err as Error).message}`, - ); - rules.push(null); - } - } - } - - unrolledAssistant.rules = rules; + // Assign rules result + if (rulesResult.rules) { + unrolledAssistant.rules = rulesResult.rules; } // Add injected blocks - for (const injectBlock of injectBlocks ?? []) { - try { - const blockConfigYaml = await registry.getContent(injectBlock); - const parsedBlock = parseMarkdownRuleOrConfigYaml( - blockConfigYaml, - injectBlock, - ); - const blockType = getBlockType(parsedBlock); - const resolvedBlock = await resolveBlock( - injectBlock, - undefined, - registry, - ); - - if (blockType) { - if (!unrolledAssistant[blockType]) { - unrolledAssistant[blockType] = []; - } - unrolledAssistant[blockType]?.push( - ...(resolvedBlock[blockType] as any), - ); - } - } catch (err) { - let msg = ""; - if (injectBlock.uriType === "file") { - msg = `${(err as Error).message}.\n> ${injectBlock.filePath}`; - } else { - msg = `${(err as Error).message}.\n> ${injectBlock.fullSlug}`; - } - errors.push({ - fatal: false, - message: msg, - }); - - console.error( - `Failed to unroll block ${JSON.stringify(injectBlock)}: ${(err as Error).message}`, - ); + for (const { blockType, resolvedBlock } of injectedResult.injectedBlocks) { + const key = blockType as BlockType; + if (!unrolledAssistant[key]) { + unrolledAssistant[key] = []; } + unrolledAssistant[key]?.push(...((resolvedBlock[blockType] ?? []) as any)); } const configResult: ConfigResult = { diff --git a/packages/config-yaml/src/markdown/createMarkdownRule.test.ts b/packages/config-yaml/src/markdown/createMarkdownRule.test.ts index 52fb9db33..982e823bf 100644 --- a/packages/config-yaml/src/markdown/createMarkdownRule.test.ts +++ b/packages/config-yaml/src/markdown/createMarkdownRule.test.ts @@ -9,7 +9,7 @@ import { markdownToRule } from "./markdownToRule.js"; // Mock package identifier for testing const mockPackageId: PackageIdentifier = { uriType: "file", - filePath: "/path/to/file", + filePath: "/path/to/folder", }; describe("sanitizeRuleName", () => { @@ -85,7 +85,9 @@ Just markdown content.`; expect(parsed.name).toBe(originalFrontmatter.name); expect(parsed.description).toBe(originalFrontmatter.description); - expect(parsed.globs).toEqual(originalFrontmatter.globs); + expect(parsed.globs).toEqual( + originalFrontmatter.globs.map((glob) => `/path/to/**/${glob}`), + ); expect(parsed.alwaysApply).toBe(originalFrontmatter.alwaysApply); expect(parsed.rule).toBe(originalMarkdown); }); @@ -102,7 +104,7 @@ describe("createRuleMarkdown", () => { const parsed = markdownToRule(result, mockPackageId); expect(parsed.description).toBe("Test description"); - expect(parsed.globs).toEqual(["*.ts", "*.js"]); + expect(parsed.globs).toEqual(["/path/to/**/*.ts", "/path/to/**/*.js"]); expect(parsed.alwaysApply).toBe(true); expect(parsed.rule).toBe("This is the rule content"); }); @@ -113,7 +115,7 @@ describe("createRuleMarkdown", () => { const parsed = markdownToRule(result, mockPackageId); expect(parsed.description).toBeUndefined(); - expect(parsed.globs).toBeUndefined(); + expect(parsed.globs).toBe("/path/to/**/*"); expect(parsed.alwaysApply).toBeUndefined(); expect(parsed.rule).toBe("Simple content"); }); @@ -124,7 +126,7 @@ describe("createRuleMarkdown", () => { }); const parsed = markdownToRule(result, mockPackageId); - expect(parsed.globs).toBe("*.py"); + expect(parsed.globs).toBe("/path/to/**/*.py"); }); it("should trim description and globs", () => { @@ -135,7 +137,7 @@ describe("createRuleMarkdown", () => { const parsed = markdownToRule(result, mockPackageId); expect(parsed.description).toBe("spaced description"); - expect(parsed.globs).toBe("*.ts"); + expect(parsed.globs).toBe("/path/to/**/*.ts"); }); it("should handle alwaysApply false explicitly", () => { diff --git a/packages/config-yaml/src/markdown/markdownToRule.test.ts b/packages/config-yaml/src/markdown/markdownToRule.test.ts index 1b930220a..0d96ab19e 100644 --- a/packages/config-yaml/src/markdown/markdownToRule.test.ts +++ b/packages/config-yaml/src/markdown/markdownToRule.test.ts @@ -20,7 +20,7 @@ This is a test rule.`; const result = markdownToRule(content, mockId); expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); - expect(result.globs).toBe("**/test/**/*.kt"); + expect(result.globs).toBe("/path/to/**/test/**/*.kt"); expect(result.name).toBe("Custom Name"); }); @@ -34,7 +34,7 @@ globs: "**/test/**/*.kt" This is a test rule.`; const result = markdownToRule(content, mockId); - expect(result.globs).toBe("**/test/**/*.kt"); + expect(result.globs).toBe("/path/to/**/test/**/*.kt"); expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); expect(result.name).toBe("to/file"); // Should use last two path segments }); @@ -45,7 +45,7 @@ This is a test rule.`; This is a test rule without frontmatter.`; const result = markdownToRule(content, mockId); - expect(result.globs).toBeUndefined(); + expect(result.globs).toBe("/path/to/**/*"); expect(result.rule).toBe(content); expect(result.name).toBe("to/file"); // Should use last two path segments }); @@ -59,13 +59,104 @@ This is a test rule without frontmatter.`; This is a test rule with empty frontmatter.`; const result = markdownToRule(content, mockId); - expect(result.globs).toBeUndefined(); + expect(result.globs).toBe("/path/to/**/*"); expect(result.rule).toBe( "# Test Rule\n\nThis is a test rule with empty frontmatter.", ); expect(result.name).toBe("to/file"); // Should use last two path segments }); + describe("glob patterns", () => { + // we want to ensure the following glob changes happen + // *.ts -> path/to/**/*.ts + // **/subdir/** -> path/to/**/**/subdir/** OR path/to/**/subdir/** + // myfile -> path/to/**/myfile (any depth including 0) + // mydir/ -> path/to/**/mydir/** + // **abc** -> path/to/**abc** + // *xyz* -> path/to/**/*xyz* + + it("should match glob pattern for file extensions", () => { + const content = `--- +globs: "*.ts" +name: glob pattern testing +--- + + # Test Rule + + This is a test rule.`; + + const result = markdownToRule(content, mockId); + expect(result.globs).toBe("/path/to/**/*.ts"); + }); + + it("should match glob pattern for dotfiles", () => { + const content = `--- +globs: ".gitignore" +name: glob pattern testing +--- + + # Test Rule + + This is a test rule.`; + + const result = markdownToRule(content, mockId); + expect(result.globs).toBe("/path/to/**/.gitignore"); + }); + + it("should also work in root as base directory", () => { + const content = `--- +globs: "src/**/Dockerfile" +name: glob pattern testing +--- + + # Test Rule + + This is a test rule.`; + + const result = markdownToRule(content, { + uriType: "file", + filePath: "/", + }); + expect(result.globs).toBe("/**/src/**/Dockerfile"); + }); + + it("should match for multiple globs", () => { + const content = `--- +globs: ["**/nested/**/deeper/**/*.rs", ".zshrc1", "**abc**", "*xyz*"] +name: glob pattern testing +--- + +# Test Rule + +This is a test rule.`; + + const result = markdownToRule(content, mockId); + expect(result.globs).toEqual([ + "/path/to/**/nested/**/deeper/**/*.rs", + "/path/to/**/.zshrc1", + "/path/to/**abc**", + "/path/to/**/*xyz*", + ]); + }); + + it("should not prepend when inside .continue", () => { + const content = `--- +globs: ".git" +name: glob pattern testing +--- + + # Test Rule + + This is a test rule.`; + + const result = markdownToRule(content, { + uriType: "file", + filePath: "/Documents/myproject/.continue/rules/rule1.md", + }); + expect(result.globs).toBe(".git"); + }); + }); + it("should handle frontmatter with whitespace", () => { const content = `--- globs: "**/test/**/*.kt" @@ -76,7 +167,7 @@ globs: "**/test/**/*.kt" This is a test rule.`; const result = markdownToRule(content, mockId); - expect(result.globs).toBe("**/test/**/*.kt"); + expect(result.globs).toBe("/path/to/**/test/**/*.kt"); expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); expect(result.name).toBe("to/file"); // Should use last two path segments }); @@ -92,7 +183,7 @@ globs: "**/test/**/*.kt"\r This is a test rule.`; const result = markdownToRule(content, mockId); - expect(result.globs).toBe("**/test/**/*.kt"); + expect(result.globs).toBe("/path/to/**/test/**/*.kt"); // The result should be normalized to \n expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); expect(result.name).toBe("to/file"); // Should use last two path segments @@ -110,7 +201,7 @@ This is a test rule.`; // Should treat as only markdown when frontmatter is malformed const result = markdownToRule(content, mockId); - expect(result.globs).toBeUndefined(); + expect(result.globs).toBe("/path/to/**/*"); expect(result.rule).toBe(content); expect(result.name).toBe("to/file"); // Should use last two path segments }); diff --git a/packages/config-yaml/src/markdown/markdownToRule.ts b/packages/config-yaml/src/markdown/markdownToRule.ts index 3add16b6c..231b2ab4a 100644 --- a/packages/config-yaml/src/markdown/markdownToRule.ts +++ b/packages/config-yaml/src/markdown/markdownToRule.ts @@ -1,3 +1,4 @@ +import path from "path"; import * as YAML from "yaml"; import { PackageIdentifier, @@ -69,6 +70,35 @@ export function getRuleName( return displayName; } +function getGlobPattern( + globs: RuleFrontmatter["globs"], + id: PackageIdentifier, +) { + if (id.uriType !== "file") { + return globs; + } + let dir = path.dirname(id.filePath); + if (dir.includes(".continue")) { + return globs; + } + if (!dir.endsWith("/")) { + dir = dir.concat("/"); + } + const prependDirAndApplyGlobstar = (glob: string) => { + if (glob.startsWith("**")) { + return dir.concat(glob); + } + return dir.concat("**/", glob); + }; + if (!globs) { + return dir.concat("**/*"); + } + if (Array.isArray(globs)) { + return globs.map(prependDirAndApplyGlobstar); + } + return prependDirAndApplyGlobstar(globs); +} + export function markdownToRule( rule: string, id: PackageIdentifier, @@ -78,7 +108,7 @@ export function markdownToRule( return { name: getRuleName(frontmatter, id), rule: markdown, - globs: frontmatter.globs, + globs: getGlobPattern(frontmatter.globs, id), regex: frontmatter.regex, description: frontmatter.description, alwaysApply: frontmatter.alwaysApply, diff --git a/packages/config-yaml/src/schemas/data/autocomplete/index.ts b/packages/config-yaml/src/schemas/data/autocomplete/index.ts index 8ae073e2e..458473c3b 100644 --- a/packages/config-yaml/src/schemas/data/autocomplete/index.ts +++ b/packages/config-yaml/src/schemas/data/autocomplete/index.ts @@ -34,7 +34,7 @@ export const autocompleteEventAllSchema = baseDevDataAllSchema.extend({ gitRepo: z.string().optional(), completionId: z.string(), uniqueId: z.string(), - timestamp: z.number(), + timestamp: z.string(), // DEPRECATED - no more nested objects after v0.1.0, all flat values completionOptions: completionOptionsSchema.optional(), diff --git a/packages/config-yaml/src/schemas/data/chatInteraction/index.ts b/packages/config-yaml/src/schemas/data/chatInteraction/index.ts index 91cbbb1e7..f13b630af 100644 --- a/packages/config-yaml/src/schemas/data/chatInteraction/index.ts +++ b/packages/config-yaml/src/schemas/data/chatInteraction/index.ts @@ -8,4 +8,12 @@ export const chatInteractionEventAllSchema = baseDevDataAllSchema.extend({ completion: z.string(), sessionId: z.string(), tools: z.array(z.string()).optional(), + rules: z + .array( + z.object({ + id: z.string(), + rule: z.string(), + }), + ) + .optional(), }); diff --git a/packages/config-yaml/src/schemas/data/chatInteraction/v0.2.0.ts b/packages/config-yaml/src/schemas/data/chatInteraction/v0.2.0.ts index aec50a223..ce0983a75 100644 --- a/packages/config-yaml/src/schemas/data/chatInteraction/v0.2.0.ts +++ b/packages/config-yaml/src/schemas/data/chatInteraction/v0.2.0.ts @@ -17,6 +17,7 @@ export const chatInteractionEventSchema_0_2_0 = modelProvider: true, sessionId: true, tools: true, + rules: true, }); export const chatInteractionEventSchema_0_2_0_noCode = diff --git a/packages/config-yaml/src/schemas/data/editOutcome/v0.2.0.ts b/packages/config-yaml/src/schemas/data/editOutcome/v0.2.0.ts index 88d867fbd..1fdbfb967 100644 --- a/packages/config-yaml/src/schemas/data/editOutcome/v0.2.0.ts +++ b/packages/config-yaml/src/schemas/data/editOutcome/v0.2.0.ts @@ -15,10 +15,17 @@ export const editOutcomeEventSchema_0_2_0 = editOutcomeEventAllSchema.pick({ modelTitle: true, modelProvider: true, accepted: true, + previousCode: true, + newCode: true, + previousCodeLines: true, + newCodeLines: true, + lineChange: true, }); export const editOutcomeEventSchema_0_2_0_noCode = editOutcomeEventSchema_0_2_0.omit({ prompt: true, completion: true, + previousCode: true, + newCode: true, }); diff --git a/packages/config-yaml/src/schemas/review.rule.md b/packages/config-yaml/src/schemas/review.rule.md new file mode 100644 index 000000000..6742bad44 --- /dev/null +++ b/packages/config-yaml/src/schemas/review.rule.md @@ -0,0 +1,3 @@ +No new additions to the ConfigYaml schema should be made for features that are experimental. This is because anything added to config.yaml can't easily be taken away without causing backward-compatibility issues for users that chose to use the setting. + +You can tell whether a feature is experimental based off of whether anything was added to the "Experimental Settings" section of `UserSettingsForm.tsx`. diff --git a/packages/hub/package-lock.json b/packages/hub/package-lock.json index bfc2041d5..ec4bd43df 100644 --- a/packages/hub/package-lock.json +++ b/packages/hub/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/hub", - "version": "0.0.1", + "version": "0.0.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/hub", - "version": "0.0.1", + "version": "0.0.4", "license": "Apache-2.0", "dependencies": { "@continuedev/config-yaml": "^1.0.70" diff --git a/packages/openai-adapters/src/apis/Bedrock.ts b/packages/openai-adapters/src/apis/Bedrock.ts index 2a580456a..ce9fcb933 100644 --- a/packages/openai-adapters/src/apis/Bedrock.ts +++ b/packages/openai-adapters/src/apis/Bedrock.ts @@ -1,6 +1,7 @@ import { BedrockRuntimeClient, ContentBlock, + ContentBlockStart, ConversationRole, ConverseStreamCommand, ConverseStreamCommandInput, @@ -57,8 +58,6 @@ interface ToolUseState { } export class BedrockApi implements BaseLlmApi { - private _currentToolResponse: Partial | null = null; - constructor(protected config: BedrockConfig) { if (config.env?.accessKeyId || config?.env?.secretAccessKey) { if (!config.env?.accessKeyId) { @@ -455,8 +454,6 @@ export class BedrockApi implements BaseLlmApi { throw new Error("No stream received from Bedrock API"); } - this._currentToolResponse = null; - for await (const chunk of response.stream) { if (chunk.contentBlockDelta?.delta) { const delta: any = chunk.contentBlockDelta.delta; @@ -479,56 +476,50 @@ export class BedrockApi implements BaseLlmApi { } // Handle tool use - if (delta.toolUse?.input && this._currentToolResponse) { - if (this._currentToolResponse.input === undefined) { - this._currentToolResponse.input = ""; - } - this._currentToolResponse.input += delta.toolUse.input; - continue; - } - } - - if (chunk.contentBlockStart?.start) { - const start: any = chunk.contentBlockStart.start; - - // Handle tool start - const toolUse = start.toolUse; - if (toolUse?.toolUseId && toolUse?.name) { - this._currentToolResponse = { - toolUseId: toolUse.toolUseId, - name: toolUse.name, - input: "", - }; - } - continue; - } - - if (chunk.contentBlockStop) { - // End of a content block - if (this._currentToolResponse) { + if (delta.toolUse) { yield chatChunkFromDelta({ model: body.model, delta: { tool_calls: [ { index: 0, - id: this._currentToolResponse.toolUseId, + id: delta.toolUse.toolUseId, type: "function", function: { - name: this._currentToolResponse.name, - arguments: this._currentToolResponse.input, + name: delta.toolUse.name, + arguments: delta.toolUse.input, + }, + }, + ], + }, + }); + } + } + + if (chunk.contentBlockStart?.start) { + const start: ContentBlockStart = chunk.contentBlockStart.start; + + if (start.toolUse) { + yield chatChunkFromDelta({ + model: body.model, + delta: { + tool_calls: [ + { + index: 0, + id: start.toolUse.toolUseId, + type: "function", + function: { + name: start.toolUse.name, + arguments: undefined, }, }, ], }, }); - this._currentToolResponse = null; } - continue; } } } catch (error) { - this._currentToolResponse = null; if (error instanceof Error) { if ("code" in error) { throw new Error( diff --git a/scripts/install-dependencies.ps1 b/scripts/install-dependencies.ps1 index e783f94b4..1e258f9fd 100644 --- a/scripts/install-dependencies.ps1 +++ b/scripts/install-dependencies.ps1 @@ -76,8 +76,20 @@ if (($null -eq $node)) { Write-Host "`nInstalling root-level dependencies..." -ForegroundColor White npm install -Write-Host "`nBuilding openai-adapters..." -ForegroundColor White -Push-Location packages/openai-adapters +Write-Host "`nBuilding config-types..." -ForegroundColor White +Push-Location packages/config-types +npm install +npm run build +Pop-Location + +Write-Host "`nBuilding fetch..." -ForegroundColor White +Push-Location packages/fetch +npm install +npm run build +Pop-Location + +Write-Host "`nBuilding llm-info..." -ForegroundColor White +Push-Location packages/llm-info npm install npm run build Pop-Location @@ -88,6 +100,18 @@ npm install npm run build Pop-Location +Write-Host "`nBuilding openai-adapters..." -ForegroundColor White +Push-Location packages/openai-adapters +npm install +npm run build +Pop-Location + +Write-Host "`nBuilding hub..." -ForegroundColor White +Push-Location packages/hub +npm install +npm run build +Pop-Location + Write-Host "`nInstalling Core extension dependencies..." -ForegroundColor White Push-Location core npm install @@ -127,4 +151,4 @@ Push-Location docs npm install -Pop-Location +Pop-Location \ No newline at end of file diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh index 503aabbcd..3f3e54f7b 100755 --- a/scripts/install-dependencies.sh +++ b/scripts/install-dependencies.sh @@ -30,8 +30,20 @@ fi echo "Installing root-level dependencies..." npm install -echo "Building openai-adapters..." -pushd packages/openai-adapters +echo "Building config-types..." +pushd packages/config-types +npm install +npm run build +popd + +echo "Building fetch..." +pushd packages/fetch +npm install +npm run build +popd + +echo "Building llm-info..." +pushd packages/llm-info npm install npm run build popd @@ -42,6 +54,18 @@ npm install npm run build popd +echo "Building openai-adapters..." +pushd packages/openai-adapters +npm install +npm run build +popd + +echo "Building hub..." +pushd packages/hub +npm install +npm run build +popd + echo "Installing Core extension dependencies..." pushd core ## This flag is set because we pull down Chromium at runtime @@ -76,4 +100,4 @@ popd echo "Installing docs dependencies..." pushd docs npm install -popd +popd \ No newline at end of file diff --git a/scripts/uninstall.js b/scripts/uninstall.js index 8754e5188..15c1edf73 100644 --- a/scripts/uninstall.js +++ b/scripts/uninstall.js @@ -18,6 +18,21 @@ const directories = [ "./binary/bin", "./binary/dist", "./binary/out", + // packages + "./packages/config-types/node_modules", + "./packages/config-types/dist", + "./packages/fetch/node_modules", + "./packages/fetch/dist", + "./packages/llm-info/node_modules", + "./packages/llm-info/dist", + "./packages/config-yaml/node_modules", + "./packages/config-yaml/dist", + "./packages/openai-adapters/node_modules", + "./packages/openai-adapters/dist", + "./packages/hub/node_modules", + "./packages/hub/dist", + // docs + "./docs/node_modules", // root "./node_modules", ];