Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into current-file-context
Changeset495fcf80a69b7a27fea3178b62a2369b37ed7b1d93c1e19d1846ae0db304d76c
Authoruinstinct <61635505+uinstinct@users.noreply.github.com> · 2025-07-11 08:44 +05:30
Committeruinstinct <61635505+uinstinct@users.noreply.github.com> · 2025-07-11 08:44 +05:30
Parents0144befdba85, f2d7bde872a5

Browse the files at this changeset

68 files changed

added .continue/rules/dev-data-guide.md +200 −0
@@ -0,0 +1,200 @@
1+---
2+alwaysApply: false
3+---
4+
5+# Continue Development Data (Dev Data) Guide
6+
7+## Overview
8+
9+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.
10+
11+## Core Architecture
12+
13+### Primary Implementation Files
14+
15+- **`/core/data/log.ts`**: Main `DataLogger` class - singleton for event logging and remote transmission
16+- **`/packages/config-yaml/src/schemas/data/`**: Schema definitions for all event types
17+
18+### Storage Locations
19+
20+- **Default storage**: `~/.continue/dev_data/`
21+- **Event files**: `~/.continue/dev_data/{version}/{eventName}.jsonl`
22+
23+## Event Types and Schemas
24+
25+### Core Event Types
26+
27+1. **`tokensGenerated`**: LLM token usage tracking
28+2. **`autocomplete`**: Code completion interactions
29+3. **`chatInteraction`**: Chat-based development assistance
30+4. **`editInteraction`**: Code editing sessions
31+5. **`editOutcome`**: Results of edit operations
32+6. **`nextEditOutcome`**: Next Edit feature outcomes
33+7. **`chatFeedback`**: User feedback on AI responses
34+8. **`toolUsage`**: Tool interaction statistics
35+9. **`quickEdit`**: Quick edit functionality usage
36+
37+### Schema Versioning
38+
39+- **Version 0.1.0**: Initial schema implementation
40+- **Version 0.2.0**: Current schema with expanded fields and metadata
41+- **Schema files**: Located in `/packages/config-yaml/src/schemas/data/`
42+
43+### Base Schema Structure
44+
45+All events inherit from a base schema (`/packages/config-yaml/src/schemas/data/base.ts`):
46+
47+```typescript
48+{
49+ eventName: string,
50+ schema: string,
51+ timestamp: string,
52+ userId: string,
53+ userAgent: string,
54+ selectedProfileId: string
55+}
56+```
57+
58+## Key Integration Points
59+
60+### Autocomplete System
61+
62+- **File**: `/core/autocomplete/util/AutocompleteLoggingService.ts`
63+- **Purpose**: Tracks code completion acceptance/rejection, timing, and cache hits
64+- **Integration**: Called from autocomplete engine when completions are shown/accepted
65+
66+### Chat Interface
67+
68+- **Integration**: Chat interactions logged through `DataLogger.logDevData()`
69+- **Data**: Includes prompts, responses, context, and user feedback
70+- **Privacy**: Can be configured to exclude code content
71+
72+### Edit Features
73+
74+- **Files**: `/extensions/vscode/src/extension/EditOutcomeTracker.ts`, `/core/nextEdit/NextEditLoggingService.ts`
75+- **Purpose**: Track edit suggestions, acceptance rates, and outcomes
76+- **Integration**: Embedded in edit workflow to capture user decisions
77+
78+### LLM Token Tracking
79+
80+- **File**: `/core/llm/index.ts`
81+- **Purpose**: Track token usage across all LLM providers
82+- **Storage**: SQLite database for efficient querying and reporting
83+
84+## Configuration and Customization
85+
86+### Configuration Structure
87+
88+Dev data is configured through `data` blocks in your Continue config:
89+
90+```yaml
91+data:
92+ - name: "Local Development Data"
93+ destination: "file:///Users/developer/.continue/dev_data"
94+ schema: "0.2.0"
95+ level: "all"
96+ events: ["autocomplete", "chatInteraction", "editOutcome"]
97+
98+ - name: "Team Analytics"
99+ destination: "https://analytics.yourcompany.com/api/events"
100+ schema: "0.2.0"
101+ level: "noCode"
102+ apiKey: "your-api-key-here"
103+ events: ["tokensGenerated", "toolUsage"]
104+```
105+
106+### Configuration Options
107+
108+- **`destination`**: Where to send data (`file://` for local, `http://`/`https://` for remote)
109+- **`schema`**: Schema version to use (`"0.1.0"` or `"0.2.0"`)
110+- **`level`**: Data detail level (`"all"` includes code, `"noCode"` excludes code content)
111+- **`events`**: Array of event types to collect
112+- **`apiKey`**: Authentication for remote endpoints
113+
114+### Privacy Controls
115+
116+- **`"all"` level**: Includes code content (prefixes, suffixes, completions)
117+- **`"noCode"` level**: Excludes code content, only metadata and metrics
118+- **Local-first**: Data is always stored locally, remote transmission is optional
119+
120+## Making Changes to Dev Data
121+
122+### Adding New Event Types
123+
124+1. **Create schema**: Add new event schema in `/packages/config-yaml/src/schemas/data/`
125+2. **Update index**: Add to schema aggregator in `/packages/config-yaml/src/schemas/data/index.ts`
126+3. **Implement logging**: Add logging calls in relevant service files
127+4. **Update version**: Consider schema version bump if breaking changes
128+
129+### Modifying Existing Events
130+
131+1. **Schema changes**: Update schema files in `/packages/config-yaml/src/schemas/data/`
132+2. **Backward compatibility**: Ensure changes don't break existing data consumers
133+3. **Version management**: Increment schema version for breaking changes
134+4. **Test thoroughly**: Validate schema changes with existing data
135+
136+### Adding New Logging Points
137+
138+1. **Import DataLogger**: `import { DataLogger } from "core/data/log"`
139+2. **Log events**: Call `DataLogger.getInstance().logDevData(eventName, data)`
140+3. **Follow patterns**: Use existing logging services as examples
141+4. **Validate data**: Ensure logged data matches schema requirements
142+
143+### Debugging Dev Data Issues
144+
145+1. **Check local storage**: Verify files are being created in `~/.continue/dev_data/`
146+2. **Validate schemas**: Ensure event data matches expected schema format
147+3. **Review configuration**: Check `data` blocks in Continue config
148+4. **Test endpoints**: Verify remote endpoints are reachable and accepting data
149+
150+## Best Practices
151+
152+### When Adding New Events
153+
154+- Follow existing naming conventions for event types
155+- Include sufficient context for analysis without oversharing sensitive data
156+- Consider privacy implications and respect user configuration levels
157+- Add appropriate error handling and logging
158+
159+### When Modifying Schemas
160+
161+- Maintain backward compatibility when possible
162+- Document schema changes thoroughly
163+- Consider impact on existing data consumers
164+- Test with real development data
165+
166+### When Integrating Logging
167+
168+- Use the singleton pattern: `DataLogger.getInstance()`
169+- Log events at appropriate points in user workflow
170+- Respect user privacy settings and configuration
171+- Handle errors gracefully without disrupting user experience
172+
173+## Common Patterns
174+
175+### Service-Based Logging
176+
177+Most dev data logging follows a service pattern:
178+
179+```typescript
180+export class FeatureLoggingService {
181+ private dataLogger = DataLogger.getInstance();
182+
183+ logFeatureUsage(data: FeatureUsageData) {
184+ this.dataLogger.logDevData("featureUsage", data);
185+ }
186+}
187+```
188+
189+### Event-Driven Logging
190+
191+Events are typically logged at key interaction points:
192+
193+```typescript
194+// When user accepts autocomplete
195+onAutocompleteAccepted(completion: CompletionData) {
196+ AutocompleteLoggingService.getInstance().logAutocompleteAccepted(completion);
197+}
198+```
199+
200+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.
modified .github/workflows/jetbrains-release.yaml +1 −1
@@ -168,7 +168,7 @@
168168 key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
169169
170170 - name: Build packages (Unix)
171- run: ./scripts/build-packages.sh
171+ run: cd ../.. && ./scripts/build-packages.sh
172172
173173 # npm install core
174174 - name: Install core node_modules
modified .vscode/launch.json +0 −1
@@ -19,7 +19,6 @@
1919 "pauseForSourceMap": false,
2020 "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
2121 "preLaunchTask": "vscode-extension:build",
22- "postDebugTask": "Terminate All Tasks",
2322 "env": {
2423 // "CONTROL_PLANE_ENV": "local",
2524 "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
modified .vscode/tasks.json +0 −13
@@ -223,19 +223,6 @@
223223 ],
224224 "type": "shell",
225225 "problemMatcher": []
226- },
227- {
228- "label": "Terminate All Tasks",
229- "command": "${input:terminate}",
230- "type": "shell"
231- }
232- ],
233- "inputs": [
234- {
235- "id": "terminate",
236- "type": "command",
237- "command": "workbench.action.tasks.terminate",
238- "args": "terminateAll"
239226 }
240227 ]
241228 }
modified binary/package-lock.json +2 −0
@@ -121,6 +121,8 @@
121121 "@babel/preset-env": "^7.24.7",
122122 "@biomejs/biome": "1.6.4",
123123 "@google/generative-ai": "^0.11.4",
124+ "@shikijs/colorized-brackets": "^3.7.0",
125+ "@shikijs/transformers": "^3.7.0",
124126 "@types/diff": "^7.0.1",
125127 "@types/follow-redirects": "^1.14.4",
126128 "@types/jest": "^29.5.12",
modified core/autocomplete/CompletionProvider.ts +1 −1
@@ -254,7 +254,7 @@
254254 completionId: helper.input.completionId,
255255 gitRepo: await this.ide.getRepoName(helper.filepath),
256256 uniqueId: await this.ide.getUniqueId(),
257- timestamp: Date.now(),
257+ timestamp: new Date().toISOString(),
258258 ...helper.options,
259259 };
260260
modified core/autocomplete/util/types.ts +1 −1
@@ -41,5 +41,5 @@
4141 gitRepo?: string;
4242 completionId: string;
4343 uniqueId: string;
44- timestamp: number;
44+ timestamp: string;
4545 }
modified core/context/providers/DocsContextProvider.ts +13 −6
@@ -145,6 +145,11 @@
145145 async loadSubmenuItems(
146146 args: LoadSubmenuItemsArgs,
147147 ): Promise<ContextSubmenuItem[]> {
148+ const { config } = args;
149+ // This set is used to filter out the docs that is not in docs config but exist in sqlite metadata
150+ const configDocsSet = new Set(
151+ config.docs?.map((doc) => doc.startUrl) || [],
152+ );
148153 // Get docs service
149154 const docsService = DocsService.getSingleton();
150155 if (!docsService) {
@@ -159,12 +164,14 @@
159164 // Get all indexed docs from the database
160165 const docs = (await docsService.listMetadata()) ?? [];
161166 for (const { startUrl, title, favicon } of docs) {
162- submenuItems.push({
163- title,
164- id: startUrl,
165- description: new URL(startUrl).hostname,
166- icon: favicon,
167- });
167+ if (configDocsSet.has(startUrl)) {
168+ submenuItems.push({
169+ title,
170+ id: startUrl,
171+ description: new URL(startUrl).hostname,
172+ icon: favicon,
173+ });
174+ }
168175 }
169176
170177 // Sort alphabetically
modified core/context/providers/HttpContextProvider.ts +4 −0
@@ -72,6 +72,10 @@
7272 description: item.description ?? "HTTP Context Item",
7373 content: item.content ?? "",
7474 name: item.name ?? this.options.title ?? "HTTP",
75+ uri: {
76+ type: item.uri.type,
77+ value: item.uri.value,
78+ },
7579 });
7680
7781 return Array.isArray(json)
modified core/indexing/docs/DocsService.ts +87 −11
@@ -107,6 +107,17 @@
107107 );
108108 };
109109
110+const siteIndexingConfigsAreEqualExceptTitleAndFavicon = (
111+ config1: SiteIndexingConfig,
112+ config2: SiteIndexingConfig,
113+) => {
114+ return (
115+ config1.startUrl === config2.startUrl &&
116+ config1.maxDepth === config2.maxDepth &&
117+ config1.useLocalCrawling === config2.useLocalCrawling
118+ );
119+};
120+
110121 /*
111122 General process:
112123 - On config update:
@@ -395,6 +406,21 @@
395406 siteIndexingConfig: SiteIndexingConfig,
396407 ): Promise<boolean> {
397408 try {
409+ // Set a initial status when retrieving cache
410+ this.handleStatusUpdate({
411+ type: "docs",
412+ id: startUrl,
413+ embeddingsProviderId: embeddingId,
414+ isReindexing: false,
415+ title: siteIndexingConfig.title,
416+ debugInfo: "Loaded from cache",
417+ icon: siteIndexingConfig.faviconUrl,
418+ url: startUrl,
419+ progress: 0,
420+ description: "Try to retrieve cache",
421+ status: "indexing",
422+ });
423+
398424 const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId);
399425
400426 if (cacheHit) {
@@ -429,7 +455,8 @@
429455 siteIndexingConfig: SiteIndexingConfig,
430456 forceReindex: boolean = false,
431457 ): Promise<void> {
432- const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig;
458+ const { startUrl, useLocalCrawling, maxDepth, faviconUrl } =
459+ siteIndexingConfig;
433460
434461 // First, if indexing is already in process, don't attempt
435462 // This queue is necessary because indexAndAdd is invoked circularly by config edits
@@ -685,7 +712,9 @@
685712 await this.deleteIndexes(startUrl);
686713 }
687714
688- const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl));
715+ const favicon =
716+ faviconUrl ||
717+ (await fetchFavicon(new URL(siteIndexingConfig.startUrl)));
689718
690719 if (this.shouldCancel(startUrl, startedWithEmbedder)) {
691720 return;
@@ -718,10 +747,6 @@
718747 void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
719748 }
720749
721- this.messenger?.send("refreshSubmenuItems", {
722- providers: ["docs"],
723- });
724-
725750 removeFromFailedGlobalContext(siteIndexingConfig);
726751 } catch (e) {
727752 console.error(
@@ -766,14 +791,22 @@
766791 const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
767792
768793 // Try to get a favicon for the site
769- const favicon = await fetchFavicon(new URL(startUrl));
794+ const favicon =
795+ this.statuses.get(startUrl)?.icon ||
796+ (await fetchFavicon(new URL(startUrl)));
797+
798+ // Always try to make the title match what users set in the config
799+ const title =
800+ this.statuses.get(startUrl)?.title ||
801+ siteEmbeddings.title ||
802+ new URL(startUrl).hostname;
770803
771804 // Add the cached embeddings to our database
772805 await this.add({
773806 favicon,
774807 siteIndexingConfig: {
775808 startUrl,
776- title: siteEmbeddings.title || new URL(startUrl).hostname,
809+ title,
777810 },
778811 chunks: siteEmbeddings.chunks,
779812 embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
@@ -910,6 +943,10 @@
910943 );
911944
912945 if (cacheHit) {
946+ // If cache hit, refresh the submenu items for docs
947+ this.messenger?.send("refreshSubmenuItems", {
948+ providers: ["docs"],
949+ });
913950 // If cache hit, retry the search once
914951 return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
915952 }
@@ -987,8 +1024,7 @@
9871024 const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
9881025
9891026 // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
990- // TODO if only favicon and title change, only update, don't embed
991- // Otherwise anything found in new config that isn't in sqlite should be added/indexed
1027+ // Anything found in new config that isn't in sqlite should be added/indexed
9921028 const addedDocs: SiteIndexingConfig[] = [];
9931029 const changedDocs: SiteIndexingConfig[] = [];
9941030 for (const doc of newConfigDocs) {
@@ -999,12 +1035,26 @@
9991035 (d) => d.startUrl === doc.startUrl,
10001036 );
10011037
1038+ // TODO: Changes to the docs config made while Continue isn't running won't be caught
10021039 if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
1003- changedDocs.push(doc);
1040+ // When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing
1041+ if (
1042+ siteIndexingConfigsAreEqualExceptTitleAndFavicon(
1043+ oldConfigDoc,
1044+ doc,
1045+ )
1046+ ) {
1047+ await this.updateMetadataInSqlite(doc);
1048+ } else {
1049+ changedDocs.push(doc);
1050+ }
10041051 } else {
10051052 if (forceReindex) {
10061053 changedDocs.push(doc);
10071054 } else {
1055+ // This is a temperary fix to catch the changes to the docs config that were made when Continue isn't running
1056+ // We only update title and faviconUrl here
1057+ await this.updateMetadataInSqlite(doc);
10081058 // if get's here, not changed, no update needed, mark as complete
10091059 this.handleStatusUpdate({
10101060 type: "docs",
@@ -1036,6 +1086,10 @@
10361086 console.error("Error syncing docs index on config update", e);
10371087 } finally {
10381088 this.isSyncing = false;
1089+ // Refresh the submenu items for docs
1090+ this.messenger?.send("refreshSubmenuItems", {
1091+ providers: ["docs"],
1092+ });
10391093 }
10401094 }
10411095
@@ -1182,6 +1236,27 @@
11821236 );
11831237 }
11841238
1239+ private async updateMetadataInSqlite(siteIndexingConfig: SiteIndexingConfig) {
1240+ const { startUrl, title, faviconUrl } = siteIndexingConfig;
1241+ const favicon = faviconUrl || (await fetchFavicon(new URL(startUrl)));
1242+ if (!this.config.selectedModelByRole.embed) {
1243+ console.warn(
1244+ `Attempting to add metadata for ${startUrl} without embeddings provider specified`,
1245+ );
1246+ return;
1247+ }
1248+
1249+ const db = await this.getOrCreateSqliteDb();
1250+
1251+ await db.run(
1252+ `UPDATE ${DocsService.sqlitebTableName} SET title = ?, favicon = ? WHERE startUrl = ? AND embeddingsProviderId = ?`,
1253+ title,
1254+ favicon,
1255+ startUrl,
1256+ this.config.selectedModelByRole.embed.embeddingId,
1257+ );
1258+ }
1259+
11851260 private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
11861261 // Handles the case where a user has manually added the doc to config.json
11871262 // so it already exists in the file
@@ -1286,5 +1361,6 @@
12861361 this.messenger?.send("refreshSubmenuItems", {
12871362 providers: ["docs"],
12881363 });
1364+ this.statuses.delete(startUrl);
12891365 }
12901366 }
modified core/llm/autodetect.ts +1 −0
@@ -46,6 +46,7 @@
4646 const PROVIDER_HANDLES_TEMPLATING: string[] = [
4747 "lmstudio",
4848 "openai",
49+ "nvidia",
4950 "ollama",
5051 "together",
5152 "novita",
modified core/llm/defaultSystemMessages.ts +1 −1
@@ -51,7 +51,7 @@
5151 You are in chat mode.
5252
5353 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.
54- If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
54+ If needed concisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
5555
5656 ${CODEBLOCK_FORMATTING_INSTRUCTIONS}
5757 ${EDIT_CODE_INSTRUCTIONS}
modified core/llm/llms/VertexAI.ts +149 −27
@@ -1,4 +1,4 @@
1-import { GoogleAuth } from "google-auth-library";
1+import { AuthClient, GoogleAuth, JWT, auth } from "google-auth-library";
22
33 import { streamResponse, streamSse } from "@continuedev/fetch";
44 import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
@@ -14,30 +14,40 @@
1414 declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown";
1515 declare anthropicInstance: Anthropic;
1616 declare geminiInstance: Gemini;
17+ static AUTH_SCOPES = "https://www.googleapis.com/auth/cloud-platform";
1718
1819 static defaultOptions: Partial<LLMOptions> | undefined = {
1920 maxEmbeddingBatchSize: 250,
2021 region: "us-central1",
2122 };
2223
23- private clientPromise = new GoogleAuth({
24- scopes: "https://www.googleapis.com/auth/cloud-platform",
25- })
26- .getClient()
27- .catch((e) => {
28- console.warn(`Failed to load credentials for Vertex AI: ${e.message}`);
29- });
24+ private clientPromise: Promise<AuthClient | void>;
3025
31- private static getDefaultApiBaseFrom(options: LLMOptions) {
32- const { region, projectId } = options;
33- if (!region || !projectId) {
34- throw new Error(
35- "region and projectId must be defined if apiBase is not provided",
36- );
37- }
38- return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`;
39- }
26+ /*
27+ Vertex Supports 3 different URL formats
28+ 1. Standard VertexAI: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/google/models/{model}:streamGenerateContent
29+ 2. Tuned model: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint}:streamGenerateContent
30+ 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
31+
32+ Authentication can be done using the following
33+ 2. Access token obtained using Google Auth client, passed to endpoint that includes full model path with project id and region
34+ 1. API Key (express mode), region and projectId will be ignored
4035
36+ In all cases we have defined apiBase to be up to everything including the location.
37+ Standard api base: https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/
38+ Express api base: https://aiplatform.googleapis.com/v1/
39+ TODO endpoints is not currently supported (api base is same as standard but we don't have a way to add endpoint name yet
40+
41+ Note that VertexAI uses the term "service endpoint" and "model", like:
42+ {service-endpoint}/v1/{model}:streamGenerateContent
43+ So "model" includes the project, location, publisher, etc
44+
45+ Express mode has limited support
46+ and CRITICALLY is only available to NEW users who had NOT used cloud services before.
47+ However it is pretty common as gemini becomes more popular.
48+ Only Gemini models are supported for now
49+ https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models
50+ */
4151 constructor(_options: LLMOptions) {
4252 if (_options.region !== "us-central1") {
4353 // Any region outside of us-central1 has a max batch size of 5.
@@ -47,7 +57,7 @@
4757 );
4858 }
4959 super(_options);
50- this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options);
60+
5161 this.vertexProvider =
5262 _options.model.includes("mistral") ||
5363 _options.model.includes("codestral") ||
@@ -58,24 +68,130 @@
5868 : _options.model.includes("gemini")
5969 ? "gemini"
6070 : "unknown";
71+
72+ // Set client authentication promise
73+ const { apiKey, region, projectId, env } = _options;
74+ const keyFile = env?.keyFile;
75+ const keyJson = env?.keyJson;
76+
77+ // Acceptable authentication methods:
78+ // apiKey only
79+ // region and projectId AND (keyFile OR keyJson OR nothing)
80+
81+ if (apiKey) {
82+ // Consider warning here instead of throwing error
83+ if (region || projectId || keyFile || keyJson) {
84+ throw new Error(
85+ "Vertex in express mode (api key only) cannot be configured with region, projectId, keyFile, or keyJson",
86+ );
87+ // console.warn(
88+ // "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",
89+ // );
90+ }
91+ if (this.vertexProvider !== "gemini") {
92+ throw new Error(
93+ "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",
94+ );
95+ }
96+ } else {
97+ if (!region && !projectId) {
98+ throw new Error(
99+ "region and projectId are required for VertexAI (when not using express/apiKey mode)",
100+ );
101+ }
102+ if (keyFile && keyJson) {
103+ throw new Error(
104+ "VertexAI credentials can be configured with either keyFile or keyJson but not both",
105+ );
106+ }
107+ }
108+
109+ if (keyJson) {
110+ // Loading keys from manually set JSON
111+ if (typeof keyJson !== "string") {
112+ throw new Error("VertexAI: keyJson must be a JSON string");
113+ }
114+ try {
115+ const parsed = JSON.parse(keyJson);
116+ if (!parsed?.private_key) {
117+ throw new Error("VertexAI: keyJson must contain a valid private key");
118+ }
119+ parsed.private_key = parsed.private_key.replace(/\\n/g, "\n");
120+ const jsonClient = auth.fromJSON(parsed);
121+ if (jsonClient instanceof JWT) {
122+ jsonClient.scopes = [VertexAI.AUTH_SCOPES];
123+ } else {
124+ throw new Error("VertexAI: keyJson must be a valid JWT");
125+ }
126+ this.clientPromise = Promise.resolve(jsonClient);
127+ } catch (e) {
128+ throw new Error("VertexAI: Failed to parse keyJson");
129+ }
130+ } else if (keyFile) {
131+ // Loading keys from manually set file path
132+ if (typeof keyFile !== "string") {
133+ throw new Error("VertexAI: keyFile must be a string");
134+ }
135+ this.clientPromise = new GoogleAuth({
136+ scopes: VertexAI.AUTH_SCOPES,
137+ keyFile,
138+ })
139+ .getClient()
140+ .catch((e) => {
141+ console.warn(
142+ `Failed to load credentials for Vertex AI: ${e.message}`,
143+ );
144+ });
145+ } else {
146+ // Loading keys from local credentials or environment variable
147+ this.clientPromise = new GoogleAuth({
148+ scopes: VertexAI.AUTH_SCOPES,
149+ })
150+ .getClient()
151+ .catch((e) => {
152+ console.warn(
153+ `Failed to load credentials for Vertex AI: ${e.message}`,
154+ );
155+ });
156+ }
157+
158+ // Set api base
159+ if (!this.apiBase) {
160+ if (apiKey) {
161+ // Express mode
162+ this.apiBase = `https://aiplatform.googleapis.com/v1/`;
163+ } else {
164+ this.apiBase = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`;
165+ }
166+ }
167+
168+ // Uses instances of other LLMs since underlying functionality is the same
61169 this.anthropicInstance = new Anthropic(_options);
62170 this.geminiInstance = new Gemini(_options);
63171 }
64172
65- async fetch(url: RequestInfo | URL, init?: RequestInit) {
66- const client = await this.clientPromise;
67- const result = await client?.getAccessToken();
68- if (!result?.token) {
69- throw new Error(
70- "Could not get an access token. Set up your Google Application Default Credentials.",
71- );
173+ async fetch(url: URL, init?: RequestInit) {
174+ const headers: Record<string, string> = {
175+ "Content-Type": "application/json",
176+ };
177+ if (this.apiKey) {
178+ url.searchParams.set("key", this.apiKey);
179+ } else {
180+ const client = await this.clientPromise;
181+ const result = await client?.getAccessToken();
182+ if (!result?.token) {
183+ throw new Error(
184+ "Could not get an access token. Set up your Google Application Default Credentials.",
185+ );
186+ }
187+ headers.Authorization = `Bearer ${result.token}`;
72188 }
189+
73190 return await super.fetch(url, {
74191 ...init,
75192 headers: {
76- "Content-Type": "application/json",
77- Authorization: `Bearer ${result.token}`,
78193 ...init?.headers,
194+ ...headers,
79195 },
80196 });
81197 }
@@ -85,6 +201,10 @@
85201 const convertedArgs = this.anthropicInstance.convertArgs(options);
86202
87203 // Remove the `model` property and add `anthropic_version`
204+ // For claude 4 models
205+ // anthropic_version is a required parameter and must be set to "vertex-2024-10-22".
206+
207+ // const
88208 const { model, ...finalOptions } = convertedArgs;
89209 return {
90210 ...finalOptions,
@@ -104,6 +224,8 @@
104224 this.cacheBehavior?.cacheSystemMessage && systemMessage
105225 );
106226
227+ // <code>/v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict
228+
107229 const apiURL = new URL(
108230 `publishers/anthropic/models/${options.model}:streamRawPredict`,
109231 this.apiBase,
modified core/llm/rules/getSystemMessageWithRules.ts +4 −0
@@ -324,6 +324,10 @@
324324 return applicableRules;
325325 };
326326
327+export function getRuleId(rule: RuleWithSource): string {
328+ return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source;
329+}
330+
327331 export const getSystemMessageWithRules = ({
328332 baseSystemMessage,
329333 userMessage,
modified docs/docs/customization/mcp-tools.mdx +0 −19
@@ -19,22 +19,3 @@
1919 ## Learn More
2020
2121 Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
22-description: Model Context Protocol servers provide specialized functionality
23-keywords: [mcp, blocks, model context protocol, integrations, tools]
24-sidebar_position: 4
25-
26----
27-
28-Model Context Protocol servers provide specialized functionality:
29-
30-- Enable integration with external tools and systems
31-- Create extensible interfaces for custom capabilities
32-- Support more complex interactions with your development environment
33-- Allow partners to contribute specialized functionality
34-- Database Connectors: Understand schema and data models during development
35-
36-![MCP Blocks Overview](/img/mcp-blocks-overview.png)
37-
38-## Learn More
39-
40-Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
modified docs/docs/customize/custom-providers.mdx +27 −0
@@ -987,6 +987,33 @@
987987 "description": "",
988988 "content": ""
989989 }
990+
991+// For response context items with hyperlinks
992+
993+[
994+ {
995+ "name": "",
996+ "description": "",
997+ "content": "",
998+ "uri": {
999+ "type": "file" or "url",
1000+ "value": "file:///path/to/file" or "https://example.com",
1001+ }
1002+ }
1003+]
1004+
1005+// OR
1006+
1007+{
1008+ "name": "",
1009+ "description": "",
1010+ "content": "",
1011+ "uri": {
1012+ "type": "file" or "url",
1013+ "value": "file:///path/to/file" or "https://example.com",
1014+ }
1015+}
1016+
9901017 ```
9911018
9921019 ### `@Commits`
modified docs/docs/customize/deep-dives/mcp.mdx +1 −1
@@ -140,7 +140,7 @@
140140 - "@modelcontextprotocol/server-sqlite"
141141 - "./database.db"
142142 cwd: "/path/to/project"
143-
143+
144144 - name: Local Project Server
145145 command: npm
146146 args:
modified docs/docs/customize/model-providers/top-level/vertexai.mdx +30 −0
@@ -114,3 +114,33 @@
114114 Vertex AI currently does not offer any reranking models.
115115
116116 [Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
117+
118+## Express mode
119+
120+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.
121+
122+<Tabs groupId="config-example">
123+ <TabItem value="yaml" label="YAML">
124+ ```yaml title="config.yaml"
125+ models:
126+ - name: Gemini 2.5 Flash - VertexAI
127+ provider: vertexai
128+ model: gemini-2.5-flash
129+ apiKey: ${{ secrets.GOOGLE_CLOUD_API_KEY }}
130+ ```
131+ </TabItem>
132+ <TabItem value="json" label="JSON">
133+ ```json title="config.json"
134+ {
135+ "models": [
136+ {
137+ "title": "Gemini 2.5 Flash - VertexAI",
138+ "provider": "vertexai",
139+ "model": "gemini-2.5-flash",
140+ "apiKey": "[YOUR_GOOGLE_CLOUD_API_KEY]",
141+ }
142+ ]
143+ }
144+ ```
145+ </TabItem>
146+</Tabs>
added docs/docs/features/agent/context-selection.mdx +3 −0
@@ -0,0 +1,3 @@
1+You can use the same methods to manually add context as [Chat](/features/chat/context-selection).
2+
3+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.
added docs/docs/features/agent/how-to-customize.mdx +27 −0
@@ -0,0 +1,27 @@
1+## Add Rules Blocks
2+
3+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.
4+
5+## Add MCP Tools
6+
7+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.
8+
9+## Tool Policies
10+
11+You can adjust the Agent's tool usage behavior to three options:
12+
13+- **Ask First (default)**: Request user permission with "Cancel" and "Continue" buttons
14+- **Automatic**: Automatically call the tool without requesting permission
15+- **Excluded**: Do not send the tool to the model
16+
17+:::warning
18+Be careful setting tools to "automatic" if their behavior is not read-only.
19+:::
20+
21+To manage tool policies:
22+
23+1. Click the tools icon in the input toolbar
24+2. View and change policies by clicking on the policy text
25+3. You can also toggle groups of tools on/off
26+
27+Tool policies are stored locally per user.
added docs/docs/features/agent/model-setup.mdx +14 −0
@@ -0,0 +1,14 @@
1+We recommend **Claude 3.5 Sonnet** from Anthropic for the best Agent experience.
2+
3+- [Add Claude 3.5 Sonnet to your assistant from the hub](https://hub.continue.dev/anthropic/claude-3-5-sonnet-20241022)
4+- Get your API key from the [Anthropic console](https://console.anthropic.com/)
5+
6+## Other recommended models
7+
8+- [Claude Sonnet 4 from Anthropic](https://hub.continue.dev/anthropic)
9+- [GPT-4o from OpenAI](https://hub.continue.dev/openai/gpt-4o)
10+- [Gemini 2.0 Pro from Google](https://hub.continue.dev/google/gemini-2.0-pro)
11+
12+Agent can be used with models that support tool use through Continue. The best chat models generally support tool use.
13+
14+For more information on models, check out [our recommended chat models](/features/chat/model-setup).
added docs/docs/features/autocomplete/context-selection.mdx +19 −0
@@ -0,0 +1,19 @@
1+# Context Selection
2+
3+Autocomplete will automatically determine context based on the current cursor position. We use the following techniques to determine what to include in the prompt:
4+
5+## File prefix/suffix
6+
7+We will always include the code from your file prior to and after the cursor position.
8+
9+## Definitions from the Language Server Protocol
10+
11+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.
12+
13+## Imported files
14+
15+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.
16+
17+## Recent files
18+
19+We automatically consider recently opened or edited files and include snippets that are relevant to the current completion.
added docs/docs/features/autocomplete/how-to-customize.mdx +5 −0
@@ -0,0 +1,5 @@
1+# How to Customize Autocomplete
2+
3+Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings.
4+
5+For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete).
added docs/docs/features/autocomplete/model-setup.mdx +29 −0
@@ -0,0 +1,29 @@
1+# Autocomplete Model Setup
2+
3+Setting up the right model for autocomplete is crucial for a smooth coding experience. Here are our top recommendations:
4+
5+## Recommended Models
6+
7+### Hosted-Based (Best Performance)
8+
9+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.
10+
11+**Quick Setup:**
12+
13+1. [Add Codestral from the hub](https://hub.continue.dev/mistral/codestral)
14+2. Get your API key from the [Mistral Platform](https://console.mistral.ai/codestral)
15+3. Configure it in your Continue settings
16+
17+### Local/Offline (Privacy First)
18+
19+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.
20+
21+**Quick Setup:**
22+
23+1. Install [Ollama](https://ollama.ai/)
24+2. [Add Qwen 2.5 Coder from the hub](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)
25+3. Configure it in your Continue settings
26+
27+## Need Help?
28+
29+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).
added docs/docs/features/chat/context-selection.mdx +39 −0
@@ -0,0 +1,39 @@
1+## Input
2+
3+Typing a question or instructions into the input box is the only required context.
4+
5+## Highlighted Code
6+
7+The highlighted code you've selected by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) will be included in your prompt.
8+
9+## Active File
10+
11+You can include the currently open file as context by pressing opt/alt + enter when you send your request.
12+
13+## Specific File
14+
15+You can include a specific file in your current workspace by typing '@Files' and selecting the file.
16+
17+## Specific Folder
18+
19+You can include a folder in your current workspace by typing '@Folder' and selecting the directory.
20+
21+## Codebase Search
22+
23+You can automatically include relevant files from your codebase by typing '@Codebase'.
24+
25+## Documentation Site
26+
27+You can include a documentation site as context by typing '@Docs' and selecting the site.
28+
29+## Terminal Contents
30+
31+You can include the contents of the terminal in your IDE by typing '@Terminal'.
32+
33+## Git Diff
34+
35+You can include all of the changes you've made to your current branch by typing '@Git Diff'.
36+
37+## Other Context
38+
39+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).
added docs/docs/features/chat/how-to-customize.mdx +7 −0
@@ -0,0 +1,7 @@
1+There are a number of different ways to customize Chat:
2+
3+- Add a `rules` block to give the model persistent instructions through the system prompt
4+- Configure `@Codebase`
5+- Configure `@Docs`
6+- [Build your own context provider](/guides/build-your-own-context-provider)
7+- [Create a custom code RAG](/guides/custom-code-rag)
added docs/docs/features/chat/model-setup.mdx +19 −0
@@ -0,0 +1,19 @@
1+We recommend setting up a model for the best experience.
2+
3+## Recommended Models
4+
5+Here's our primary model recommendation:
6+
7+**Claude 3.5 Sonnet** from Anthropic
8+
9+- [Add Claude 3.5 Sonnet to your assistant from the hub](https://hub.continue.dev/anthropic/claude-3-5-sonnet-20241022)
10+- Get your API key from the [Anthropic console](https://console.anthropic.com/)
11+
12+Other top models to consider:
13+
14+- [GPT-4o from OpenAI](https://hub.continue.dev/openai/gpt-4o)
15+- [Grok-2 from xAI](https://hub.continue.dev/xai/grok-2)
16+- [Gemini 2.0 Flash from Google](https://hub.continue.dev/google/gemini-2.0-flash)
17+- [Llama 3.1 8b from Meta (local)](https://hub.continue.dev/ollama/llama3.1)
18+
19+For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model).
added docs/docs/features/edit/context-selection.mdx +11 −0
@@ -0,0 +1,11 @@
1+## Input
2+
3+The input you provide is included in the prompt.
4+
5+## Code to Edit
6+
7+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.
8+
9+## Context Providers
10+
11+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.
added docs/docs/features/edit/how-to-customize.mdx +9 −0
@@ -0,0 +1,9 @@
1+## Setting active Edit/Apply model
2+
3+You can configure particular models from your Assistant to be used for Edit and Apply requests.
4+
5+1. Click the 3 dots above the main input
6+2. Click the cube icon to expand the "Models" section
7+3. Use the dropdowns to select models for Edit and Apply
8+
9+Learn more about the [Edit role](/customize/model-roles/edit) and [Apply role](/customize/model-roles/apply).
added docs/docs/features/edit/model-setup.mdx +14 −0
@@ -0,0 +1,14 @@
1+By default, Edit uses the same model as Chat. We recommend **Claude 3.5 Sonnet** from Anthropic.
2+
3+[Explore other Edit models on the Continue Hub →](https://hub.continue.dev)
4+
5+## Apply Model
6+
7+We also recommend setting up an Apply model for the best Edit experience.
8+
9+**Recommended Apply models:**
10+
11+- [Morph v0 Fast Apply](https://hub.continue.dev)
12+- [Relace Instant Apply](https://hub.continue.dev)
13+
14+[Explore other Apply models on the Continue Hub →](https://hub.continue.dev)
modified docs/docusaurus.config.js +49 −0
@@ -636,6 +636,18 @@
636636 to: "/features/autocomplete/how-it-works",
637637 from: "/autocomplete/how-it-works",
638638 },
639+ {
640+ to: "/features/autocomplete/model-setup",
641+ from: "/autocomplete/model-setup",
642+ },
643+ {
644+ to: "/features/autocomplete/how-to-customize",
645+ from: "/autocomplete/how-to-customize",
646+ },
647+ {
648+ to: "/features/autocomplete/context-selection",
649+ from: "/autocomplete/context-selection",
650+ },
639651 {
640652 to: "/features/edit/how-it-works",
641653 from: "/edit/how-it-works",
@@ -656,6 +668,43 @@
656668 to: "/customize/json-reference",
657669 from: ["/json-reference", "/advanced/json-reference"],
658670 },
671+ // New feature page redirects
672+ {
673+ to: "/features/chat/model-setup",
674+ from: "/chat/model-setup",
675+ },
676+ {
677+ to: "/features/chat/how-to-customize",
678+ from: "/chat/how-to-customize",
679+ },
680+ {
681+ to: "/features/chat/context-selection",
682+ from: "/chat/context-selection",
683+ },
684+ {
685+ to: "/features/edit/model-setup",
686+ from: "/edit/model-setup",
687+ },
688+ {
689+ to: "/features/edit/how-to-customize",
690+ from: "/edit/how-to-customize",
691+ },
692+ {
693+ to: "/features/edit/context-selection",
694+ from: "/edit/context-selection",
695+ },
696+ {
697+ to: "/features/agent/model-setup",
698+ from: "/agent/model-setup",
699+ },
700+ {
701+ to: "/features/agent/how-to-customize",
702+ from: "/agent/how-to-customize",
703+ },
704+ {
705+ to: "/features/agent/context-selection",
706+ from: "/agent/context-selection",
707+ },
659708 ],
660709 },
661710 ],
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +6 −0
@@ -7,6 +7,12 @@
77 import com.intellij.openapi.components.service
88 import com.intellij.openapi.fileEditor.FileEditorManager
99
10+class RestartContinueProcess : AnAction() {
11+ override fun actionPerformed(e: AnActionEvent) {
12+ val pluginService = getContinuePluginService(e.project) ?: return
13+ pluginService.coreMessengerManager?.restart()
14+ }
15+}
1016
1117 class AcceptDiffAction : AnAction() {
1218 override fun actionPerformed(e: AnActionEvent) {
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +1 −1
@@ -2,7 +2,7 @@
22
33 class MessageTypes {
44 companion object {
5- val ideMessageTypes = listOf(
5+ val IDE_MESSAGE_TYPES = listOf(
66 "readRangeInFile",
77 "isTelemetryEnabled",
88 "getUniqueId",
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +21 −176
@@ -1,51 +1,40 @@
11 package com.github.continuedev.continueintellijextension.`continue`
22
33 import com.github.continuedev.continueintellijextension.constants.MessageTypes
4-import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
4+import com.github.continuedev.continueintellijextension.`continue`.process.ContinueBinaryProcess
5+import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler
6+import com.github.continuedev.continueintellijextension.`continue`.process.ContinueSocketProcess
57 import com.github.continuedev.continueintellijextension.services.ContinuePluginService
6-import com.github.continuedev.continueintellijextension.services.TelemetryService
78 import com.github.continuedev.continueintellijextension.utils.uuid
89 import com.google.gson.Gson
910 import com.intellij.openapi.components.service
1011 import com.intellij.openapi.project.Project
11-import java.io.*
12-import java.net.Socket
13-import java.nio.charset.StandardCharsets
14-import java.nio.file.Files
15-import java.nio.file.Paths
16-import java.nio.file.attribute.PosixFilePermission
1712 import kotlinx.coroutines.*
1813
1914 class CoreMessenger(
2015 private val project: Project,
21- continueCorePath: String,
2216 private val ideProtocolClient: IdeProtocolClient,
23- val coroutineScope: CoroutineScope
17+ val coroutineScope: CoroutineScope,
18+ private val onExit: () -> Unit
2419 ) {
25- private var writer: Writer? = null
26- private var reader: BufferedReader? = null
27- private var process: Process? = null
2820 private val gson = Gson()
2921 private val responseListeners = mutableMapOf<String, (Any?) -> Unit>()
30- private val useTcp: Boolean = System.getenv("USE_TCP")?.toBoolean() ?: false
31-
32- private fun write(message: String) {
33- try {
34- writer?.write(message + "\r\n")
35- writer?.flush()
36- } catch (e: Exception) {
37- println("Error writing to Continue core: $e")
38- }
39- }
22+ private val process = startContinueProcess()
4023
4124 fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
4225 val id = messageId ?: uuid()
43- val message =
44- gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data))
26+ val message = gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data))
4527 responseListeners[id] = onResponse
46- coroutineScope.launch(Dispatchers.IO) {
47- write(message)
48- }
28+ process.write(message)
29+ }
30+
31+ private fun startContinueProcess(): ContinueProcessHandler {
32+ val isTcp = System.getenv("USE_TCP")?.toBoolean() ?: false
33+ val process = if (isTcp)
34+ ContinueSocketProcess()
35+ else
36+ ContinueBinaryProcess(onExit)
37+ return ContinueProcessHandler(coroutineScope, process, ::handleMessage)
4938 }
5039
5140 private fun handleMessage(json: String) {
@@ -55,13 +44,10 @@
5544 val data = responseMap["data"]
5645
5746 // IDE listeners
58- if (MessageTypes.ideMessageTypes.contains(messageType)) {
47+ if (MessageTypes.IDE_MESSAGE_TYPES.contains(messageType)) {
5948 ideProtocolClient.handleMessage(json) { data ->
60- val message =
61- gson.toJson(
62- mapOf("messageId" to messageId, "messageType" to messageType, "data" to data)
63- )
64- write(message)
49+ val message = gson.toJson(mapOf("messageId" to messageId, "messageType" to messageType, "data" to data))
50+ process.write(message)
6551 }
6652 }
6753
@@ -82,148 +68,7 @@
8268 }
8369 }
8470
85- private fun setPermissions(destination: String) {
86- val osName = System.getProperty("os.name").toLowerCase()
87- if (osName.contains("mac") || osName.contains("darwin")) {
88- ProcessBuilder("xattr", "-dr", "com.apple.quarantine", destination).start().waitFor()
89- setFilePermissions(destination, "rwxr-xr-x")
90- } else if (osName.contains("nix") || osName.contains("nux")) {
91- setFilePermissions(destination, "rwxr-xr-x")
92- }
93- }
94-
95- private fun setFilePermissions(path: String, posixPermissions: String) {
96- val perms = HashSet<PosixFilePermission>()
97- if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ)
98- if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE)
99- if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE)
100- Files.setPosixFilePermissions(Paths.get(path), perms)
101- }
102-
103- private val exitCallbacks: MutableList<() -> Unit> = mutableListOf()
104-
105- fun onDidExit(callback: () -> Unit) {
106- exitCallbacks.add(callback)
107- }
108-
109- init {
110- if (useTcp) {
111- try {
112- val socket = Socket("127.0.0.1", 3000)
113- val writer = PrintWriter(socket.getOutputStream(), true)
114- this.writer = writer
115- val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
116- this.reader = reader
117-
118- Thread {
119- try {
120- while (true) {
121- val line = reader.readLine()
122- if (line != null && line.isNotEmpty()) {
123- try {
124- handleMessage(line)
125- } catch (e: Exception) {
126- println("Error handling message: $line")
127- println(e)
128- }
129- } else {
130- Thread.sleep(100)
131- }
132- }
133- } catch (e: IOException) {
134- e.printStackTrace()
135- } finally {
136- try {
137- reader.close()
138- writer.close()
139- } catch (e: IOException) {
140- e.printStackTrace()
141- }
142- }
143- }
144- .start()
145- } catch (e: Exception) {
146- println("TCP Connection Error: Unable to connect to 127.0.0.1:3000")
147- println("Reason: ${e.message}")
148- e.printStackTrace()
149- }
150- } else {
151- // Set proper permissions synchronously
152- runBlocking(Dispatchers.IO) {
153- setPermissions(continueCorePath)
154- }
155-
156- // Start the subprocess
157- val processBuilder =
158- ProcessBuilder(continueCorePath).directory(File(continueCorePath).parentFile)
159- process = processBuilder.start()
160-
161- val outputStream = process!!.outputStream
162- val inputStream = process!!.inputStream
163-
164- writer = OutputStreamWriter(outputStream, StandardCharsets.UTF_8)
165- reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))
166-
167- process!!.onExit().thenRun {
168- exitCallbacks.forEach { it() }
169- var err = process?.errorStream?.bufferedReader()?.readText()?.trim()
170- if (err != null) {
171- // There are often "⚡️Done in Xms" messages, and we want everything after the last one
172- val delimiter = "⚡ Done in"
173- val doneIndex = err.lastIndexOf(delimiter)
174- if (doneIndex != -1) {
175- err = err.substring(doneIndex + delimiter.length)
176- }
177- }
178-
179- println("Core process exited with output: $err")
180-
181- // Log the cause of the failure
182- val telemetryService = service<TelemetryService>()
183- telemetryService.capture("jetbrains_core_exit", mapOf("error" to err))
184-
185- // Clean up all resources
186- writer?.close()
187- reader?.close()
188- process?.destroy()
189- }
190-
191- coroutineScope.launch(Dispatchers.IO) {
192- try {
193- while (true) {
194- val line = reader?.readLine()
195- if (line != null && line.isNotEmpty()) {
196- try {
197- handleMessage(line)
198- } catch (e: Exception) {
199- println("Error handling message: $line")
200- println(e)
201- }
202- } else {
203- delay(100)
204- }
205- }
206- } catch (e: IOException) {
207- e.printStackTrace()
208- } finally {
209- try {
210- reader?.close()
211- writer?.close()
212- outputStream.close()
213- inputStream.close()
214- process?.destroy()
215- } catch (e: IOException) {
216- e.printStackTrace()
217- }
218- }
219- }
220- }
221- }
222-
22371 fun killSubProcess() {
224- process?.isAlive?.let {
225- exitCallbacks.clear()
226- process?.destroy()
227- }
72+ process.close()
22873 }
22974 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt +27 −30
@@ -2,53 +2,50 @@
22
33 import com.github.continuedev.continueintellijextension.services.TelemetryService
44 import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
5-import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
65 import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
76 import com.intellij.openapi.components.service
7+import com.intellij.openapi.diagnostic.Logger
88 import com.intellij.openapi.project.Project
9-import kotlinx.coroutines.*
9+import kotlinx.coroutines.CoroutineScope
10+import kotlinx.coroutines.delay
11+import kotlinx.coroutines.launch
1012
1113 class CoreMessengerManager(
1214 private val project: Project,
1315 private val ideProtocolClient: IdeProtocolClient,
1416 private val coroutineScope: CoroutineScope
1517 ) {
16-
17- var coreMessenger: CoreMessenger? = null
18+ var coreMessenger: CoreMessenger = createCoreMessenger()
1819 private var lastBackoffInterval = 0.5
20+ private val log = Logger.getInstance(CoreMessengerManager::class.java)
1921
2022 init {
21- coroutineScope.launch {
22- val continueBinaryPath = getContinueBinaryPath()
23- setupCoreMessenger(continueBinaryPath)
24- }
23+ setupAnonymousTelemetry()
2524 }
2625
27- private fun setupCoreMessenger(continueCorePath: String) {
28- try {
29- coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope)
30-
31- coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
32- val allowAnonymousTelemetry = response.castNestedOrNull<Boolean>("content", "result", "config", "allowAnonymousTelemetry")
33-
34- val telemetryService = service<TelemetryService>()
35- if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
36- telemetryService.setup(getMachineUniqueID())
37- }
38- }
39-
40- // On exit, use exponential backoff to create another CoreMessenger
41- coreMessenger?.onDidExit {
26+ fun restart() {
27+ coroutineScope.launch {
28+ try {
29+ coreMessenger.killSubProcess()
4230 lastBackoffInterval *= 2
43- println("CoreMessenger exited, retrying in $lastBackoffInterval seconds")
44- Thread.sleep((lastBackoffInterval * 1000).toLong())
45- setupCoreMessenger(continueCorePath)
31+ log.warn("Continue process exited, retrying in $lastBackoffInterval seconds")
32+ delay((lastBackoffInterval * 1000).toLong())
33+ coreMessenger = createCoreMessenger()
34+ } catch (e: Exception) {
35+ service<TelemetryService>().capture("jetbrains_core_start_error", mapOf("error" to e))
4636 }
47- } catch (err: Throwable) {
48- val telemetryService = service<TelemetryService>()
49- telemetryService.capture("jetbrains_core_start_error", mapOf("error" to err))
37+ }
38+ }
5039
51- err.printStackTrace()
40+ private fun createCoreMessenger() =
41+ CoreMessenger(project, ideProtocolClient, coroutineScope, ::restart)
42+
43+ private fun setupAnonymousTelemetry() {
44+ coreMessenger.request("config/getSerializedProfileInfo", null, null) { response ->
45+ val allowAnonymousTelemetry =
46+ response.castNestedOrNull<Boolean>("content", "result", "config", "allowAnonymousTelemetry")
47+ if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null)
48+ service<TelemetryService>().setup(getMachineUniqueID())
5249 }
5350 }
5451 }
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt +81 −0
@@ -0,0 +1,81 @@
1+package com.github.continuedev.continueintellijextension.`continue`.process
2+
3+import com.github.continuedev.continueintellijextension.services.TelemetryService
4+import com.github.continuedev.continueintellijextension.utils.OS
5+import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
6+import com.github.continuedev.continueintellijextension.utils.getOS
7+import com.intellij.openapi.components.service
8+import kotlinx.coroutines.Dispatchers
9+import kotlinx.coroutines.runBlocking
10+import java.io.File
11+import java.io.InputStream
12+import java.io.OutputStream
13+import java.nio.file.Files
14+import java.nio.file.Paths
15+import java.nio.file.attribute.PosixFilePermission
16+
17+class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
18+
19+ private val process = startBinaryProcess()
20+ override val input: InputStream = process.inputStream
21+ override val output: OutputStream = process.outputStream
22+
23+ override fun close() =
24+ process.destroy()
25+
26+ private fun startBinaryProcess(): Process {
27+ val path = getContinueBinaryPath()
28+ runBlocking(Dispatchers.IO) {
29+ setPermissions()
30+ }
31+ return ProcessBuilder(path).directory(File(path).parentFile)
32+ .start()
33+ .apply { onExit().thenRun(onExit).thenRun { reportErrorTelemetry() } }
34+ }
35+
36+
37+ private fun reportErrorTelemetry() {
38+ var err = process.errorStream?.bufferedReader()?.readText()?.trim()
39+ if (err != null) {
40+ // There are often "⚡️Done in Xms" messages, and we want everything after the last one
41+ val delimiter = "⚡ Done in"
42+ val doneIndex = err.lastIndexOf(delimiter)
43+ if (doneIndex != -1) {
44+ err = err.substring(doneIndex + delimiter.length)
45+ }
46+ }
47+
48+ println("Core process exited with output: $err")
49+
50+ val telemetryService = service<TelemetryService>()
51+ telemetryService.capture("jetbrains_core_exit", mapOf("error" to err))
52+ }
53+
54+ private companion object {
55+
56+ private fun setPermissions() {
57+ val os = getOS()
58+ when (os) {
59+ OS.MAC -> setMacOsPermissions()
60+ OS.WINDOWS -> {}
61+ OS.LINUX -> elevatePermissions()
62+ }
63+ }
64+
65+ private fun setMacOsPermissions() {
66+ ProcessBuilder("xattr", "-dr", "com.apple.quarantine", getContinueBinaryPath()).start().waitFor()
67+ elevatePermissions()
68+ }
69+
70+ private fun elevatePermissions() {
71+ val path = getContinueBinaryPath()
72+ val permissions = setOf(
73+ PosixFilePermission.OWNER_READ,
74+ PosixFilePermission.OWNER_WRITE,
75+ PosixFilePermission.OWNER_EXECUTE
76+ )
77+ Files.setPosixFilePermissions(Paths.get(path), permissions)
78+ }
79+ }
80+
81+}
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcess.kt +13 −0
@@ -0,0 +1,13 @@
1+package com.github.continuedev.continueintellijextension.`continue`.process
2+
3+import java.io.InputStream
4+import java.io.OutputStream
5+
6+interface ContinueProcess {
7+
8+ val input: InputStream
9+ val output: OutputStream
10+
11+ fun close()
12+
13+}
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt +61 −0
@@ -0,0 +1,61 @@
1+package com.github.continuedev.continueintellijextension.`continue`.process
2+
3+import com.github.continuedev.continueintellijextension.error.ContinueErrorService
4+import com.intellij.openapi.components.service
5+import kotlinx.coroutines.*
6+import kotlinx.coroutines.channels.Channel
7+import java.io.BufferedReader
8+import java.io.IOException
9+import java.io.InputStreamReader
10+import java.io.OutputStreamWriter
11+
12+class ContinueProcessHandler(
13+ parentScope: CoroutineScope,
14+ private val process: ContinueProcess,
15+ handleMessage: (String) -> (Unit)
16+) {
17+ private val innerJob = Job()
18+ private val scope = CoroutineScope(parentScope.coroutineContext + innerJob)
19+ private val pendingWrites = Channel<String>(Channel.UNLIMITED)
20+ private val writer = OutputStreamWriter(process.output)
21+ private val reader = BufferedReader(InputStreamReader(process.input))
22+
23+ init {
24+ scope.launch(Dispatchers.IO) {
25+ try {
26+ while (isActive) {
27+ val line = reader.readLine()
28+ if (line != null && line.isNotEmpty()) {
29+ try {
30+ handleMessage(line)
31+ } catch (e: Exception) {
32+ service<ContinueErrorService>().report(e, "Error handling message: $line")
33+ }
34+ } else
35+ delay(100)
36+ }
37+ } catch (e: IOException) {
38+ service<ContinueErrorService>().report(e)
39+ }
40+ }
41+ scope.launch(Dispatchers.IO) {
42+ for (message in pendingWrites) {
43+ writer.write(message)
44+ writer.write("\r\n")
45+ writer.flush()
46+ }
47+ }
48+ }
49+
50+ fun write(message: String) =
51+ pendingWrites.trySend(message)
52+
53+ fun close() {
54+ innerJob.cancel()
55+ scope.launch(Dispatchers.IO) {
56+ reader.close()
57+ writer.close()
58+ process.close()
59+ }
60+ }
61+}
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueSocketProcess.kt +16 −0
@@ -0,0 +1,16 @@
1+package com.github.continuedev.continueintellijextension.`continue`.process
2+
3+import java.io.InputStream
4+import java.io.OutputStream
5+import java.net.Socket
6+
7+class ContinueSocketProcess : ContinueProcess {
8+
9+ private val socket = Socket("127.0.0.1", 3000)
10+ override val input: InputStream = socket.inputStream
11+ override val output: OutputStream = socket.outputStream
12+
13+ override fun close() =
14+ socket.close()
15+
16+}
modified extensions/intellij/src/main/resources/META-INF/plugin.xml +7 −0
@@ -70,6 +70,13 @@
7070 <override-text place="GoToAction" text="Continue: Accept Diff"/>
7171 </action>
7272
73+ <action id="continue.restartProcess"
74+ class="com.github.continuedev.continueintellijextension.actions.RestartContinueProcess"
75+ text="Restart Process"
76+ description="Restart Process">
77+ <override-text place="GoToAction" text="Continue: Restart Process"/>
78+ </action>
79+
7380 <action id="continue.rejectDiff"
7481 class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction"
7582 text="Reject Diff" description="Reject Diff">
added extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueProcessHandlerTest.kt +51 −0
@@ -0,0 +1,51 @@
1+package com.github.continuedev.continueintellijextension.unit
2+
3+import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcess
4+import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler
5+import kotlinx.coroutines.Dispatchers
6+import kotlinx.coroutines.joinAll
7+import kotlinx.coroutines.launch
8+import kotlinx.coroutines.test.runTest
9+import org.junit.jupiter.api.Assertions
10+import org.junit.jupiter.api.RepeatedTest
11+import java.io.InputStream
12+import java.io.OutputStream
13+
14+class ContinueProcessHandlerTest {
15+
16+ @RepeatedTest(5)
17+ fun `test concurrent writes with queue`() = runTest {
18+ val process = StringContinueProcess()
19+ val handler = ContinueProcessHandler(this, process) {}
20+
21+ (0..100).map { i -> launch(Dispatchers.Default) { handler.write("message number $i") } }
22+ .joinAll()
23+
24+ handler.close()
25+
26+ // assert all message lines are present (order is not important)
27+ val lines = process.string.split("\r\n").filter { it.isNotBlank() }
28+ for (i in 0..100)
29+ Assertions.assertTrue(lines.contains("message number $i"))
30+
31+ // note: this test will fail if the handler writes messages directly to the output stream
32+ // this problem can be easily reproduced by removing the channel<string> from the handler code
33+ }
34+
35+ class StringContinueProcess : ContinueProcess {
36+ val string = StringBuilder()
37+ override val input: InputStream = InputStream.nullInputStream()
38+ override val output: OutputStream = object : OutputStream() {
39+ override fun write(b: Int) {
40+ string.append(b.toChar())
41+ }
42+
43+ override fun write(b: ByteArray, off: Int, len: Int) {
44+ string.append(String(b, off, len))
45+ }
46+ }
47+
48+ override fun close() {
49+ }
50+ }
51+}
modified extensions/vscode/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/package.json +2 −0
@@ -19,6 +19,7 @@
1919 "@continuedev/config-yaml": "file:../packages/config-yaml",
2020 "@headlessui/react": "^2.2.0",
2121 "@heroicons/react": "^2.0.18",
22+ "@panzoom/panzoom": "^4.6.0",
2223 "@reduxjs/toolkit": "^2.3.0",
2324 "@tiptap/core": "^2.3.2",
2425 "@tiptap/extension-document": "^2.3.2",
@@ -43,6 +44,7 @@
4344 "handlebars": "^4.7.8",
4445 "lodash": "^4.17.21",
4546 "lowlight": "^3.3.0",
47+ "mermaid": "^11.6.0",
4648 "minisearch": "^7.0.2",
4749 "mustache": "^4.2.0",
4850 "posthog-js": "^1.130.1",
modified gui/public/logos/sambanova.png +0 −0

Binary content is not shown. View the file.

added gui/src/components/StyledMarkdownPreview/MermaidBlock.tsx +175 −0
@@ -0,0 +1,175 @@
1+import {
2+ ArrowPathRoundedSquareIcon,
3+ MagnifyingGlassMinusIcon,
4+ MagnifyingGlassPlusIcon,
5+} from "@heroicons/react/24/outline";
6+import Panzoom from "@panzoom/panzoom";
7+import mermaid from "mermaid";
8+import { useEffect, useId, useRef, useState } from "react";
9+import { useDebouncedEffect } from "../find/useDebounce";
10+import { ToolTip } from "../gui/Tooltip";
11+
12+const MINIMUM_ZOOM_STEP = 0.05;
13+
14+const MERMAID_THEME_COLORS = {
15+ background: "#1e1e1e",
16+ primaryColor: "#4d8bf0",
17+ primaryTextColor: "#ffffff",
18+ primaryBorderColor: "#4d8bf0",
19+ secondaryColor: "#3a6db3",
20+ secondaryTextColor: "#ffffff",
21+ secondaryBorderColor: "#3a6db3",
22+ tertiaryColor: "#59bc89",
23+ tertiaryTextColor: "#ffffff",
24+ tertiaryBorderColor: "#59bc89",
25+ noteBkgColor: "#2d2d2d",
26+ noteTextColor: "#e6e6e6",
27+ noteBorderColor: "#555555",
28+ lineColor: "#8c8c8c",
29+ textColor: "#e6e6e6",
30+ mainBkg: "#252525",
31+ errorBkgColor: "#f44336",
32+ errorTextColor: "#ffffff",
33+ nodeBorder: "#555555",
34+ clusterBkg: "#2a2a2a",
35+ clusterBorder: "#555555",
36+ defaultLinkColor: "#8c8c8c",
37+ titleColor: "#e6e6e6",
38+ edgeLabelBackground: "#252525",
39+ activeTaskBkgColor: "#4caf50",
40+ activeTaskBorderColor: "#388e3c",
41+ doneTaskBkgColor: "#388e3c",
42+ doneTaskBorderColor: "#2e7d32",
43+ critBkgColor: "#f44336",
44+ critBorderColor: "#d32f2f",
45+ taskTextColor: "#e6e6e6",
46+ taskTextOutsideColor: "#e6e6e6",
47+ taskTextLightColor: "#b3b3b3",
48+ sectionBkgColor: "#2a2a2a",
49+ altSectionBkgColor: "#303030",
50+ sectionBkgColor2: "#252525",
51+ excludeBkgColor: "#2d2d2d",
52+ fillType0: "#264f78",
53+ fillType1: "#3a6db3",
54+ fillType2: "#59bc89",
55+ fillType3: "#4d8bf0",
56+ fillType4: "#3a6db3",
57+ fillType5: "#264f78",
58+ fillType6: "#59bc89",
59+ fillType7: "#4d8bf0",
60+};
61+
62+mermaid.initialize({
63+ startOnLoad: false,
64+ securityLevel: "loose",
65+ theme: "dark",
66+ themeVariables: {
67+ ...MERMAID_THEME_COLORS,
68+ fontSize: "14px",
69+ fontFamily: "var(--vscode-font-family)",
70+ },
71+});
72+
73+export default function MermaidDiagram({ code }: { code: string }) {
74+ const mermaidRenderContainerRef = useRef<HTMLDivElement>(null);
75+ const zoomInButtonRef = useRef<SVGSVGElement>(null);
76+ const zoomOutButtonRef = useRef<SVGSVGElement>(null);
77+ const resetZoomButtonRef = useRef<SVGSVGElement>(null);
78+
79+ const zoomInButtonId = useId();
80+ const zoomOutButtonId = useId();
81+ const resetZoomButtonId = useId();
82+
83+ const [isLoading, setIsLoading] = useState(false);
84+ const [error, setError] = useState("");
85+
86+ useEffect(() => {
87+ setIsLoading(true);
88+ }, [code]);
89+
90+ useDebouncedEffect(
91+ () => {
92+ if (mermaidRenderContainerRef.current) {
93+ mermaidRenderContainerRef.current.innerHTML = "";
94+ }
95+ const diagramId = `mermaid-id-${Math.random().toString(36).substring(2)}`;
96+ void (async () => {
97+ if (!mermaidRenderContainerRef.current) return;
98+ try {
99+ await mermaid.parse(code);
100+ const renderedSVG = await mermaid.render(diagramId, code);
101+ mermaidRenderContainerRef.current.innerHTML = renderedSVG.svg;
102+ setError("");
103+ const panzoom = Panzoom(mermaidRenderContainerRef.current, {
104+ step: MINIMUM_ZOOM_STEP,
105+ });
106+ zoomInButtonRef.current?.addEventListener("click", () =>
107+ panzoom.zoomIn({ step: MINIMUM_ZOOM_STEP * 4 }),
108+ );
109+ zoomOutButtonRef.current?.addEventListener("click", () =>
110+ panzoom.zoomOut({ step: MINIMUM_ZOOM_STEP * 4 }),
111+ );
112+ resetZoomButtonRef.current?.addEventListener("click", () =>
113+ panzoom.reset(),
114+ );
115+ mermaidRenderContainerRef.current.parentElement?.addEventListener(
116+ "wheel",
117+ (event) => {
118+ if (!event.shiftKey) return;
119+ panzoom.zoomWithWheel(event);
120+ },
121+ );
122+ } catch (err: any) {
123+ if (err.message) {
124+ setError(err.message);
125+ } else {
126+ setError(
127+ "Unknown error when parsing or rendering the Mermaid diagram.",
128+ );
129+ }
130+ }
131+ setIsLoading(false);
132+ })();
133+ },
134+ 500,
135+ [code],
136+ );
137+
138+ return (
139+ <>
140+ {isLoading && (
141+ <div className="text-vsc-foreground text-xs">Generating diagram...</div>
142+ )}
143+ {!!error ? (
144+ <div className="text-error whitespace-pre text-sm">{error}</div>
145+ ) : (
146+ <div className="relative">
147+ <div className="absolute right-0 z-10 m-2 flex items-center gap-x-1">
148+ <MagnifyingGlassPlusIcon
149+ data-tooltip-id={zoomInButtonId}
150+ ref={zoomInButtonRef}
151+ className="h-4 w-4 cursor-pointer"
152+ />
153+ <ToolTip id={zoomInButtonId}>Zoom In</ToolTip>
154+ <MagnifyingGlassMinusIcon
155+ data-tooltip-id={zoomOutButtonId}
156+ ref={zoomOutButtonRef}
157+ className="h-4 w-4 cursor-pointer"
158+ />
159+ <ToolTip id={zoomOutButtonId}>Zoom Out</ToolTip>
160+ <ArrowPathRoundedSquareIcon
161+ data-tooltip-id={resetZoomButtonId}
162+ ref={resetZoomButtonRef}
163+ className="h-4 w-4 cursor-pointer"
164+ />
165+ <ToolTip id={resetZoomButtonId}>Reset Zoom</ToolTip>
166+ </div>
167+ <div
168+ className="flex min-h-5 justify-center"
169+ ref={mermaidRenderContainerRef}
170+ />
171+ </div>
172+ )}
173+ </>
174+ );
175+}
modified gui/src/components/StyledMarkdownPreview/index.tsx +5 −0
@@ -21,6 +21,7 @@
2121 import FilenameLink from "./FilenameLink";
2222 import "./katex.css";
2323 import "./markdown.css";
24+import MermaidBlock from "./MermaidBlock";
2425 import { rehypeHighlightPlugin } from "./rehypeHighlightPlugin";
2526 import { StepContainerPreToolbar } from "./StepContainerPreToolbar";
2627 import SymbolLink from "./SymbolLink";
@@ -333,6 +334,10 @@
333334 }
334335 }
335336 }
337+ if (codeProps.className?.includes("language-mermaid")) {
338+ const codeText = String(codeProps.children || "");
339+ return <MermaidBlock code={codeText} />;
340+ }
336341 return <code {...codeProps}>{codeProps.children}</code>;
337342 },
338343 },
deleted gui/src/components/dialogs/FeedbackDialog.tsx +0 −64
@@ -1,64 +0,0 @@
1-import { usePostHog } from "posthog-js/react";
2-import { setDialogMessage } from "../../redux/slices/uiSlice";
3-import { useAppDispatch } from "../../redux/hooks";
4-
5-export default function FeedbackDialog() {
6- const posthog = usePostHog();
7- const dispatch = useAppDispatch();
8-
9- return (
10- <div className="p-4 text-center">
11- 👋 Thanks for using Continue. We are always trying to improve and love
12- hearing from users. If you're interested in speaking, enter your name and
13- email. We won't use this information for anything other than reaching out.
14- <br />
15- <br />
16- <form
17- onSubmit={(e: any) => {
18- e.preventDefault();
19- posthog?.capture("user_interest_form", {
20- name: e.target.elements[0].value,
21- email: e.target.elements[1].value,
22- });
23- dispatch(
24- setDialogMessage(
25- <div className="p-4 text-center">
26- Thanks! We'll be in touch soon.
27- </div>,
28- ),
29- );
30- }}
31- style={{
32- display: "flex",
33- flexDirection: "column",
34- gap: "10px",
35- }}
36- >
37- <input
38- style={{ padding: "10px", borderRadius: "5px" }}
39- type="text"
40- name="name"
41- placeholder="Name"
42- required
43- />
44- <input
45- style={{ padding: "10px", borderRadius: "5px" }}
46- type="email"
47- name="email"
48- placeholder="Email"
49- required
50- />
51- <button
52- style={{
53- padding: "10px",
54- borderRadius: "5px",
55- cursor: "pointer",
56- }}
57- type="submit"
58- >
59- Submit
60- </button>
61- </form>
62- </div>
63- );
64-}
modified gui/src/components/find/FindWidget.tsx +1 −1
@@ -18,7 +18,7 @@
1818 SearchMatch,
1919 searchWithinContainer,
2020 } from "./findWidgetSearch";
21-import useDebounceValue from "./useDebounce";
21+import { useDebounceValue } from "./useDebounce";
2222 import { useElementSize } from "./useElementSize";
2323
2424 interface HighlightOverlayProps {
modified gui/src/components/find/useDebounce.ts +31 −3
@@ -1,6 +1,6 @@
1-import { useEffect, useState } from "react";
1+import { useEffect, useRef, useState } from "react";
22
3-function useDebounceValue<T>(value: T, delay: number = 500): T {
3+export function useDebounceValue<T>(value: T, delay: number = 500): T {
44 const [debouncedValue, setDebouncedValue] = useState<T>(value);
55
66 useEffect(() => {
@@ -16,4 +16,32 @@
1616 return debouncedValue;
1717 }
1818
19-export default useDebounceValue;
19+export function useDebouncedEffect(
20+ effect: () => void,
21+ delay: number,
22+ deps: unknown[],
23+) {
24+ const timeoutRef = useRef<NodeJS.Timeout | null>(null);
25+ const callBackRef = useRef(() => {});
26+
27+ useEffect(() => {
28+ // do not want the timeout to reset on effect dep change
29+ callBackRef.current = effect;
30+ }, [effect]);
31+
32+ useEffect(() => {
33+ if (timeoutRef.current) {
34+ clearTimeout(timeoutRef.current);
35+ }
36+
37+ timeoutRef.current = setTimeout(() => {
38+ callBackRef.current();
39+ }, delay);
40+
41+ return () => {
42+ if (timeoutRef.current) {
43+ clearTimeout(timeoutRef.current);
44+ }
45+ };
46+ }, [delay, ...deps]);
47+}
modified gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx +1 −1
@@ -28,7 +28,7 @@
2828 Back to {mode.charAt(0).toUpperCase() + mode.slice(1)}
2929 </span>
3030 <span className="truncate">
31- Editing{" "}
31+ Editing:{" "}
3232 <span className="italic">
3333 {getEditFilenameAndRangeText(codeToEdit)}
3434 </span>
modified gui/src/context/SubmenuContextProviders.tsx +241 −3
@@ -29,6 +29,14 @@
2929
3030 const MAX_LENGTH = 70;
3131
32+// Enhanced search result interface for intelligent sorting
33+interface EnhancedSearchResult
34+ extends SearchResult,
35+ Omit<ContextSubmenuItemWithProvider, "id"> {
36+ sortPriority: number;
37+ matchQuality: number;
38+}
39+
3240 interface SubtextContextProvidersContextType {
3341 getSubmenuContextItems: (
3442 providerTitle: string | undefined,
@@ -43,6 +51,91 @@
4351 const SubmenuContextProvidersContext =
4452 createContext<SubtextContextProvidersContextType>(initialContextProviders);
4553
54+// Helper functions for intelligent file sorting
55+function hasExactWordMatch(text: string, query: string): boolean {
56+ const words = text.split(/[^a-zA-Z0-9]+/);
57+ return words.some((word) => word === query);
58+}
59+
60+function isCommonDevFile(fileName: string): boolean {
61+ const commonExtensions = [
62+ ".ts",
63+ ".tsx",
64+ ".js",
65+ ".jsx",
66+ ".py",
67+ ".java",
68+ ".cpp",
69+ ".c",
70+ ".h",
71+ ".vue",
72+ ".svelte",
73+ ];
74+ const commonNames = [
75+ "index",
76+ "main",
77+ "app",
78+ "component",
79+ "service",
80+ "util",
81+ "helper",
82+ "config",
83+ "types",
84+ ];
85+
86+ const extension = fileName.substring(fileName.lastIndexOf("."));
87+ const baseName = fileName
88+ .substring(0, fileName.lastIndexOf("."))
89+ .toLowerCase();
90+
91+ return commonExtensions.includes(extension) || commonNames.includes(baseName);
92+}
93+
94+function isInCommonDirectory(filePath: string): boolean {
95+ const commonDirs = [
96+ "src/",
97+ "lib/",
98+ "components/",
99+ "utils/",
100+ "helpers/",
101+ "services/",
102+ "pages/",
103+ "views/",
104+ "hooks/",
105+ "store/",
106+ "types/",
107+ "interfaces/",
108+ "models/",
109+ "api/",
110+ ];
111+ return commonDirs.some((dir) => filePath.includes(dir));
112+}
113+
114+function matchesCamelCaseOrAbbreviation(
115+ fileName: string,
116+ query: string,
117+): boolean {
118+ // Extract capital letters for camel case matching
119+ const capitals = fileName.match(/[A-Z]/g)?.join("").toLowerCase() || "";
120+
121+ // Check if query matches the capital letters pattern
122+ if (capitals.length > 0 && capitals.includes(query)) {
123+ return true;
124+ }
125+
126+ // Check for abbreviation matches (first letters of words)
127+ const words = fileName.split(/[^a-zA-Z0-9]+/).filter((w) => w.length > 0);
128+ if (words.length > 1) {
129+ const abbreviation = words
130+ .map((word) => word[0])
131+ .join("")
132+ .toLowerCase();
133+ return abbreviation.includes(query);
134+ }
135+
136+ return false;
137+}
138+
46139 export const SubmenuContextProvidersProvider = ({
47140 children,
48141 }: {
@@ -128,6 +221,98 @@
128221 new Map<ContextProviderName, AbortController>(),
129222 ).current;
130223
224+ const calculateFileSortPriority = useCallback(
225+ (
226+ result: SearchResult & ContextSubmenuItemWithProvider,
227+ query: string,
228+ openFiles: ContextSubmenuItemWithProvider[],
229+ ): number => {
230+ const fileName = result.title.toLowerCase();
231+ const filePath = result.description.toLowerCase();
232+ const queryLower = query.toLowerCase();
233+
234+ // Priority 1: Exact filename match
235+ if (fileName === queryLower) {
236+ return 1;
237+ }
238+
239+ // Priority 2: Recently opened files
240+ if (openFiles.some((f) => f.id === result.id)) {
241+ return 2;
242+ }
243+
244+ // Priority 3: Filename starts with query
245+ if (fileName.startsWith(queryLower)) {
246+ return 3;
247+ }
248+
249+ // Priority 4: Exact word match in filename
250+ if (hasExactWordMatch(fileName, queryLower)) {
251+ return 4;
252+ }
253+
254+ // Priority 5: Common development files
255+ if (isCommonDevFile(fileName)) {
256+ return 5;
257+ }
258+
259+ // Priority 6: Files in common directories
260+ if (isInCommonDirectory(filePath)) {
261+ return 6;
262+ }
263+
264+ // Priority 7: CamelCase/abbreviation matches
265+ if (matchesCamelCaseOrAbbreviation(fileName, queryLower)) {
266+ return 7;
267+ }
268+
269+ // Priority 8: Path starts with query
270+ if (filePath.startsWith(queryLower)) {
271+ return 8;
272+ }
273+
274+ // Priority 9: Default
275+ return 9;
276+ },
277+ [],
278+ );
279+
280+ const calculateMatchQuality = useCallback(
281+ (
282+ result: SearchResult & ContextSubmenuItemWithProvider,
283+ query: string,
284+ ): number => {
285+ const fileName = result.title.toLowerCase();
286+ const queryLower = query.toLowerCase();
287+ let quality = 0;
288+
289+ // Exact match bonus
290+ if (fileName === queryLower) quality += 100;
291+
292+ // Prefix match bonus
293+ if (fileName.startsWith(queryLower)) quality += 50;
294+
295+ // Contains match bonus
296+ if (fileName.includes(queryLower)) quality += 25;
297+
298+ // Shorter filename bonus (prefer concise names)
299+ quality += Math.max(0, 50 - fileName.length);
300+
301+ // Extension preference (common dev files)
302+ if (
303+ fileName.endsWith(".ts") ||
304+ fileName.endsWith(".tsx") ||
305+ fileName.endsWith(".js") ||
306+ fileName.endsWith(".jsx")
307+ ) {
308+ quality += 10;
309+ }
310+
311+ return quality;
312+ },
313+ [],
314+ );
315+
131316 const getSubmenuContextItems = useCallback(
132317 (
133318 providerTitle: string | undefined,
@@ -168,9 +353,57 @@
168353 });
169354 }
170355 }
171- searchResults.sort((a, b) => b.score - a.score);
172356
173- // 2. Add fallback results if no search results
357+ // 2. Enhanced sorting for file provider
358+ if (
359+ providerTitle === "file" ||
360+ (!providerTitle &&
361+ searchResults.some((r) => r.providerTitle === "file"))
362+ ) {
363+ const enhancedResults: EnhancedSearchResult[] = searchResults.map(
364+ (result): EnhancedSearchResult => ({
365+ ...result,
366+ id: result.id,
367+ title: result.title,
368+ description: result.description,
369+ providerTitle: result.providerTitle,
370+ sortPriority: calculateFileSortPriority(
371+ result,
372+ query,
373+ lastOpenFilesRef.current,
374+ ),
375+ matchQuality: calculateMatchQuality(result, query),
376+ }),
377+ );
378+
379+ // Sort by multiple criteria
380+ enhancedResults.sort((a, b) => {
381+ // Primary: Sort priority (lower = better)
382+ if (a.sortPriority !== b.sortPriority) {
383+ return a.sortPriority - b.sortPriority;
384+ }
385+
386+ // Secondary: Match quality (higher = better)
387+ if (a.matchQuality !== b.matchQuality) {
388+ return b.matchQuality - a.matchQuality;
389+ }
390+
391+ // Tertiary: MiniSearch relevance score (higher = better)
392+ if (a.score !== b.score) {
393+ return b.score - a.score;
394+ }
395+
396+ // Quaternary: Path length (shorter = better)
397+ return a.description.length - b.description.length;
398+ });
399+
400+ searchResults = enhancedResults;
401+ } else {
402+ // Default sorting for non-file providers
403+ searchResults.sort((a, b) => b.score - a.score);
404+ }
405+
406+ // 3. Add fallback results if no search results
174407 if (searchResults.length === 0) {
175408 const fallbackItems = (
176409 providerTitle ? (fallbackResults[providerTitle] ?? []) : []
@@ -223,7 +456,12 @@
223456 return [];
224457 }
225458 },
226- [fallbackResults, minisearches],
459+ [
460+ fallbackResults,
461+ minisearches,
462+ calculateFileSortPriority,
463+ calculateMatchQuality,
464+ ],
227465 );
228466
229467 const loadSubmenuItems = useCallback(
modified gui/src/pages/gui/Chat.tsx +0 −20
@@ -16,7 +16,6 @@
1616 import { ErrorBoundary } from "react-error-boundary";
1717 import styled from "styled-components";
1818 import { Button, lightGray, vscBackground } from "../../components";
19-import FeedbackDialog from "../../components/dialogs/FeedbackDialog";
2019 import { useFindWidget } from "../../components/find/FindWidget";
2120 import TimelineItem from "../../components/gui/TimelineItem";
2221 import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton";
@@ -37,18 +36,12 @@
3736 newSession,
3837 updateToolCallOutput,
3938 } from "../../redux/slices/sessionSlice";
40-import {
41- setDialogEntryOn,
42- setDialogMessage,
43- setShowDialog,
44-} from "../../redux/slices/uiSlice";
4539 import { streamEditThunk } from "../../redux/thunks/edit";
4640 import { loadLastSession } from "../../redux/thunks/session";
4741 import { streamResponseThunk } from "../../redux/thunks/streamResponse";
4842 import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
4943
5044 import { cancelStream } from "../../redux/thunks/cancelStream";
51-import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
5245 import { EmptyChatBody } from "./EmptyChatBody";
5346 import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
5447 import { ToolCallDiv } from "./ToolCallDiv";
@@ -221,19 +214,6 @@
221214 editorToClearOnSend.commands.clearContent();
222215 }
223216 }
224-
225- // Increment localstorage counter for popup
226- const currentCount = getLocalStorage("mainTextEntryCounter");
227- if (currentCount) {
228- setLocalStorage("mainTextEntryCounter", currentCount + 1);
229- if (currentCount === 300) {
230- dispatch(setDialogMessage(<FeedbackDialog />));
231- dispatch(setDialogEntryOn(false));
232- dispatch(setShowDialog(true));
233- }
234- } else {
235- setLocalStorage("mainTextEntryCounter", 1);
236- }
237217 },
238218 [
239219 history,
modified gui/src/redux/slices/uiSlice.ts +0 −11
@@ -83,12 +83,6 @@
8383 ) => {
8484 state.dialogMessage = action.payload;
8585 },
86- setDialogEntryOn: (
87- state,
88- action: PayloadAction<UIState["dialogEntryOn"]>,
89- ) => {
90- state.dialogEntryOn = action.payload;
91- },
9286 setShowDialog: (state, action: PayloadAction<UIState["showDialog"]>) => {
9387 state.showDialog = action.payload;
9488 },
@@ -98,9 +92,6 @@
9892 ) => {
9993 state.isExploreDialogOpen = action.payload;
10094 },
101- setHasDismissedExploreDialog: (state, action: PayloadAction<boolean>) => {
102- state.hasDismissedExploreDialog = action.payload;
103- },
10495 // Tools
10596 addTool: (state, action: PayloadAction<Tool>) => {
10697 state.toolSettings[action.payload.function.name] =
@@ -173,10 +164,8 @@
173164 export const {
174165 setOnboardingCard,
175166 setDialogMessage,
176- setDialogEntryOn,
177167 setShowDialog,
178168 setIsExploreDialogOpen,
179- setHasDismissedExploreDialog,
180169 toggleToolSetting,
181170 setToolPolicy,
182171 clearToolPolicy,
modified gui/src/redux/thunks/edit.ts +8 −4
@@ -133,6 +133,14 @@
133133 return;
134134 }
135135
136+ if (!state.editModeState.codeToEdit[0]) {
137+ extra.ideMessenger.post("showToast", [
138+ "info",
139+ "Please open a file to use Edit mode",
140+ ]);
141+ return;
142+ }
143+
136144 dispatch(setMainEditorContentTrigger({}));
137145 dispatch(setPreviousModeEditorContent(editorContent));
138146
@@ -148,9 +156,5 @@
148156 );
149157
150158 dispatch(setIsInEdit(true));
151-
152- if (!state.editModeState.codeToEdit[0]) {
153- extra.ideMessenger.post("edit/addCurrentSelection", undefined);
154- }
155159 },
156160 );
modified gui/src/redux/thunks/moveTerminalProcessToBackground.ts +10 −3
@@ -10,9 +10,10 @@
1010
1111 /**
1212 * This thunk is used to move a terminal command to the background
13- * when the user clicks the "Continue" button in the UI
13+ * when the user clicks the "Move to background" link in the UI
1414 *
15- * It marks the command as visually complete without stopping
15+ * It preserves all existing terminal output, marks the command as
16+ * visually complete, and stops listening to further output from
1617 * the already running process
1718 */
1819 export const moveTerminalProcessToBackground = createAsyncThunk<
@@ -39,6 +40,12 @@
3940 return;
4041 }
4142
43+ // Find existing terminal output to preserve it
44+ const existingOutput = toolCall.output?.find(
45+ (item) => item.name === "Terminal",
46+ );
47+ const existingContent = existingOutput?.content || "";
48+
4249 const status =
4350 "Command moved to background. Further output will be ignored.";
4451
@@ -46,7 +53,7 @@
4653 {
4754 name: "Terminal",
4855 description: "Terminal command output",
49- content: "\n" + status,
56+ content: existingContent + (existingContent ? "\n\n" : "") + status,
5057 status: status,
5158 },
5259 ];
modified gui/src/redux/thunks/streamNormalInput.ts +5 −0
@@ -1,6 +1,7 @@
11 import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
22 import { LLMFullCompletionOptions, ModelDescription, Tool } from "core";
33 import { modelSupportsTools } from "core/llm/autodetect";
4+import { getRuleId } from "core/llm/rules/getSystemMessageWithRules";
45 import { ToCoreProtocol } from "core/protocol";
56 import { BuiltInToolNames } from "core/tools/builtIn";
67 import { selectActiveTools } from "../selectors/selectActiveTools";
@@ -171,6 +172,10 @@
171172 ...(!!activeTools.length && {
172173 tools: activeTools.map((tool) => tool.function.name),
173174 }),
175+ rules: appliedRules.map((rule) => ({
176+ id: getRuleId(rule),
177+ rule: rule.rule,
178+ })),
174179 },
175180 });
176181 // else if (state.session.mode === "edit") {
modified gui/src/util/localStorage.ts +0 −1
@@ -6,7 +6,6 @@
66 hasDismissedExploreDialog: boolean;
77 onboardingStatus?: OnboardingStatus;
88 hasDismissedOnboardingCard: boolean;
9- mainTextEntryCounter: number;
109 ide: "vscode" | "jetbrains";
1110 vsCodeUriScheme: string;
1211 ftc: number;
modified gui/src/util/toolCallState.test.ts +100 −0
@@ -479,4 +479,104 @@
479479 );
480480 expect(currentState.parsedArgs).toEqual({ location: "Paris, France" });
481481 });
482+
483+ it("should handle arguments streamed in full progressive chunks", () => {
484+ // Test case where model streams args progressively but includes full prefix each time
485+ // e.g. '{"query":"te' -> '{"query":"tes' -> '{"query":"test"}'
486+ const currentState: ToolCallState = {
487+ status: "generating",
488+ toolCall: {
489+ id: "call123",
490+ type: "function",
491+ function: {
492+ name: "searchFiles",
493+ arguments: '{"query":"te',
494+ },
495+ },
496+ toolCallId: "call123",
497+ parsedArgs: { query: "te" },
498+ };
499+
500+ const delta: ToolCallDelta = {
501+ function: {
502+ arguments: '{"query":"tes',
503+ },
504+ };
505+
506+ const result = addToolCallDeltaToState(delta, currentState);
507+ expect(result.toolCall.function.arguments).toBe('{"query":"tes');
508+ expect(result.parsedArgs).toEqual({ query: "tes" });
509+
510+ // Continue the streaming
511+ const nextDelta: ToolCallDelta = {
512+ function: {
513+ arguments: '{"query":"test"}',
514+ },
515+ };
516+
517+ const finalResult = addToolCallDeltaToState(nextDelta, result);
518+ expect(finalResult.toolCall.function.arguments).toBe('{"query":"test"}');
519+ expect(finalResult.parsedArgs).toEqual({ query: "test" });
520+ });
521+
522+ it("should handle when args delta is a superset of current args", () => {
523+ // Test case where model sends a subset of the current arguments
524+ // This can happen in certain LLM implementations
525+ const currentState: ToolCallState = {
526+ status: "generating",
527+ toolCall: {
528+ id: "call123",
529+ type: "function",
530+ function: {
531+ name: "searchFiles",
532+ arguments: '{"query":"test"',
533+ },
534+ },
535+ toolCallId: "call123",
536+ parsedArgs: { query: "test" },
537+ };
538+
539+ const delta: ToolCallDelta = {
540+ function: {
541+ arguments: '{"query":"test","limit":10}',
542+ },
543+ };
544+
545+ // The subset should be ignored, keeping the current state
546+ const result = addToolCallDeltaToState(delta, currentState);
547+ expect(result.toolCall.function.arguments).toBe(
548+ '{"query":"test","limit":10}',
549+ );
550+ expect(result.parsedArgs).toEqual({ query: "test", limit: 10 });
551+ });
552+
553+ it("should handle when args are complete JSON and new deltas arrive", () => {
554+ // When args are already a valid JSON object, new deltas should not modify it
555+ const currentState: ToolCallState = {
556+ status: "generating",
557+ toolCall: {
558+ id: "call123",
559+ type: "function",
560+ function: {
561+ name: "searchFiles",
562+ arguments: '{"query":"test","limit":10}',
563+ },
564+ },
565+ toolCallId: "call123",
566+ parsedArgs: { query: "test", limit: 10 },
567+ };
568+
569+ const delta: ToolCallDelta = {
570+ function: {
571+ arguments: ',"sort":"asc"}',
572+ },
573+ };
574+
575+ // The complete JSON should not be modified
576+ const result = addToolCallDeltaToState(delta, currentState);
577+ expect(result.toolCall.function.arguments).toBe(
578+ '{"query":"test","limit":10}',
579+ );
580+ expect(result.parsedArgs).toEqual({ query: "test", limit: 10 });
581+ });
482582 });
modified gui/src/util/toolCallState.ts +15 −6
@@ -34,15 +34,24 @@
3434 if (nameDelta.startsWith(currentName)) {
3535 // Case where model progresssively streams name but full name each time e.g. "readFi" -> "readFil" -> "readFile"
3636 mergedName = nameDelta;
37- } else if (currentName.startsWith(nameDelta)) {
38- // Case where model streams in full name each time e.g. readFile -> readFile -> readFile
39- // do nothing
40- } else {
41- // Case where model streams in name in parts e.g. "read" -> "File"
37+ } else if (!currentName.startsWith(nameDelta)) {
4238 mergedName = currentName + nameDelta;
4339 }
4440
45- const mergedArgs = currentArgs + argsDelta;
41+ // Similar logic for args, with an extra JSON check
42+ let mergedArgs = currentArgs;
43+ try {
44+ // If args is JSON parseable, it is complete, don't add to it
45+ JSON.parse(currentArgs);
46+ } catch (e) {
47+ if (argsDelta.startsWith(currentArgs)) {
48+ // Case where model progresssively streams args but full args each time e.g. "{"file": "file1"}" -> "{"file": "file1", "line": 1}"
49+ mergedArgs = argsDelta;
50+ } else if (!currentArgs.startsWith(argsDelta)) {
51+ // Case where model streams in args in parts e.g. "{"file": "file1"" -> ", "line": 1}"
52+ mergedArgs = currentArgs + argsDelta;
53+ }
54+ }
4655
4756 const [_, parsedArgs] = incrementalParseJson(mergedArgs || "{}");
4857
modified packages/config-yaml/src/schemas/data/autocomplete/index.ts +1 −1
@@ -34,7 +34,7 @@
3434 gitRepo: z.string().optional(),
3535 completionId: z.string(),
3636 uniqueId: z.string(),
37- timestamp: z.number(),
37+ timestamp: z.string(),
3838
3939 // DEPRECATED - no more nested objects after v0.1.0, all flat values
4040 completionOptions: completionOptionsSchema.optional(),
modified packages/config-yaml/src/schemas/data/chatInteraction/index.ts +8 −0
@@ -8,4 +8,12 @@
88 completion: z.string(),
99 sessionId: z.string(),
1010 tools: z.array(z.string()).optional(),
11+ rules: z
12+ .array(
13+ z.object({
14+ id: z.string(),
15+ rule: z.string(),
16+ }),
17+ )
18+ .optional(),
1119 });
modified packages/config-yaml/src/schemas/data/chatInteraction/v0.2.0.ts +1 −0
@@ -17,6 +17,7 @@
1717 modelProvider: true,
1818 sessionId: true,
1919 tools: true,
20+ rules: true,
2021 });
2122
2223 export const chatInteractionEventSchema_0_2_0_noCode =
modified packages/config-yaml/src/schemas/data/editOutcome/v0.2.0.ts +7 −0
@@ -15,10 +15,17 @@
1515 modelTitle: true,
1616 modelProvider: true,
1717 accepted: true,
18+ previousCode: true,
19+ newCode: true,
20+ previousCodeLines: true,
21+ newCodeLines: true,
22+ lineChange: true,
1823 });
1924
2025 export const editOutcomeEventSchema_0_2_0_noCode =
2126 editOutcomeEventSchema_0_2_0.omit({
2227 prompt: true,
2328 completion: true,
29+ previousCode: true,
30+ newCode: true,
2431 });
modified packages/hub/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/hub",
3- "version": "0.0.1",
3+ "version": "0.0.4",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/hub",
9- "version": "0.0.1",
9+ "version": "0.0.4",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-yaml": "^1.0.70"
modified scripts/install-dependencies.ps1 +27 −3
@@ -76,8 +76,20 @@
7676 Write-Host "`nInstalling root-level dependencies..." -ForegroundColor White
7777 npm install
7878
79-Write-Host "`nBuilding openai-adapters..." -ForegroundColor White
80-Push-Location packages/openai-adapters
79+Write-Host "`nBuilding config-types..." -ForegroundColor White
80+Push-Location packages/config-types
81+npm install
82+npm run build
83+Pop-Location
84+
85+Write-Host "`nBuilding fetch..." -ForegroundColor White
86+Push-Location packages/fetch
87+npm install
88+npm run build
89+Pop-Location
90+
91+Write-Host "`nBuilding llm-info..." -ForegroundColor White
92+Push-Location packages/llm-info
8193 npm install
8294 npm run build
8395 Pop-Location
@@ -88,6 +100,18 @@
88100 npm run build
89101 Pop-Location
90102
103+Write-Host "`nBuilding openai-adapters..." -ForegroundColor White
104+Push-Location packages/openai-adapters
105+npm install
106+npm run build
107+Pop-Location
108+
109+Write-Host "`nBuilding hub..." -ForegroundColor White
110+Push-Location packages/hub
111+npm install
112+npm run build
113+Pop-Location
114+
91115 Write-Host "`nInstalling Core extension dependencies..." -ForegroundColor White
92116 Push-Location core
93117 npm install
@@ -127,4 +151,4 @@
127151
128152 npm install
129153
130-Pop-Location
154+Pop-Location
No newline at the end of the file
modified scripts/install-dependencies.sh +27 −3
@@ -30,8 +30,20 @@
3030 echo "Installing root-level dependencies..."
3131 npm install
3232
33-echo "Building openai-adapters..."
34-pushd packages/openai-adapters
33+echo "Building config-types..."
34+pushd packages/config-types
35+npm install
36+npm run build
37+popd
38+
39+echo "Building fetch..."
40+pushd packages/fetch
41+npm install
42+npm run build
43+popd
44+
45+echo "Building llm-info..."
46+pushd packages/llm-info
3547 npm install
3648 npm run build
3749 popd
@@ -42,6 +54,18 @@
4254 npm run build
4355 popd
4456
57+echo "Building openai-adapters..."
58+pushd packages/openai-adapters
59+npm install
60+npm run build
61+popd
62+
63+echo "Building hub..."
64+pushd packages/hub
65+npm install
66+npm run build
67+popd
68+
4569 echo "Installing Core extension dependencies..."
4670 pushd core
4771 ## This flag is set because we pull down Chromium at runtime
@@ -76,4 +100,4 @@
76100 echo "Installing docs dependencies..."
77101 pushd docs
78102 npm install
79-popd
103+popd
No newline at the end of the file
modified scripts/uninstall.js +15 −0
@@ -18,6 +18,21 @@
1818 "./binary/bin",
1919 "./binary/dist",
2020 "./binary/out",
21+ // packages
22+ "./packages/config-types/node_modules",
23+ "./packages/config-types/dist",
24+ "./packages/fetch/node_modules",
25+ "./packages/fetch/dist",
26+ "./packages/llm-info/node_modules",
27+ "./packages/llm-info/dist",
28+ "./packages/config-yaml/node_modules",
29+ "./packages/config-yaml/dist",
30+ "./packages/openai-adapters/node_modules",
31+ "./packages/openai-adapters/dist",
32+ "./packages/hub/node_modules",
33+ "./packages/hub/dist",
34+ // docs
35+ "./docs/node_modules",
2136 // root
2237 "./node_modules",
2338 ];