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/.vscode/launch.json b/.vscode/launch.json index 346714e94..53632f8d2 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -19,7 +19,6 @@ "pauseForSourceMap": false, "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"], "preLaunchTask": "vscode-extension:build", - "postDebugTask": "Terminate All Tasks", "env": { // "CONTROL_PLANE_ENV": "local", "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" 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/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/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/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/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/docs/customize/model-providers/top-level/vertexai.mdx b/docs/customize/model-providers/top-level/vertexai.mdx index e16df9615..d1628d798 100644 --- a/docs/customize/model-providers/top-level/vertexai.mdx +++ b/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/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/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/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/vscode/package-lock.json b/extensions/vscode/package-lock.json index d62caf298..6936cc88b 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.58", + "version": "1.1.59", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.58", + "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 cb33e7a31..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.59", + "version": "1.1.60", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" 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 8a7346691..a92523acc 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -184,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", 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/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/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 09a3884b7..cab6b3adc 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"; @@ -37,18 +36,12 @@ 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"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { cancelStream } from "../../redux/thunks/cancelStream"; -import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { ToolCallDiv } from "./ToolCallDiv"; @@ -221,19 +214,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/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/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 37910c105..211f211c8 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,6 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { LLMFullCompletionOptions, ModelDescription, Tool } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; +import { getRuleId } from "core/llm/rules/getSystemMessageWithRules"; import { ToCoreProtocol } from "core/protocol"; import { BuiltInToolNames } from "core/tools/builtIn"; import { selectActiveTools } from "../selectors/selectActiveTools"; @@ -171,6 +172,10 @@ export const streamNormalInput = createAsyncThunk< ...(!!activeTools.length && { tools: activeTools.map((tool) => tool.function.name), }), + rules: appliedRules.map((rule) => ({ + id: getRuleId(rule), + rule: rule.rule, + })), }, }); // else if (state.session.mode === "edit") { 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 e42ac6430..dab9b87b4 100644 --- a/gui/src/util/toolCallState.ts +++ b/gui/src/util/toolCallState.ts @@ -34,15 +34,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/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/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", ];