merge main
This commit is contained in:
commit
7da112bbfa
116 changed files with 4384 additions and 2389 deletions
200
.continue/rules/dev-data-guide.md
Normal file
200
.continue/rules/dev-data-guide.md
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
---
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Continue Development Data (Dev Data) Guide
|
||||
|
||||
## Overview
|
||||
|
||||
Development data (dev data) captures detailed information about how developers interact with LLM-aided development tools. Unlike basic telemetry, dev data includes lots of details into the complete software development workflow, including code context, user interactions, and development patterns.
|
||||
|
||||
## Core Architecture
|
||||
|
||||
### Primary Implementation Files
|
||||
|
||||
- **`/core/data/log.ts`**: Main `DataLogger` class - singleton for event logging and remote transmission
|
||||
- **`/packages/config-yaml/src/schemas/data/`**: Schema definitions for all event types
|
||||
|
||||
### Storage Locations
|
||||
|
||||
- **Default storage**: `~/.continue/dev_data/`
|
||||
- **Event files**: `~/.continue/dev_data/{version}/{eventName}.jsonl`
|
||||
|
||||
## Event Types and Schemas
|
||||
|
||||
### Core Event Types
|
||||
|
||||
1. **`tokensGenerated`**: LLM token usage tracking
|
||||
2. **`autocomplete`**: Code completion interactions
|
||||
3. **`chatInteraction`**: Chat-based development assistance
|
||||
4. **`editInteraction`**: Code editing sessions
|
||||
5. **`editOutcome`**: Results of edit operations
|
||||
6. **`nextEditOutcome`**: Next Edit feature outcomes
|
||||
7. **`chatFeedback`**: User feedback on AI responses
|
||||
8. **`toolUsage`**: Tool interaction statistics
|
||||
9. **`quickEdit`**: Quick edit functionality usage
|
||||
|
||||
### Schema Versioning
|
||||
|
||||
- **Version 0.1.0**: Initial schema implementation
|
||||
- **Version 0.2.0**: Current schema with expanded fields and metadata
|
||||
- **Schema files**: Located in `/packages/config-yaml/src/schemas/data/`
|
||||
|
||||
### Base Schema Structure
|
||||
|
||||
All events inherit from a base schema (`/packages/config-yaml/src/schemas/data/base.ts`):
|
||||
|
||||
```typescript
|
||||
{
|
||||
eventName: string,
|
||||
schema: string,
|
||||
timestamp: string,
|
||||
userId: string,
|
||||
userAgent: string,
|
||||
selectedProfileId: string
|
||||
}
|
||||
```
|
||||
|
||||
## Key Integration Points
|
||||
|
||||
### Autocomplete System
|
||||
|
||||
- **File**: `/core/autocomplete/util/AutocompleteLoggingService.ts`
|
||||
- **Purpose**: Tracks code completion acceptance/rejection, timing, and cache hits
|
||||
- **Integration**: Called from autocomplete engine when completions are shown/accepted
|
||||
|
||||
### Chat Interface
|
||||
|
||||
- **Integration**: Chat interactions logged through `DataLogger.logDevData()`
|
||||
- **Data**: Includes prompts, responses, context, and user feedback
|
||||
- **Privacy**: Can be configured to exclude code content
|
||||
|
||||
### Edit Features
|
||||
|
||||
- **Files**: `/extensions/vscode/src/extension/EditOutcomeTracker.ts`, `/core/nextEdit/NextEditLoggingService.ts`
|
||||
- **Purpose**: Track edit suggestions, acceptance rates, and outcomes
|
||||
- **Integration**: Embedded in edit workflow to capture user decisions
|
||||
|
||||
### LLM Token Tracking
|
||||
|
||||
- **File**: `/core/llm/index.ts`
|
||||
- **Purpose**: Track token usage across all LLM providers
|
||||
- **Storage**: SQLite database for efficient querying and reporting
|
||||
|
||||
## Configuration and Customization
|
||||
|
||||
### Configuration Structure
|
||||
|
||||
Dev data is configured through `data` blocks in your Continue config:
|
||||
|
||||
```yaml
|
||||
data:
|
||||
- name: "Local Development Data"
|
||||
destination: "file:///Users/developer/.continue/dev_data"
|
||||
schema: "0.2.0"
|
||||
level: "all"
|
||||
events: ["autocomplete", "chatInteraction", "editOutcome"]
|
||||
|
||||
- name: "Team Analytics"
|
||||
destination: "https://analytics.yourcompany.com/api/events"
|
||||
schema: "0.2.0"
|
||||
level: "noCode"
|
||||
apiKey: "your-api-key-here"
|
||||
events: ["tokensGenerated", "toolUsage"]
|
||||
```
|
||||
|
||||
### Configuration Options
|
||||
|
||||
- **`destination`**: Where to send data (`file://` for local, `http://`/`https://` for remote)
|
||||
- **`schema`**: Schema version to use (`"0.1.0"` or `"0.2.0"`)
|
||||
- **`level`**: Data detail level (`"all"` includes code, `"noCode"` excludes code content)
|
||||
- **`events`**: Array of event types to collect
|
||||
- **`apiKey`**: Authentication for remote endpoints
|
||||
|
||||
### Privacy Controls
|
||||
|
||||
- **`"all"` level**: Includes code content (prefixes, suffixes, completions)
|
||||
- **`"noCode"` level**: Excludes code content, only metadata and metrics
|
||||
- **Local-first**: Data is always stored locally, remote transmission is optional
|
||||
|
||||
## Making Changes to Dev Data
|
||||
|
||||
### Adding New Event Types
|
||||
|
||||
1. **Create schema**: Add new event schema in `/packages/config-yaml/src/schemas/data/`
|
||||
2. **Update index**: Add to schema aggregator in `/packages/config-yaml/src/schemas/data/index.ts`
|
||||
3. **Implement logging**: Add logging calls in relevant service files
|
||||
4. **Update version**: Consider schema version bump if breaking changes
|
||||
|
||||
### Modifying Existing Events
|
||||
|
||||
1. **Schema changes**: Update schema files in `/packages/config-yaml/src/schemas/data/`
|
||||
2. **Backward compatibility**: Ensure changes don't break existing data consumers
|
||||
3. **Version management**: Increment schema version for breaking changes
|
||||
4. **Test thoroughly**: Validate schema changes with existing data
|
||||
|
||||
### Adding New Logging Points
|
||||
|
||||
1. **Import DataLogger**: `import { DataLogger } from "core/data/log"`
|
||||
2. **Log events**: Call `DataLogger.getInstance().logDevData(eventName, data)`
|
||||
3. **Follow patterns**: Use existing logging services as examples
|
||||
4. **Validate data**: Ensure logged data matches schema requirements
|
||||
|
||||
### Debugging Dev Data Issues
|
||||
|
||||
1. **Check local storage**: Verify files are being created in `~/.continue/dev_data/`
|
||||
2. **Validate schemas**: Ensure event data matches expected schema format
|
||||
3. **Review configuration**: Check `data` blocks in Continue config
|
||||
4. **Test endpoints**: Verify remote endpoints are reachable and accepting data
|
||||
|
||||
## Best Practices
|
||||
|
||||
### When Adding New Events
|
||||
|
||||
- Follow existing naming conventions for event types
|
||||
- Include sufficient context for analysis without oversharing sensitive data
|
||||
- Consider privacy implications and respect user configuration levels
|
||||
- Add appropriate error handling and logging
|
||||
|
||||
### When Modifying Schemas
|
||||
|
||||
- Maintain backward compatibility when possible
|
||||
- Document schema changes thoroughly
|
||||
- Consider impact on existing data consumers
|
||||
- Test with real development data
|
||||
|
||||
### When Integrating Logging
|
||||
|
||||
- Use the singleton pattern: `DataLogger.getInstance()`
|
||||
- Log events at appropriate points in user workflow
|
||||
- Respect user privacy settings and configuration
|
||||
- Handle errors gracefully without disrupting user experience
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Service-Based Logging
|
||||
|
||||
Most dev data logging follows a service pattern:
|
||||
|
||||
```typescript
|
||||
export class FeatureLoggingService {
|
||||
private dataLogger = DataLogger.getInstance();
|
||||
|
||||
logFeatureUsage(data: FeatureUsageData) {
|
||||
this.dataLogger.logDevData("featureUsage", data);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Event-Driven Logging
|
||||
|
||||
Events are typically logged at key interaction points:
|
||||
|
||||
```typescript
|
||||
// When user accepts autocomplete
|
||||
onAutocompleteAccepted(completion: CompletionData) {
|
||||
AutocompleteLoggingService.getInstance().logAutocompleteAccepted(completion);
|
||||
}
|
||||
```
|
||||
|
||||
This guide provides the foundation for understanding and working with Continue's dev data system. Always prioritize user privacy and follow established patterns when making changes.
|
||||
2
.github/workflows/jetbrains-release.yaml
vendored
2
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -168,7 +168,7 @@ jobs:
|
|||
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
|
||||
|
||||
- name: Build packages (Unix)
|
||||
run: ./scripts/build-packages.sh
|
||||
run: cd ../.. && ./scripts/build-packages.sh
|
||||
|
||||
# npm install core
|
||||
- name: Install core node_modules
|
||||
|
|
|
|||
13
.vscode/tasks.json
vendored
13
.vscode/tasks.json
vendored
|
|
@ -223,19 +223,6 @@
|
|||
],
|
||||
"type": "shell",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "Terminate All Tasks",
|
||||
"command": "${input:terminate}",
|
||||
"type": "shell"
|
||||
}
|
||||
],
|
||||
"inputs": [
|
||||
{
|
||||
"id": "terminate",
|
||||
"type": "command",
|
||||
"command": "workbench.action.tasks.terminate",
|
||||
"args": "terminateAll"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
1
binary/.gitignore
vendored
1
binary/.gitignore
vendored
|
|
@ -3,3 +3,4 @@ bin
|
|||
data
|
||||
out
|
||||
tmp
|
||||
tree-sitter
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ function cleanSlate() {
|
|||
rimrafSync(out);
|
||||
rimrafSync(build);
|
||||
rimrafSync(path.join(__dirname, "tmp"));
|
||||
rimrafSync(path.join(__dirname, "tree-sitter"));
|
||||
fs.mkdirSync(bin);
|
||||
fs.mkdirSync(out);
|
||||
fs.mkdirSync(build);
|
||||
|
|
@ -142,6 +143,25 @@ async function buildWithEsbuild() {
|
|||
);
|
||||
});
|
||||
|
||||
// copy tree-sitter colder to binary folder to make it available when running in intellij debug mode
|
||||
const treeSitterDir = path.join(__dirname, "tree-sitter");
|
||||
fs.mkdirSync(treeSitterDir);
|
||||
await new Promise((resolve, reject) => {
|
||||
ncp(
|
||||
path.join(__dirname, "..", "extensions", "vscode", "tree-sitter"),
|
||||
treeSitterDir,
|
||||
{ dereference: true },
|
||||
(error) => {
|
||||
if (error) {
|
||||
console.warn("[error] Error copying tree-sitter files", error);
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const filesToCopy = [
|
||||
"../core/vendor/tree-sitter.wasm",
|
||||
"../core/llm/llamaTokenizerWorkerPool.mjs",
|
||||
|
|
|
|||
2
binary/package-lock.json
generated
2
binary/package-lock.json
generated
|
|
@ -121,6 +121,8 @@
|
|||
"@babel/preset-env": "^7.24.7",
|
||||
"@biomejs/biome": "1.6.4",
|
||||
"@google/generative-ai": "^0.11.4",
|
||||
"@shikijs/colorized-brackets": "^3.7.0",
|
||||
"@shikijs/transformers": "^3.7.0",
|
||||
"@types/diff": "^7.0.1",
|
||||
"@types/follow-redirects": "^1.14.4",
|
||||
"@types/jest": "^29.5.12",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"../../../core/node_modules/sqlite3/**/*",
|
||||
"../../out/tree-sitter.wasm",
|
||||
"../../out/tree-sitter-wasms/*",
|
||||
"../../tree-sitter/**/*",
|
||||
"../../out/llamaTokenizer.mjs",
|
||||
"../../out/llamaTokenizerWorkerPool.mjs",
|
||||
"../../out/tiktokenWorkerPool.mjs",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"../../../core/node_modules/sqlite3/**/*",
|
||||
"../../out/tree-sitter.wasm",
|
||||
"../../out/tree-sitter-wasms/*",
|
||||
"../../tree-sitter/**/*",
|
||||
"../../out/llamaTokenizer.mjs",
|
||||
"../../out/llamaTokenizerWorkerPool.mjs",
|
||||
"../../out/tiktokenWorkerPool.mjs",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"../../../core/node_modules/sqlite3/**/*",
|
||||
"../../out/tree-sitter.wasm",
|
||||
"../../out/tree-sitter-wasms/*",
|
||||
"../../tree-sitter/**/*",
|
||||
"../../out/llamaTokenizer.mjs",
|
||||
"../../out/llamaTokenizerWorkerPool.mjs",
|
||||
"../../out/tiktokenWorkerPool.mjs",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"../../../core/node_modules/sqlite3/**/*",
|
||||
"../../out/tree-sitter.wasm",
|
||||
"../../out/tree-sitter-wasms/*",
|
||||
"../../tree-sitter/**/*",
|
||||
"../../out/llamaTokenizer.mjs",
|
||||
"../../out/llamaTokenizerWorkerPool.mjs",
|
||||
"../../out/tiktokenWorkerPool.mjs",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"../../../core/node_modules/sqlite3/**/*",
|
||||
"../../out/tree-sitter.wasm",
|
||||
"../../out/tree-sitter-wasms/*",
|
||||
"../../tree-sitter/**/*",
|
||||
"../../node_modules/win-ca/lib/crypt32-ia32.node",
|
||||
"../../node_modules/win-ca/lib/crypt32-x64.node",
|
||||
"../../node_modules/win-ca/lib/roots.exe",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"../../../core/node_modules/sqlite3/**/*",
|
||||
"../../out/tree-sitter.wasm",
|
||||
"../../out/tree-sitter-wasms/*",
|
||||
"../../tree-sitter/**/*",
|
||||
"../../node_modules/win-ca/lib/crypt32-ia32.node",
|
||||
"../../node_modules/win-ca/lib/crypt32-x64.node",
|
||||
"../../node_modules/win-ca/lib/roots.exe",
|
||||
|
|
|
|||
|
|
@ -254,7 +254,7 @@ export class CompletionProvider {
|
|||
completionId: helper.input.completionId,
|
||||
gitRepo: await this.ide.getRepoName(helper.filepath),
|
||||
uniqueId: await this.ide.getUniqueId(),
|
||||
timestamp: Date.now(),
|
||||
timestamp: new Date().toISOString(),
|
||||
...helper.options,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -41,5 +41,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
|
|||
gitRepo?: string;
|
||||
completionId: string;
|
||||
uniqueId: string;
|
||||
timestamp: number;
|
||||
timestamp: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,7 +47,8 @@ class MCPConnection {
|
|||
};
|
||||
|
||||
constructor(public options: MCPOptions) {
|
||||
this.transport = this.constructTransport(options);
|
||||
// Don't construct transport in constructor to avoid blocking
|
||||
this.transport = {} as Transport; // Will be set in connectClient
|
||||
|
||||
this.client = new Client(
|
||||
{
|
||||
|
|
@ -132,7 +133,8 @@ class MCPConnection {
|
|||
});
|
||||
}),
|
||||
(async () => {
|
||||
this.transport = this.constructTransport(this.options);
|
||||
this.transport = await this.constructTransportAsync(this.options);
|
||||
|
||||
try {
|
||||
await this.client.connect(this.transport);
|
||||
} catch (error) {
|
||||
|
|
@ -295,7 +297,9 @@ class MCPConnection {
|
|||
};
|
||||
}
|
||||
|
||||
private constructTransport(options: MCPOptions): Transport {
|
||||
private async constructTransportAsync(
|
||||
options: MCPOptions,
|
||||
): Promise<Transport> {
|
||||
switch (options.transport.type) {
|
||||
case "stdio":
|
||||
const env: Record<string, string> = options.transport.env
|
||||
|
|
@ -309,7 +313,7 @@ class MCPConnection {
|
|||
// For non-Windows platforms, try to get the PATH from user shell
|
||||
if (process.platform !== "win32") {
|
||||
try {
|
||||
const shellEnvPath = getEnvPathFromUserShell();
|
||||
const shellEnvPath = await getEnvPathFromUserShell();
|
||||
if (shellEnvPath && shellEnvPath !== process.env.PATH) {
|
||||
env.PATH = shellEnvPath;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,13 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
|||
import MCPConnection from "./MCPConnection";
|
||||
import { StdioOptions } from "../../index.d.js";
|
||||
|
||||
// Mock the shell path utility
|
||||
vi.mock("../../util/shellPath", () => ({
|
||||
getEnvPathFromUserShell: vi
|
||||
.fn()
|
||||
.mockResolvedValue("/usr/local/bin:/usr/bin:/bin"),
|
||||
}));
|
||||
|
||||
describe("MCPConnection", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
|
|
@ -98,7 +105,7 @@ describe("MCPConnection", () => {
|
|||
expect(conn.status).toBe("not-connected");
|
||||
});
|
||||
|
||||
it("should throw on invalid transport type", () => {
|
||||
it("should throw on invalid transport type", async () => {
|
||||
const options = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
|
|
@ -107,9 +114,14 @@ describe("MCPConnection", () => {
|
|||
} as any,
|
||||
};
|
||||
|
||||
expect(() => new MCPConnection(options)).toThrow(
|
||||
"Unsupported transport type: invalid",
|
||||
);
|
||||
const conn = new MCPConnection(options);
|
||||
const abortController = new AbortController();
|
||||
|
||||
// The validation now happens during connectClient, not constructor
|
||||
await conn.connectClient(false, abortController.signal);
|
||||
|
||||
expect(conn.status).toBe("error");
|
||||
expect(conn.errors[0]).toContain("Unsupported transport type: invalid");
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -203,6 +215,15 @@ describe("MCPConnection", () => {
|
|||
() => new Promise((resolve) => setTimeout(resolve, 1000)),
|
||||
);
|
||||
|
||||
// Mock the required methods for successful connection
|
||||
const mockGetServerCapabilities = vi
|
||||
.spyOn(Client.prototype, "getServerCapabilities")
|
||||
.mockReturnValue({
|
||||
resources: {},
|
||||
tools: {},
|
||||
prompts: {},
|
||||
});
|
||||
|
||||
const abortController = new AbortController();
|
||||
await conn.connectClient(false, abortController.signal);
|
||||
|
||||
|
|
@ -211,7 +232,7 @@ describe("MCPConnection", () => {
|
|||
});
|
||||
|
||||
it("should handle connection timeout", async () => {
|
||||
const conn = new MCPConnection({ ...options, timeout: 1 });
|
||||
const conn = new MCPConnection({ ...options, timeout: 50 });
|
||||
const mockConnect = vi
|
||||
.spyOn(Client.prototype, "connect")
|
||||
.mockImplementation(
|
||||
|
|
@ -223,7 +244,9 @@ describe("MCPConnection", () => {
|
|||
|
||||
expect(conn.status).toBe("error");
|
||||
expect(conn.errors[0]).toContain("Failed to connect");
|
||||
expect(mockConnect).toHaveBeenCalled();
|
||||
// The connection should timeout before connect is called due to transport construction
|
||||
// Since transport construction happens first, and we're not mocking that,
|
||||
// the timeout will happen during transport construction or connect attempt
|
||||
});
|
||||
|
||||
it("should handle already connected state", async () => {
|
||||
|
|
|
|||
|
|
@ -145,6 +145,11 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const { config } = args;
|
||||
// This set is used to filter out the docs that is not in docs config but exist in sqlite metadata
|
||||
const configDocsSet = new Set(
|
||||
config.docs?.map((doc) => doc.startUrl) || [],
|
||||
);
|
||||
// Get docs service
|
||||
const docsService = DocsService.getSingleton();
|
||||
if (!docsService) {
|
||||
|
|
@ -159,12 +164,14 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
// Get all indexed docs from the database
|
||||
const docs = (await docsService.listMetadata()) ?? [];
|
||||
for (const { startUrl, title, favicon } of docs) {
|
||||
submenuItems.push({
|
||||
title,
|
||||
id: startUrl,
|
||||
description: new URL(startUrl).hostname,
|
||||
icon: favicon,
|
||||
});
|
||||
if (configDocsSet.has(startUrl)) {
|
||||
submenuItems.push({
|
||||
title,
|
||||
id: startUrl,
|
||||
description: new URL(startUrl).hostname,
|
||||
icon: favicon,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Sort alphabetically
|
||||
|
|
|
|||
|
|
@ -72,6 +72,10 @@ class HttpContextProvider extends BaseContextProvider {
|
|||
description: item.description ?? "HTTP Context Item",
|
||||
content: item.content ?? "",
|
||||
name: item.name ?? this.options.title ?? "HTTP",
|
||||
uri: {
|
||||
type: item.uri.type,
|
||||
value: item.uri.value,
|
||||
},
|
||||
});
|
||||
|
||||
return Array.isArray(json)
|
||||
|
|
|
|||
|
|
@ -107,6 +107,17 @@ const siteIndexingConfigsAreEqual = (
|
|||
);
|
||||
};
|
||||
|
||||
const siteIndexingConfigsAreEqualExceptTitleAndFavicon = (
|
||||
config1: SiteIndexingConfig,
|
||||
config2: SiteIndexingConfig,
|
||||
) => {
|
||||
return (
|
||||
config1.startUrl === config2.startUrl &&
|
||||
config1.maxDepth === config2.maxDepth &&
|
||||
config1.useLocalCrawling === config2.useLocalCrawling
|
||||
);
|
||||
};
|
||||
|
||||
/*
|
||||
General process:
|
||||
- On config update:
|
||||
|
|
@ -395,6 +406,21 @@ export default class DocsService {
|
|||
siteIndexingConfig: SiteIndexingConfig,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
// Set a initial status when retrieving cache
|
||||
this.handleStatusUpdate({
|
||||
type: "docs",
|
||||
id: startUrl,
|
||||
embeddingsProviderId: embeddingId,
|
||||
isReindexing: false,
|
||||
title: siteIndexingConfig.title,
|
||||
debugInfo: "Loaded from cache",
|
||||
icon: siteIndexingConfig.faviconUrl,
|
||||
url: startUrl,
|
||||
progress: 0,
|
||||
description: "Try to retrieve cache",
|
||||
status: "indexing",
|
||||
});
|
||||
|
||||
const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId);
|
||||
|
||||
if (cacheHit) {
|
||||
|
|
@ -429,7 +455,8 @@ export default class DocsService {
|
|||
siteIndexingConfig: SiteIndexingConfig,
|
||||
forceReindex: boolean = false,
|
||||
): Promise<void> {
|
||||
const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig;
|
||||
const { startUrl, useLocalCrawling, maxDepth, faviconUrl } =
|
||||
siteIndexingConfig;
|
||||
|
||||
// First, if indexing is already in process, don't attempt
|
||||
// This queue is necessary because indexAndAdd is invoked circularly by config edits
|
||||
|
|
@ -685,7 +712,9 @@ export default class DocsService {
|
|||
await this.deleteIndexes(startUrl);
|
||||
}
|
||||
|
||||
const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl));
|
||||
const favicon =
|
||||
faviconUrl ||
|
||||
(await fetchFavicon(new URL(siteIndexingConfig.startUrl)));
|
||||
|
||||
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
|
||||
return;
|
||||
|
|
@ -718,10 +747,6 @@ export default class DocsService {
|
|||
void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
|
||||
}
|
||||
|
||||
this.messenger?.send("refreshSubmenuItems", {
|
||||
providers: ["docs"],
|
||||
});
|
||||
|
||||
removeFromFailedGlobalContext(siteIndexingConfig);
|
||||
} catch (e) {
|
||||
console.error(
|
||||
|
|
@ -766,14 +791,22 @@ export default class DocsService {
|
|||
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
|
||||
|
||||
// Try to get a favicon for the site
|
||||
const favicon = await fetchFavicon(new URL(startUrl));
|
||||
const favicon =
|
||||
this.statuses.get(startUrl)?.icon ||
|
||||
(await fetchFavicon(new URL(startUrl)));
|
||||
|
||||
// Always try to make the title match what users set in the config
|
||||
const title =
|
||||
this.statuses.get(startUrl)?.title ||
|
||||
siteEmbeddings.title ||
|
||||
new URL(startUrl).hostname;
|
||||
|
||||
// Add the cached embeddings to our database
|
||||
await this.add({
|
||||
favicon,
|
||||
siteIndexingConfig: {
|
||||
startUrl,
|
||||
title: siteEmbeddings.title || new URL(startUrl).hostname,
|
||||
title,
|
||||
},
|
||||
chunks: siteEmbeddings.chunks,
|
||||
embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
|
||||
|
|
@ -910,6 +943,10 @@ export default class DocsService {
|
|||
);
|
||||
|
||||
if (cacheHit) {
|
||||
// If cache hit, refresh the submenu items for docs
|
||||
this.messenger?.send("refreshSubmenuItems", {
|
||||
providers: ["docs"],
|
||||
});
|
||||
// If cache hit, retry the search once
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
|
||||
}
|
||||
|
|
@ -987,8 +1024,7 @@ export default class DocsService {
|
|||
const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
|
||||
|
||||
// Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
|
||||
// TODO if only favicon and title change, only update, don't embed
|
||||
// Otherwise anything found in new config that isn't in sqlite should be added/indexed
|
||||
// Anything found in new config that isn't in sqlite should be added/indexed
|
||||
const addedDocs: SiteIndexingConfig[] = [];
|
||||
const changedDocs: SiteIndexingConfig[] = [];
|
||||
for (const doc of newConfigDocs) {
|
||||
|
|
@ -999,12 +1035,26 @@ export default class DocsService {
|
|||
(d) => d.startUrl === doc.startUrl,
|
||||
);
|
||||
|
||||
// TODO: Changes to the docs config made while Continue isn't running won't be caught
|
||||
if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
|
||||
changedDocs.push(doc);
|
||||
// When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing
|
||||
if (
|
||||
siteIndexingConfigsAreEqualExceptTitleAndFavicon(
|
||||
oldConfigDoc,
|
||||
doc,
|
||||
)
|
||||
) {
|
||||
await this.updateMetadataInSqlite(doc);
|
||||
} else {
|
||||
changedDocs.push(doc);
|
||||
}
|
||||
} else {
|
||||
if (forceReindex) {
|
||||
changedDocs.push(doc);
|
||||
} else {
|
||||
// This is a temperary fix to catch the changes to the docs config that were made when Continue isn't running
|
||||
// We only update title and faviconUrl here
|
||||
await this.updateMetadataInSqlite(doc);
|
||||
// if get's here, not changed, no update needed, mark as complete
|
||||
this.handleStatusUpdate({
|
||||
type: "docs",
|
||||
|
|
@ -1036,6 +1086,10 @@ export default class DocsService {
|
|||
console.error("Error syncing docs index on config update", e);
|
||||
} finally {
|
||||
this.isSyncing = false;
|
||||
// Refresh the submenu items for docs
|
||||
this.messenger?.send("refreshSubmenuItems", {
|
||||
providers: ["docs"],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1182,6 +1236,27 @@ export default class DocsService {
|
|||
);
|
||||
}
|
||||
|
||||
private async updateMetadataInSqlite(siteIndexingConfig: SiteIndexingConfig) {
|
||||
const { startUrl, title, faviconUrl } = siteIndexingConfig;
|
||||
const favicon = faviconUrl || (await fetchFavicon(new URL(startUrl)));
|
||||
if (!this.config.selectedModelByRole.embed) {
|
||||
console.warn(
|
||||
`Attempting to add metadata for ${startUrl} without embeddings provider specified`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const db = await this.getOrCreateSqliteDb();
|
||||
|
||||
await db.run(
|
||||
`UPDATE ${DocsService.sqlitebTableName} SET title = ?, favicon = ? WHERE startUrl = ? AND embeddingsProviderId = ?`,
|
||||
title,
|
||||
favicon,
|
||||
startUrl,
|
||||
this.config.selectedModelByRole.embed.embeddingId,
|
||||
);
|
||||
}
|
||||
|
||||
private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
|
||||
// Handles the case where a user has manually added the doc to config.json
|
||||
// so it already exists in the file
|
||||
|
|
@ -1286,5 +1361,6 @@ export default class DocsService {
|
|||
this.messenger?.send("refreshSubmenuItems", {
|
||||
providers: ["docs"],
|
||||
});
|
||||
this.statuses.delete(startUrl);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,6 +46,7 @@ import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js";
|
|||
const PROVIDER_HANDLES_TEMPLATING: string[] = [
|
||||
"lmstudio",
|
||||
"openai",
|
||||
"nvidia",
|
||||
"ollama",
|
||||
"together",
|
||||
"novita",
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
|||
You are in chat mode.
|
||||
|
||||
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
|
||||
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
|
||||
If needed concisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
|
||||
|
||||
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
|
||||
${EDIT_CODE_INSTRUCTIONS}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { GoogleAuth } from "google-auth-library";
|
||||
import { AuthClient, GoogleAuth, JWT, auth } from "google-auth-library";
|
||||
|
||||
import { streamResponse, streamSse } from "@continuedev/fetch";
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
|
|
@ -14,30 +14,40 @@ class VertexAI extends BaseLLM {
|
|||
declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown";
|
||||
declare anthropicInstance: Anthropic;
|
||||
declare geminiInstance: Gemini;
|
||||
static AUTH_SCOPES = "https://www.googleapis.com/auth/cloud-platform";
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = {
|
||||
maxEmbeddingBatchSize: 250,
|
||||
region: "us-central1",
|
||||
};
|
||||
|
||||
private clientPromise = new GoogleAuth({
|
||||
scopes: "https://www.googleapis.com/auth/cloud-platform",
|
||||
})
|
||||
.getClient()
|
||||
.catch((e) => {
|
||||
console.warn(`Failed to load credentials for Vertex AI: ${e.message}`);
|
||||
});
|
||||
private clientPromise: Promise<AuthClient | void>;
|
||||
|
||||
private static getDefaultApiBaseFrom(options: LLMOptions) {
|
||||
const { region, projectId } = options;
|
||||
if (!region || !projectId) {
|
||||
throw new Error(
|
||||
"region and projectId must be defined if apiBase is not provided",
|
||||
);
|
||||
}
|
||||
return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`;
|
||||
}
|
||||
/*
|
||||
Vertex Supports 3 different URL formats
|
||||
1. Standard VertexAI: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/google/models/{model}:streamGenerateContent
|
||||
2. Tuned model: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint}:streamGenerateContent
|
||||
3. Express mode: e.g. https://aiplatform.googleapis.com/v1/publishers/google/models/{model}:streamGenerateContent?key={API_KEY} // see https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview
|
||||
|
||||
Authentication can be done using the following
|
||||
2. Access token obtained using Google Auth client, passed to endpoint that includes full model path with project id and region
|
||||
1. API Key (express mode), region and projectId will be ignored
|
||||
|
||||
In all cases we have defined apiBase to be up to everything including the location.
|
||||
Standard api base: https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/
|
||||
Express api base: https://aiplatform.googleapis.com/v1/
|
||||
TODO endpoints is not currently supported (api base is same as standard but we don't have a way to add endpoint name yet
|
||||
|
||||
Note that VertexAI uses the term "service endpoint" and "model", like:
|
||||
{service-endpoint}/v1/{model}:streamGenerateContent
|
||||
So "model" includes the project, location, publisher, etc
|
||||
|
||||
Express mode has limited support
|
||||
and CRITICALLY is only available to NEW users who had NOT used cloud services before.
|
||||
However it is pretty common as gemini becomes more popular.
|
||||
Only Gemini models are supported for now
|
||||
https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models
|
||||
*/
|
||||
constructor(_options: LLMOptions) {
|
||||
if (_options.region !== "us-central1") {
|
||||
// Any region outside of us-central1 has a max batch size of 5.
|
||||
|
|
@ -47,7 +57,7 @@ class VertexAI extends BaseLLM {
|
|||
);
|
||||
}
|
||||
super(_options);
|
||||
this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options);
|
||||
|
||||
this.vertexProvider =
|
||||
_options.model.includes("mistral") ||
|
||||
_options.model.includes("codestral") ||
|
||||
|
|
@ -58,24 +68,130 @@ class VertexAI extends BaseLLM {
|
|||
: _options.model.includes("gemini")
|
||||
? "gemini"
|
||||
: "unknown";
|
||||
|
||||
// Set client authentication promise
|
||||
const { apiKey, region, projectId, env } = _options;
|
||||
const keyFile = env?.keyFile;
|
||||
const keyJson = env?.keyJson;
|
||||
|
||||
// Acceptable authentication methods:
|
||||
// apiKey only
|
||||
// region and projectId AND (keyFile OR keyJson OR nothing)
|
||||
|
||||
if (apiKey) {
|
||||
// Consider warning here instead of throwing error
|
||||
if (region || projectId || keyFile || keyJson) {
|
||||
throw new Error(
|
||||
"Vertex in express mode (api key only) cannot be configured with region, projectId, keyFile, or keyJson",
|
||||
);
|
||||
// console.warn(
|
||||
// "Region, projectId, and key path/file are ignored when apiKey is set. See VertexAI Express Mode docs https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview",
|
||||
// );
|
||||
}
|
||||
if (this.vertexProvider !== "gemini") {
|
||||
throw new Error(
|
||||
"VertexAI: only gemini models are supported in express (apiKey) mode. See https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models",
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (!region && !projectId) {
|
||||
throw new Error(
|
||||
"region and projectId are required for VertexAI (when not using express/apiKey mode)",
|
||||
);
|
||||
}
|
||||
if (keyFile && keyJson) {
|
||||
throw new Error(
|
||||
"VertexAI credentials can be configured with either keyFile or keyJson but not both",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (keyJson) {
|
||||
// Loading keys from manually set JSON
|
||||
if (typeof keyJson !== "string") {
|
||||
throw new Error("VertexAI: keyJson must be a JSON string");
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(keyJson);
|
||||
if (!parsed?.private_key) {
|
||||
throw new Error("VertexAI: keyJson must contain a valid private key");
|
||||
}
|
||||
parsed.private_key = parsed.private_key.replace(/\\n/g, "\n");
|
||||
const jsonClient = auth.fromJSON(parsed);
|
||||
if (jsonClient instanceof JWT) {
|
||||
jsonClient.scopes = [VertexAI.AUTH_SCOPES];
|
||||
} else {
|
||||
throw new Error("VertexAI: keyJson must be a valid JWT");
|
||||
}
|
||||
this.clientPromise = Promise.resolve(jsonClient);
|
||||
} catch (e) {
|
||||
throw new Error("VertexAI: Failed to parse keyJson");
|
||||
}
|
||||
} else if (keyFile) {
|
||||
// Loading keys from manually set file path
|
||||
if (typeof keyFile !== "string") {
|
||||
throw new Error("VertexAI: keyFile must be a string");
|
||||
}
|
||||
this.clientPromise = new GoogleAuth({
|
||||
scopes: VertexAI.AUTH_SCOPES,
|
||||
keyFile,
|
||||
})
|
||||
.getClient()
|
||||
.catch((e) => {
|
||||
console.warn(
|
||||
`Failed to load credentials for Vertex AI: ${e.message}`,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
// Loading keys from local credentials or environment variable
|
||||
this.clientPromise = new GoogleAuth({
|
||||
scopes: VertexAI.AUTH_SCOPES,
|
||||
})
|
||||
.getClient()
|
||||
.catch((e) => {
|
||||
console.warn(
|
||||
`Failed to load credentials for Vertex AI: ${e.message}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Set api base
|
||||
if (!this.apiBase) {
|
||||
if (apiKey) {
|
||||
// Express mode
|
||||
this.apiBase = `https://aiplatform.googleapis.com/v1/`;
|
||||
} else {
|
||||
this.apiBase = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`;
|
||||
}
|
||||
}
|
||||
|
||||
// Uses instances of other LLMs since underlying functionality is the same
|
||||
this.anthropicInstance = new Anthropic(_options);
|
||||
this.geminiInstance = new Gemini(_options);
|
||||
}
|
||||
|
||||
async fetch(url: RequestInfo | URL, init?: RequestInit) {
|
||||
const client = await this.clientPromise;
|
||||
const result = await client?.getAccessToken();
|
||||
if (!result?.token) {
|
||||
throw new Error(
|
||||
"Could not get an access token. Set up your Google Application Default Credentials.",
|
||||
);
|
||||
async fetch(url: URL, init?: RequestInit) {
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
if (this.apiKey) {
|
||||
url.searchParams.set("key", this.apiKey);
|
||||
} else {
|
||||
const client = await this.clientPromise;
|
||||
const result = await client?.getAccessToken();
|
||||
if (!result?.token) {
|
||||
throw new Error(
|
||||
"Could not get an access token. Set up your Google Application Default Credentials.",
|
||||
);
|
||||
}
|
||||
headers.Authorization = `Bearer ${result.token}`;
|
||||
}
|
||||
|
||||
return await super.fetch(url, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${result.token}`,
|
||||
...init?.headers,
|
||||
...headers,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -85,6 +201,10 @@ class VertexAI extends BaseLLM {
|
|||
const convertedArgs = this.anthropicInstance.convertArgs(options);
|
||||
|
||||
// Remove the `model` property and add `anthropic_version`
|
||||
// For claude 4 models
|
||||
// anthropic_version is a required parameter and must be set to "vertex-2024-10-22".
|
||||
|
||||
// const
|
||||
const { model, ...finalOptions } = convertedArgs;
|
||||
return {
|
||||
...finalOptions,
|
||||
|
|
@ -104,6 +224,8 @@ class VertexAI extends BaseLLM {
|
|||
this.cacheBehavior?.cacheSystemMessage && systemMessage
|
||||
);
|
||||
|
||||
// <code>/v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict
|
||||
|
||||
const apiURL = new URL(
|
||||
`publishers/anthropic/models/${options.model}:streamRawPredict`,
|
||||
this.apiBase,
|
||||
|
|
|
|||
|
|
@ -324,6 +324,10 @@ export const getApplicableRules = (
|
|||
return applicableRules;
|
||||
};
|
||||
|
||||
export function getRuleId(rule: RuleWithSource): string {
|
||||
return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source;
|
||||
}
|
||||
|
||||
export const getSystemMessageWithRules = ({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
"claude-3-7",
|
||||
"claude-3.7",
|
||||
"claude-sonnet-4",
|
||||
"claude-4-sonnet",
|
||||
"gpt-4",
|
||||
"o3",
|
||||
"gemini",
|
||||
|
|
@ -33,6 +34,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
"claude-3-7",
|
||||
"claude-3.7",
|
||||
"claude-sonnet-4",
|
||||
"claude-4-sonnet",
|
||||
"claude-opus-4",
|
||||
].some((part) => model.toLowerCase().startsWith(part))
|
||||
) {
|
||||
|
|
@ -95,6 +97,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
"claude-3-7-sonnet",
|
||||
"claude-3.7-sonnet",
|
||||
"claude-sonnet-4",
|
||||
"claude-4-sonnet",
|
||||
"claude-opus-4",
|
||||
"nova-lite",
|
||||
"nova-pro",
|
||||
|
|
|
|||
|
|
@ -482,12 +482,13 @@ export class EditAggregator {
|
|||
return;
|
||||
}
|
||||
|
||||
const diff = createDiff(
|
||||
beforeContent,
|
||||
afterContent,
|
||||
filePath,
|
||||
DiffFormatType.Unified,
|
||||
); // Used for checks, not for final output
|
||||
const diff = createDiff({
|
||||
beforeContent: beforeContent,
|
||||
afterContent: afterContent,
|
||||
filePath: filePath,
|
||||
diffType: DiffFormatType.Unified,
|
||||
contextLines: 3,
|
||||
}); // Used for checks, not for final output
|
||||
|
||||
// Skip diffs with too many changed lines
|
||||
const changedLineCount = this.countChangedLines(diff);
|
||||
|
|
|
|||
|
|
@ -12,15 +12,29 @@ export type BeforeAfterDiff = {
|
|||
afterContent: string;
|
||||
};
|
||||
|
||||
export const createDiff = (
|
||||
beforeContent: string,
|
||||
afterContent: string,
|
||||
filePath: string,
|
||||
diffType: DiffFormatType,
|
||||
) => {
|
||||
export interface CreateDiffArgs {
|
||||
beforeContent: string;
|
||||
afterContent: string;
|
||||
filePath: string;
|
||||
diffType: DiffFormatType;
|
||||
contextLines: number;
|
||||
}
|
||||
|
||||
export const createDiff = ({
|
||||
beforeContent,
|
||||
afterContent,
|
||||
filePath,
|
||||
diffType,
|
||||
contextLines,
|
||||
}: CreateDiffArgs) => {
|
||||
switch (diffType) {
|
||||
case DiffFormatType.Unified:
|
||||
return createUnifiedDiff(beforeContent, afterContent, filePath);
|
||||
return createUnifiedDiff(
|
||||
beforeContent,
|
||||
afterContent,
|
||||
filePath,
|
||||
contextLines,
|
||||
);
|
||||
case DiffFormatType.TokenLineDiff:
|
||||
return createTokenLineDiff(beforeContent, afterContent, filePath);
|
||||
}
|
||||
|
|
@ -31,6 +45,7 @@ const createUnifiedDiff = (
|
|||
beforeContent: string,
|
||||
afterContent: string,
|
||||
filePath: string,
|
||||
contextLines: number,
|
||||
) => {
|
||||
const normalizedBefore = beforeContent.endsWith("\n")
|
||||
? beforeContent
|
||||
|
|
@ -45,7 +60,7 @@ const createUnifiedDiff = (
|
|||
normalizedAfter,
|
||||
"before",
|
||||
"after",
|
||||
{ context: 3 },
|
||||
{ context: contextLines },
|
||||
);
|
||||
|
||||
return patch;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { IDE, Position } from "../..";
|
|||
import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
|
||||
import { GetLspDefinitionsFunction } from "../../autocomplete/types";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
// import { DataLogger } from "../../data/log";
|
||||
import { DataLogger } from "../../data/log";
|
||||
import { RecentlyEditedRange } from "../types";
|
||||
import { getAutocompleteContext } from "./autocompleteContextFetching";
|
||||
import { createDiff, DiffFormatType } from "./diffFormatting";
|
||||
|
|
@ -108,31 +108,32 @@ export const processNextEditData = async ({
|
|||
);
|
||||
}
|
||||
|
||||
// if (filenamesAndDiffs.length > 0) {
|
||||
// // if there are previous edits, log
|
||||
// void DataLogger.getInstance().logDevData({
|
||||
// name: "nextEditWithHistory",
|
||||
// data: {
|
||||
// previousEdits: filenamesAndDiffs,
|
||||
// fileURI: filePath,
|
||||
// workspaceDirURI: workspaceDir,
|
||||
// beforeContent,
|
||||
// afterContent,
|
||||
// beforeCursorPos: cursorPosBeforeEdit,
|
||||
// afterCursorPos: cursorPosAfterPrevEdit,
|
||||
// context: autocompleteContext,
|
||||
// },
|
||||
// });
|
||||
// }
|
||||
if (filenamesAndDiffs.length > 0) {
|
||||
// if there are previous edits, log
|
||||
void DataLogger.getInstance().logDevData({
|
||||
name: "nextEditWithHistory",
|
||||
data: {
|
||||
previousEdits: filenamesAndDiffs,
|
||||
fileURI: filePath,
|
||||
workspaceDirURI: workspaceDir,
|
||||
beforeContent,
|
||||
afterContent,
|
||||
beforeCursorPos: cursorPosBeforeEdit,
|
||||
afterCursorPos: cursorPosAfterPrevEdit,
|
||||
context: autocompleteContext,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// add current edit to history
|
||||
const thisEdit: prevEdit = {
|
||||
unidiff: createDiff(
|
||||
beforeContent,
|
||||
afterContent,
|
||||
filePath,
|
||||
DiffFormatType.Unified,
|
||||
),
|
||||
unidiff: createDiff({
|
||||
beforeContent: beforeContent,
|
||||
afterContent: afterContent,
|
||||
filePath: filePath,
|
||||
diffType: DiffFormatType.Unified,
|
||||
contextLines: 25, // storing many context lines for downstream trimming
|
||||
}),
|
||||
fileUri: filePath,
|
||||
workspaceUri: workspaceDir,
|
||||
timestamp: timestamp,
|
||||
|
|
|
|||
|
|
@ -15,12 +15,13 @@ export const processSmallEdit = async (
|
|||
ide: IDE,
|
||||
) => {
|
||||
NextEditProvider.getInstance().addDiffToContext(
|
||||
createDiff(
|
||||
beforeAfterdiff.beforeContent,
|
||||
beforeAfterdiff.afterContent,
|
||||
beforeAfterdiff.filePath,
|
||||
DiffFormatType.Unified,
|
||||
),
|
||||
createDiff({
|
||||
beforeContent: beforeAfterdiff.beforeContent,
|
||||
afterContent: beforeAfterdiff.afterContent,
|
||||
filePath: beforeAfterdiff.filePath,
|
||||
diffType: DiffFormatType.Unified,
|
||||
contextLines: 3, // NOTE: This can change depending on experiments!
|
||||
}),
|
||||
);
|
||||
|
||||
// Get the current context data from the most recent message
|
||||
|
|
|
|||
|
|
@ -56,7 +56,11 @@ Critical rules:
|
|||
* Include just the changing lines, and a few surrounding lines if needed for uniqueness.
|
||||
* Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
|
||||
* Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
|
||||
4. Special operations:
|
||||
4. Splitting up tool calls:
|
||||
* When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls
|
||||
* If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
|
||||
* DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
|
||||
5. Special operations:
|
||||
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
|
||||
* To delete code: Use empty REPLACE section
|
||||
|
||||
|
|
|
|||
|
|
@ -39,14 +39,13 @@ export const getConfigDependentToolDefinitions = (
|
|||
params: ConfigDependentToolParams,
|
||||
): Tool[] => [
|
||||
requestRuleTool(params),
|
||||
// Search and replace is now generally available
|
||||
searchAndReplaceInFileTool,
|
||||
// Keep edit file tool available for models that need it
|
||||
editFileTool,
|
||||
...(params.enableExperimentalTools
|
||||
? [
|
||||
searchAndReplaceInFileTool,
|
||||
viewRepoMapTool,
|
||||
viewSubdirectoryTool,
|
||||
codebaseTool,
|
||||
]
|
||||
: [editFileTool]),
|
||||
? [viewRepoMapTool, viewSubdirectoryTool, codebaseTool]
|
||||
: []),
|
||||
];
|
||||
|
||||
export const getToolsForIde = async (ide: IDE): Promise<Tool[]> =>
|
||||
|
|
|
|||
|
|
@ -6,9 +6,9 @@ export function safeParseToolCallArgs(
|
|||
try {
|
||||
return JSON.parse(toolCall.function?.arguments?.trim() || "{}");
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`Failed to parse tool call arguments:\nTool call: ${toolCall.function?.name + " " + toolCall.id}\nArgs:${toolCall.function?.arguments}\n`,
|
||||
);
|
||||
//console.error(
|
||||
// `Failed to parse tool call arguments:\nTool call: ${toolCall.function?.name + " " + toolCall.id}\nArgs:${toolCall.function?.arguments}\n`,
|
||||
//);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import * as URI from "uri-js";
|
||||
import * as YAML from "yaml";
|
||||
|
||||
import { ConfigYaml, DevEventName } from "@continuedev/config-yaml";
|
||||
|
|
@ -466,3 +467,38 @@ export function getDiffsDirectoryPath(): string {
|
|||
}
|
||||
return diffsPath;
|
||||
}
|
||||
|
||||
export const isFileWithinFolder = (
|
||||
fileUri: string,
|
||||
folderPath: string,
|
||||
): boolean => {
|
||||
try {
|
||||
if (!fileUri || !folderPath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const fileUriParsed = URI.parse(fileUri);
|
||||
const fileScheme = fileUriParsed.scheme || "file";
|
||||
let filePath = fileUriParsed.path || "";
|
||||
filePath = decodeURIComponent(filePath);
|
||||
|
||||
let folderWithScheme = folderPath;
|
||||
if (!folderPath.includes("://")) {
|
||||
folderWithScheme = `${fileScheme}://${folderPath.startsWith("/") ? "" : "/"}${folderPath}`;
|
||||
}
|
||||
const folderUriParsed = URI.parse(folderWithScheme);
|
||||
|
||||
let folderPathClean = folderUriParsed.path || "";
|
||||
folderPathClean = decodeURIComponent(folderPathClean);
|
||||
|
||||
filePath = filePath.replace(/\/$/, "");
|
||||
folderPathClean = folderPathClean.replace(/\/$/, "");
|
||||
|
||||
return (
|
||||
filePath === folderPathClean || filePath.startsWith(`${folderPathClean}/`)
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error in isFileWithinFolder:", error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { execSync } from "child_process";
|
||||
import { homedir } from "os";
|
||||
import { exec } from "child_process";
|
||||
import { promisify } from "util";
|
||||
|
||||
export function getEnvPathFromUserShell(): string | undefined {
|
||||
const execAsync = promisify(exec);
|
||||
export async function getEnvPathFromUserShell(): Promise<string | undefined> {
|
||||
if (process.platform === "win32") {
|
||||
console.warn(`${getEnvPathFromUserShell.name} not implemented for Windows`);
|
||||
return undefined;
|
||||
|
|
@ -15,7 +16,7 @@ export function getEnvPathFromUserShell(): string | undefined {
|
|||
// Source common profile files
|
||||
const command = `${process.env.SHELL} -l -c 'for f in ~/.zprofile ~/.zshrc ~/.bash_profile ~/.bashrc; do [ -f "$f" ] && source "$f" 2>/dev/null; done; echo $PATH'`;
|
||||
|
||||
const stdout = execSync(command, {
|
||||
const { stdout } = await execAsync(command, {
|
||||
encoding: "utf8",
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -19,22 +19,3 @@ Model Context Protocol servers provide specialized functionality:
|
|||
## Learn More
|
||||
|
||||
Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
|
||||
description: Model Context Protocol servers provide specialized functionality
|
||||
keywords: [mcp, blocks, model context protocol, integrations, tools]
|
||||
sidebar_position: 4
|
||||
|
||||
---
|
||||
|
||||
Model Context Protocol servers provide specialized functionality:
|
||||
|
||||
- Enable integration with external tools and systems
|
||||
- Create extensible interfaces for custom capabilities
|
||||
- Support more complex interactions with your development environment
|
||||
- Allow partners to contribute specialized functionality
|
||||
- Database Connectors: Understand schema and data models during development
|
||||
|
||||

|
||||
|
||||
## Learn More
|
||||
|
||||
Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
|
||||
|
|
|
|||
|
|
@ -987,6 +987,33 @@ The response 200 OK should be a JSON object with the following structure:
|
|||
"description": "",
|
||||
"content": ""
|
||||
}
|
||||
|
||||
// For response context items with hyperlinks
|
||||
|
||||
[
|
||||
{
|
||||
"name": "",
|
||||
"description": "",
|
||||
"content": "",
|
||||
"uri": {
|
||||
"type": "file" or "url",
|
||||
"value": "file:///path/to/file" or "https://example.com",
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
// OR
|
||||
|
||||
{
|
||||
"name": "",
|
||||
"description": "",
|
||||
"content": "",
|
||||
"uri": {
|
||||
"type": "file" or "url",
|
||||
"value": "file:///path/to/file" or "https://example.com",
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### `@Commits`
|
||||
|
|
|
|||
|
|
@ -140,7 +140,7 @@ mcpServers:
|
|||
- "@modelcontextprotocol/server-sqlite"
|
||||
- "./database.db"
|
||||
cwd: "/path/to/project"
|
||||
|
||||
|
||||
- name: Local Project Server
|
||||
command: npm
|
||||
args:
|
||||
|
|
|
|||
|
|
@ -114,3 +114,33 @@ We recommend configuring **text-embedding-004** as your embeddings model.
|
|||
Vertex AI currently does not offer any reranking models.
|
||||
|
||||
[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
|
||||
|
||||
## Express mode
|
||||
|
||||
You can use VertexAI in [express mode](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview) by only providing an API Key. Only some Gemini models are supported in express mode for now.
|
||||
|
||||
<Tabs groupId="config-example">
|
||||
<TabItem value="yaml" label="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Gemini 2.5 Flash - VertexAI
|
||||
provider: vertexai
|
||||
model: gemini-2.5-flash
|
||||
apiKey: ${{ secrets.GOOGLE_CLOUD_API_KEY }}
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="json" label="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Gemini 2.5 Flash - VertexAI",
|
||||
"provider": "vertexai",
|
||||
"model": "gemini-2.5-flash",
|
||||
"apiKey": "[YOUR_GOOGLE_CLOUD_API_KEY]",
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
|
|
|||
3
docs/docs/features/agent/context-selection.mdx
Normal file
3
docs/docs/features/agent/context-selection.mdx
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
You can use the same methods to manually add context as [Chat](/features/chat/context-selection).
|
||||
|
||||
Tool call responses are automatically included as context items. This enables Agent mode to see the result of the previous action and decide what to do next.
|
||||
27
docs/docs/features/agent/how-to-customize.mdx
Normal file
27
docs/docs/features/agent/how-to-customize.mdx
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
## Add Rules Blocks
|
||||
|
||||
Adding Rules can be done in your assistant locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details.
|
||||
|
||||
## Add MCP Tools
|
||||
|
||||
You can add MCP servers to your assistant to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details.
|
||||
|
||||
## Tool Policies
|
||||
|
||||
You can adjust the Agent's tool usage behavior to three options:
|
||||
|
||||
- **Ask First (default)**: Request user permission with "Cancel" and "Continue" buttons
|
||||
- **Automatic**: Automatically call the tool without requesting permission
|
||||
- **Excluded**: Do not send the tool to the model
|
||||
|
||||
:::warning
|
||||
Be careful setting tools to "automatic" if their behavior is not read-only.
|
||||
:::
|
||||
|
||||
To manage tool policies:
|
||||
|
||||
1. Click the tools icon in the input toolbar
|
||||
2. View and change policies by clicking on the policy text
|
||||
3. You can also toggle groups of tools on/off
|
||||
|
||||
Tool policies are stored locally per user.
|
||||
14
docs/docs/features/agent/model-setup.mdx
Normal file
14
docs/docs/features/agent/model-setup.mdx
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
We recommend **Claude 3.5 Sonnet** from Anthropic for the best Agent experience.
|
||||
|
||||
- [Add Claude 3.5 Sonnet to your assistant from the hub](https://hub.continue.dev/anthropic/claude-3-5-sonnet-20241022)
|
||||
- Get your API key from the [Anthropic console](https://console.anthropic.com/)
|
||||
|
||||
## Other recommended models
|
||||
|
||||
- [Claude Sonnet 4 from Anthropic](https://hub.continue.dev/anthropic)
|
||||
- [GPT-4o from OpenAI](https://hub.continue.dev/openai/gpt-4o)
|
||||
- [Gemini 2.0 Pro from Google](https://hub.continue.dev/google/gemini-2.0-pro)
|
||||
|
||||
Agent can be used with models that support tool use through Continue. The best chat models generally support tool use.
|
||||
|
||||
For more information on models, check out [our recommended chat models](/features/chat/model-setup).
|
||||
19
docs/docs/features/autocomplete/context-selection.mdx
Normal file
19
docs/docs/features/autocomplete/context-selection.mdx
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
# Context Selection
|
||||
|
||||
Autocomplete will automatically determine context based on the current cursor position. We use the following techniques to determine what to include in the prompt:
|
||||
|
||||
## File prefix/suffix
|
||||
|
||||
We will always include the code from your file prior to and after the cursor position.
|
||||
|
||||
## Definitions from the Language Server Protocol
|
||||
|
||||
Similar to how you can use cmd/ctrl + click in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type.
|
||||
|
||||
## Imported files
|
||||
|
||||
Because there are often many imports, we can't include all of them. Instead, we look for symbols around your cursor that have matching imports and use that as context.
|
||||
|
||||
## Recent files
|
||||
|
||||
We automatically consider recently opened or edited files and include snippets that are relevant to the current completion.
|
||||
5
docs/docs/features/autocomplete/how-to-customize.mdx
Normal file
5
docs/docs/features/autocomplete/how-to-customize.mdx
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
# How to Customize Autocomplete
|
||||
|
||||
Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings.
|
||||
|
||||
For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete).
|
||||
29
docs/docs/features/autocomplete/model-setup.mdx
Normal file
29
docs/docs/features/autocomplete/model-setup.mdx
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
# Autocomplete Model Setup
|
||||
|
||||
Setting up the right model for autocomplete is crucial for a smooth coding experience. Here are our top recommendations:
|
||||
|
||||
## Recommended Models
|
||||
|
||||
### Hosted-Based (Best Performance)
|
||||
|
||||
For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral. This model is specifically designed for code completion and offers excellent performance across multiple programming languages.
|
||||
|
||||
**Quick Setup:**
|
||||
|
||||
1. [Add Codestral from the hub](https://hub.continue.dev/mistral/codestral)
|
||||
2. Get your API key from the [Mistral Platform](https://console.mistral.ai/codestral)
|
||||
3. Configure it in your Continue settings
|
||||
|
||||
### Local/Offline (Privacy First)
|
||||
|
||||
For a fully local autocomplete experience that doesn't send your code to external servers, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)** running on Ollama. This model provides good suggestions while keeping your code completely private.
|
||||
|
||||
**Quick Setup:**
|
||||
|
||||
1. Install [Ollama](https://ollama.ai/)
|
||||
2. [Add Qwen 2.5 Coder from the hub](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)
|
||||
3. Configure it in your Continue settings
|
||||
|
||||
## Need Help?
|
||||
|
||||
If you're not seeing any completions or need more detailed configuration options, check out our comprehensive [autocomplete deep dive guide](/customize/deep-dives/autocomplete).
|
||||
39
docs/docs/features/chat/context-selection.mdx
Normal file
39
docs/docs/features/chat/context-selection.mdx
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
## Input
|
||||
|
||||
Typing a question or instructions into the input box is the only required context.
|
||||
|
||||
## Highlighted Code
|
||||
|
||||
The highlighted code you've selected by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) will be included in your prompt.
|
||||
|
||||
## Active File
|
||||
|
||||
You can include the currently open file as context by pressing opt/alt + enter when you send your request.
|
||||
|
||||
## Specific File
|
||||
|
||||
You can include a specific file in your current workspace by typing '@Files' and selecting the file.
|
||||
|
||||
## Specific Folder
|
||||
|
||||
You can include a folder in your current workspace by typing '@Folder' and selecting the directory.
|
||||
|
||||
## Codebase Search
|
||||
|
||||
You can automatically include relevant files from your codebase by typing '@Codebase'.
|
||||
|
||||
## Documentation Site
|
||||
|
||||
You can include a documentation site as context by typing '@Docs' and selecting the site.
|
||||
|
||||
## Terminal Contents
|
||||
|
||||
You can include the contents of the terminal in your IDE by typing '@Terminal'.
|
||||
|
||||
## Git Diff
|
||||
|
||||
You can include all of the changes you've made to your current branch by typing '@Git Diff'.
|
||||
|
||||
## Other Context
|
||||
|
||||
You can see a full list of built-in context providers [here](/customize/custom-providers) and learn about how to create your own context provider [here](/guides/build-your-own-context-provider).
|
||||
7
docs/docs/features/chat/how-to-customize.mdx
Normal file
7
docs/docs/features/chat/how-to-customize.mdx
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
There are a number of different ways to customize Chat:
|
||||
|
||||
- Add a `rules` block to give the model persistent instructions through the system prompt
|
||||
- Configure `@Codebase`
|
||||
- Configure `@Docs`
|
||||
- [Build your own context provider](/guides/build-your-own-context-provider)
|
||||
- [Create a custom code RAG](/guides/custom-code-rag)
|
||||
19
docs/docs/features/chat/model-setup.mdx
Normal file
19
docs/docs/features/chat/model-setup.mdx
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
We recommend setting up a model for the best experience.
|
||||
|
||||
## Recommended Models
|
||||
|
||||
Here's our primary model recommendation:
|
||||
|
||||
**Claude 3.5 Sonnet** from Anthropic
|
||||
|
||||
- [Add Claude 3.5 Sonnet to your assistant from the hub](https://hub.continue.dev/anthropic/claude-3-5-sonnet-20241022)
|
||||
- Get your API key from the [Anthropic console](https://console.anthropic.com/)
|
||||
|
||||
Other top models to consider:
|
||||
|
||||
- [GPT-4o from OpenAI](https://hub.continue.dev/openai/gpt-4o)
|
||||
- [Grok-2 from xAI](https://hub.continue.dev/xai/grok-2)
|
||||
- [Gemini 2.0 Flash from Google](https://hub.continue.dev/google/gemini-2.0-flash)
|
||||
- [Llama 3.1 8b from Meta (local)](https://hub.continue.dev/ollama/llama3.1)
|
||||
|
||||
For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model).
|
||||
11
docs/docs/features/edit/context-selection.mdx
Normal file
11
docs/docs/features/edit/context-selection.mdx
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
## Input
|
||||
|
||||
The input you provide is included in the prompt.
|
||||
|
||||
## Code to Edit
|
||||
|
||||
The **entire contents** of each file (the current file for Jetbrains inline Edit, the `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.
|
||||
|
||||
## Context Providers
|
||||
|
||||
In VS Code Edit mode, you can use `@` to add context using [Context Providers](/customize/custom-providers), similar to [Chat](/features/chat/context-selection). Some context providers may be disabled in Edit mode.
|
||||
9
docs/docs/features/edit/how-to-customize.mdx
Normal file
9
docs/docs/features/edit/how-to-customize.mdx
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
## Setting active Edit/Apply model
|
||||
|
||||
You can configure particular models from your Assistant to be used for Edit and Apply requests.
|
||||
|
||||
1. Click the 3 dots above the main input
|
||||
2. Click the cube icon to expand the "Models" section
|
||||
3. Use the dropdowns to select models for Edit and Apply
|
||||
|
||||
Learn more about the [Edit role](/customize/model-roles/edit) and [Apply role](/customize/model-roles/apply).
|
||||
14
docs/docs/features/edit/model-setup.mdx
Normal file
14
docs/docs/features/edit/model-setup.mdx
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
By default, Edit uses the same model as Chat. We recommend **Claude 3.5 Sonnet** from Anthropic.
|
||||
|
||||
[Explore other Edit models on the Continue Hub →](https://hub.continue.dev)
|
||||
|
||||
## Apply Model
|
||||
|
||||
We also recommend setting up an Apply model for the best Edit experience.
|
||||
|
||||
**Recommended Apply models:**
|
||||
|
||||
- [Morph v0 Fast Apply](https://hub.continue.dev)
|
||||
- [Relace Instant Apply](https://hub.continue.dev)
|
||||
|
||||
[Explore other Apply models on the Continue Hub →](https://hub.continue.dev)
|
||||
|
|
@ -636,6 +636,18 @@ const config = {
|
|||
to: "/features/autocomplete/how-it-works",
|
||||
from: "/autocomplete/how-it-works",
|
||||
},
|
||||
{
|
||||
to: "/features/autocomplete/model-setup",
|
||||
from: "/autocomplete/model-setup",
|
||||
},
|
||||
{
|
||||
to: "/features/autocomplete/how-to-customize",
|
||||
from: "/autocomplete/how-to-customize",
|
||||
},
|
||||
{
|
||||
to: "/features/autocomplete/context-selection",
|
||||
from: "/autocomplete/context-selection",
|
||||
},
|
||||
{
|
||||
to: "/features/edit/how-it-works",
|
||||
from: "/edit/how-it-works",
|
||||
|
|
@ -656,6 +668,43 @@ const config = {
|
|||
to: "/customize/json-reference",
|
||||
from: ["/json-reference", "/advanced/json-reference"],
|
||||
},
|
||||
// New feature page redirects
|
||||
{
|
||||
to: "/features/chat/model-setup",
|
||||
from: "/chat/model-setup",
|
||||
},
|
||||
{
|
||||
to: "/features/chat/how-to-customize",
|
||||
from: "/chat/how-to-customize",
|
||||
},
|
||||
{
|
||||
to: "/features/chat/context-selection",
|
||||
from: "/chat/context-selection",
|
||||
},
|
||||
{
|
||||
to: "/features/edit/model-setup",
|
||||
from: "/edit/model-setup",
|
||||
},
|
||||
{
|
||||
to: "/features/edit/how-to-customize",
|
||||
from: "/edit/how-to-customize",
|
||||
},
|
||||
{
|
||||
to: "/features/edit/context-selection",
|
||||
from: "/edit/context-selection",
|
||||
},
|
||||
{
|
||||
to: "/features/agent/model-setup",
|
||||
from: "/agent/model-setup",
|
||||
},
|
||||
{
|
||||
to: "/features/agent/how-to-customize",
|
||||
from: "/agent/how-to-customize",
|
||||
},
|
||||
{
|
||||
to: "/features/agent/context-selection",
|
||||
from: "/agent/context-selection",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
|
|||
pluginName=continue-intellij-extension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
# SemVer format -> https://semver.org
|
||||
pluginVersion=1.0.27
|
||||
pluginVersion=1.0.28
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginSinceBuild=223
|
||||
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
|
||||
|
|
|
|||
|
|
@ -7,6 +7,12 @@ import com.intellij.openapi.actionSystem.PlatformDataKeys
|
|||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
|
||||
class RestartContinueProcess : AnAction() {
|
||||
override fun actionPerformed(e: AnActionEvent) {
|
||||
val pluginService = getContinuePluginService(e.project) ?: return
|
||||
pluginService.coreMessengerManager?.restart()
|
||||
}
|
||||
}
|
||||
|
||||
class AcceptDiffAction : AnAction() {
|
||||
override fun actionPerformed(e: AnActionEvent) {
|
||||
|
|
|
|||
|
|
@ -185,18 +185,17 @@ class AutocompleteService(private val project: Project) {
|
|||
return
|
||||
}
|
||||
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
WriteAction.run<Throwable> {
|
||||
// Clear existing completions
|
||||
hideCompletions(editor)
|
||||
invokeLater {
|
||||
// Clear existing completions
|
||||
hideCompletions(editor)
|
||||
|
||||
val properties = InlayProperties()
|
||||
properties.relatesToPrecedingText(true)
|
||||
properties.disableSoftWrapping(true)
|
||||
val properties = InlayProperties()
|
||||
properties.relatesToPrecedingText(true)
|
||||
properties.disableSoftWrapping(true)
|
||||
|
||||
val lines = completion.lines()
|
||||
pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n"))
|
||||
editor.addInlayElement(lines, offset, properties)
|
||||
val lines = completion.lines()
|
||||
pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n"))
|
||||
editor.addInlayElement(lines, offset, properties)
|
||||
|
||||
// val attributes = TextAttributes().apply {
|
||||
// backgroundColor = JBColor.GREEN
|
||||
|
|
@ -204,7 +203,6 @@ class AutocompleteService(private val project: Project) {
|
|||
// val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE")
|
||||
// key.let { editor.colorsScheme.setAttributes(it, attributes) }
|
||||
// editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package com.github.continuedev.continueintellijextension.constants
|
|||
|
||||
class MessageTypes {
|
||||
companion object {
|
||||
val ideMessageTypes = listOf(
|
||||
val IDE_MESSAGE_TYPES = listOf(
|
||||
"readRangeInFile",
|
||||
"isTelemetryEnabled",
|
||||
"getUniqueId",
|
||||
|
|
|
|||
|
|
@ -1,51 +1,40 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import com.github.continuedev.continueintellijextension.constants.MessageTypes
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueBinaryProcess
|
||||
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler
|
||||
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueSocketProcess
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.services.TelemetryService
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.google.gson.Gson
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.project.Project
|
||||
import java.io.*
|
||||
import java.net.Socket
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Paths
|
||||
import java.nio.file.attribute.PosixFilePermission
|
||||
import kotlinx.coroutines.*
|
||||
|
||||
class CoreMessenger(
|
||||
private val project: Project,
|
||||
continueCorePath: String,
|
||||
private val ideProtocolClient: IdeProtocolClient,
|
||||
val coroutineScope: CoroutineScope
|
||||
val coroutineScope: CoroutineScope,
|
||||
private val onExit: () -> Unit
|
||||
) {
|
||||
private var writer: Writer? = null
|
||||
private var reader: BufferedReader? = null
|
||||
private var process: Process? = null
|
||||
private val gson = Gson()
|
||||
private val responseListeners = mutableMapOf<String, (Any?) -> Unit>()
|
||||
private val useTcp: Boolean = System.getenv("USE_TCP")?.toBoolean() ?: false
|
||||
|
||||
private fun write(message: String) {
|
||||
try {
|
||||
writer?.write(message + "\r\n")
|
||||
writer?.flush()
|
||||
} catch (e: Exception) {
|
||||
println("Error writing to Continue core: $e")
|
||||
}
|
||||
}
|
||||
private val process = startContinueProcess()
|
||||
|
||||
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
|
||||
val id = messageId ?: uuid()
|
||||
val message =
|
||||
gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data))
|
||||
val message = gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data))
|
||||
responseListeners[id] = onResponse
|
||||
coroutineScope.launch(Dispatchers.IO) {
|
||||
write(message)
|
||||
}
|
||||
process.write(message)
|
||||
}
|
||||
|
||||
private fun startContinueProcess(): ContinueProcessHandler {
|
||||
val isTcp = System.getenv("USE_TCP")?.toBoolean() ?: false
|
||||
val process = if (isTcp)
|
||||
ContinueSocketProcess()
|
||||
else
|
||||
ContinueBinaryProcess(onExit)
|
||||
return ContinueProcessHandler(coroutineScope, process, ::handleMessage)
|
||||
}
|
||||
|
||||
private fun handleMessage(json: String) {
|
||||
|
|
@ -55,13 +44,10 @@ class CoreMessenger(
|
|||
val data = responseMap["data"]
|
||||
|
||||
// IDE listeners
|
||||
if (MessageTypes.ideMessageTypes.contains(messageType)) {
|
||||
if (MessageTypes.IDE_MESSAGE_TYPES.contains(messageType)) {
|
||||
ideProtocolClient.handleMessage(json) { data ->
|
||||
val message =
|
||||
gson.toJson(
|
||||
mapOf("messageId" to messageId, "messageType" to messageType, "data" to data)
|
||||
)
|
||||
write(message)
|
||||
val message = gson.toJson(mapOf("messageId" to messageId, "messageType" to messageType, "data" to data))
|
||||
process.write(message)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -82,148 +68,7 @@ class CoreMessenger(
|
|||
}
|
||||
}
|
||||
|
||||
private fun setPermissions(destination: String) {
|
||||
val osName = System.getProperty("os.name").toLowerCase()
|
||||
if (osName.contains("mac") || osName.contains("darwin")) {
|
||||
ProcessBuilder("xattr", "-dr", "com.apple.quarantine", destination).start().waitFor()
|
||||
setFilePermissions(destination, "rwxr-xr-x")
|
||||
} else if (osName.contains("nix") || osName.contains("nux")) {
|
||||
setFilePermissions(destination, "rwxr-xr-x")
|
||||
}
|
||||
}
|
||||
|
||||
private fun setFilePermissions(path: String, posixPermissions: String) {
|
||||
val perms = HashSet<PosixFilePermission>()
|
||||
if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ)
|
||||
if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE)
|
||||
if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE)
|
||||
Files.setPosixFilePermissions(Paths.get(path), perms)
|
||||
}
|
||||
|
||||
private val exitCallbacks: MutableList<() -> Unit> = mutableListOf()
|
||||
|
||||
fun onDidExit(callback: () -> Unit) {
|
||||
exitCallbacks.add(callback)
|
||||
}
|
||||
|
||||
init {
|
||||
if (useTcp) {
|
||||
try {
|
||||
val socket = Socket("127.0.0.1", 3000)
|
||||
val writer = PrintWriter(socket.getOutputStream(), true)
|
||||
this.writer = writer
|
||||
val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
|
||||
this.reader = reader
|
||||
|
||||
Thread {
|
||||
try {
|
||||
while (true) {
|
||||
val line = reader.readLine()
|
||||
if (line != null && line.isNotEmpty()) {
|
||||
try {
|
||||
handleMessage(line)
|
||||
} catch (e: Exception) {
|
||||
println("Error handling message: $line")
|
||||
println(e)
|
||||
}
|
||||
} else {
|
||||
Thread.sleep(100)
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
} finally {
|
||||
try {
|
||||
reader.close()
|
||||
writer.close()
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
.start()
|
||||
} catch (e: Exception) {
|
||||
println("TCP Connection Error: Unable to connect to 127.0.0.1:3000")
|
||||
println("Reason: ${e.message}")
|
||||
e.printStackTrace()
|
||||
}
|
||||
} else {
|
||||
// Set proper permissions synchronously
|
||||
runBlocking(Dispatchers.IO) {
|
||||
setPermissions(continueCorePath)
|
||||
}
|
||||
|
||||
// Start the subprocess
|
||||
val processBuilder =
|
||||
ProcessBuilder(continueCorePath).directory(File(continueCorePath).parentFile)
|
||||
process = processBuilder.start()
|
||||
|
||||
val outputStream = process!!.outputStream
|
||||
val inputStream = process!!.inputStream
|
||||
|
||||
writer = OutputStreamWriter(outputStream, StandardCharsets.UTF_8)
|
||||
reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))
|
||||
|
||||
process!!.onExit().thenRun {
|
||||
exitCallbacks.forEach { it() }
|
||||
var err = process?.errorStream?.bufferedReader()?.readText()?.trim()
|
||||
if (err != null) {
|
||||
// There are often "⚡️Done in Xms" messages, and we want everything after the last one
|
||||
val delimiter = "⚡ Done in"
|
||||
val doneIndex = err.lastIndexOf(delimiter)
|
||||
if (doneIndex != -1) {
|
||||
err = err.substring(doneIndex + delimiter.length)
|
||||
}
|
||||
}
|
||||
|
||||
println("Core process exited with output: $err")
|
||||
|
||||
// Log the cause of the failure
|
||||
val telemetryService = service<TelemetryService>()
|
||||
telemetryService.capture("jetbrains_core_exit", mapOf("error" to err))
|
||||
|
||||
// Clean up all resources
|
||||
writer?.close()
|
||||
reader?.close()
|
||||
process?.destroy()
|
||||
}
|
||||
|
||||
coroutineScope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
while (true) {
|
||||
val line = reader?.readLine()
|
||||
if (line != null && line.isNotEmpty()) {
|
||||
try {
|
||||
handleMessage(line)
|
||||
} catch (e: Exception) {
|
||||
println("Error handling message: $line")
|
||||
println(e)
|
||||
}
|
||||
} else {
|
||||
delay(100)
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
} finally {
|
||||
try {
|
||||
reader?.close()
|
||||
writer?.close()
|
||||
outputStream.close()
|
||||
inputStream.close()
|
||||
process?.destroy()
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun killSubProcess() {
|
||||
process?.isAlive?.let {
|
||||
exitCallbacks.clear()
|
||||
process?.destroy()
|
||||
}
|
||||
process.close()
|
||||
}
|
||||
}
|
||||
|
|
@ -2,53 +2,50 @@ package com.github.continuedev.continueintellijextension.`continue`
|
|||
|
||||
import com.github.continuedev.continueintellijextension.services.TelemetryService
|
||||
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
||||
import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
|
||||
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.diagnostic.Logger
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class CoreMessengerManager(
|
||||
private val project: Project,
|
||||
private val ideProtocolClient: IdeProtocolClient,
|
||||
private val coroutineScope: CoroutineScope
|
||||
) {
|
||||
|
||||
var coreMessenger: CoreMessenger? = null
|
||||
var coreMessenger: CoreMessenger = createCoreMessenger()
|
||||
private var lastBackoffInterval = 0.5
|
||||
private val log = Logger.getInstance(CoreMessengerManager::class.java)
|
||||
|
||||
init {
|
||||
setupAnonymousTelemetry()
|
||||
}
|
||||
|
||||
fun restart() {
|
||||
coroutineScope.launch {
|
||||
val continueBinaryPath = getContinueBinaryPath()
|
||||
setupCoreMessenger(continueBinaryPath)
|
||||
try {
|
||||
coreMessenger.killSubProcess()
|
||||
lastBackoffInterval *= 2
|
||||
log.warn("Continue process exited, retrying in $lastBackoffInterval seconds")
|
||||
delay((lastBackoffInterval * 1000).toLong())
|
||||
coreMessenger = createCoreMessenger()
|
||||
} catch (e: Exception) {
|
||||
service<TelemetryService>().capture("jetbrains_core_start_error", mapOf("error" to e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun setupCoreMessenger(continueCorePath: String) {
|
||||
try {
|
||||
coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope)
|
||||
private fun createCoreMessenger() =
|
||||
CoreMessenger(project, ideProtocolClient, coroutineScope, ::restart)
|
||||
|
||||
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val allowAnonymousTelemetry = response.castNestedOrNull<Boolean>("content", "result", "config", "allowAnonymousTelemetry")
|
||||
|
||||
val telemetryService = service<TelemetryService>()
|
||||
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
|
||||
telemetryService.setup(getMachineUniqueID())
|
||||
}
|
||||
}
|
||||
|
||||
// On exit, use exponential backoff to create another CoreMessenger
|
||||
coreMessenger?.onDidExit {
|
||||
lastBackoffInterval *= 2
|
||||
println("CoreMessenger exited, retrying in $lastBackoffInterval seconds")
|
||||
Thread.sleep((lastBackoffInterval * 1000).toLong())
|
||||
setupCoreMessenger(continueCorePath)
|
||||
}
|
||||
} catch (err: Throwable) {
|
||||
val telemetryService = service<TelemetryService>()
|
||||
telemetryService.capture("jetbrains_core_start_error", mapOf("error" to err))
|
||||
|
||||
err.printStackTrace()
|
||||
private fun setupAnonymousTelemetry() {
|
||||
coreMessenger.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val allowAnonymousTelemetry =
|
||||
response.castNestedOrNull<Boolean>("content", "result", "config", "allowAnonymousTelemetry")
|
||||
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null)
|
||||
service<TelemetryService>().setup(getMachineUniqueID())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -495,7 +495,7 @@ class IntelliJIDE(
|
|||
|
||||
// Create the list of IndexTag objects
|
||||
return workspaceDirs.mapIndexed { index, directory ->
|
||||
IndexTag(directory, branches[index], artifactId)
|
||||
IndexTag(artifactId, branches[index], directory)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -622,4 +622,5 @@ class IntelliJIDE(
|
|||
return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray()
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,81 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`.process
|
||||
|
||||
import com.github.continuedev.continueintellijextension.services.TelemetryService
|
||||
import com.github.continuedev.continueintellijextension.utils.OS
|
||||
import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
|
||||
import com.github.continuedev.continueintellijextension.utils.getOS
|
||||
import com.intellij.openapi.components.service
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Paths
|
||||
import java.nio.file.attribute.PosixFilePermission
|
||||
|
||||
class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
|
||||
|
||||
private val process = startBinaryProcess()
|
||||
override val input: InputStream = process.inputStream
|
||||
override val output: OutputStream = process.outputStream
|
||||
|
||||
override fun close() =
|
||||
process.destroy()
|
||||
|
||||
private fun startBinaryProcess(): Process {
|
||||
val path = getContinueBinaryPath()
|
||||
runBlocking(Dispatchers.IO) {
|
||||
setPermissions()
|
||||
}
|
||||
return ProcessBuilder(path).directory(File(path).parentFile)
|
||||
.start()
|
||||
.apply { onExit().thenRun(onExit).thenRun { reportErrorTelemetry() } }
|
||||
}
|
||||
|
||||
|
||||
private fun reportErrorTelemetry() {
|
||||
var err = process.errorStream?.bufferedReader()?.readText()?.trim()
|
||||
if (err != null) {
|
||||
// There are often "⚡️Done in Xms" messages, and we want everything after the last one
|
||||
val delimiter = "⚡ Done in"
|
||||
val doneIndex = err.lastIndexOf(delimiter)
|
||||
if (doneIndex != -1) {
|
||||
err = err.substring(doneIndex + delimiter.length)
|
||||
}
|
||||
}
|
||||
|
||||
println("Core process exited with output: $err")
|
||||
|
||||
val telemetryService = service<TelemetryService>()
|
||||
telemetryService.capture("jetbrains_core_exit", mapOf("error" to err))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
private fun setPermissions() {
|
||||
val os = getOS()
|
||||
when (os) {
|
||||
OS.MAC -> setMacOsPermissions()
|
||||
OS.WINDOWS -> {}
|
||||
OS.LINUX -> elevatePermissions()
|
||||
}
|
||||
}
|
||||
|
||||
private fun setMacOsPermissions() {
|
||||
ProcessBuilder("xattr", "-dr", "com.apple.quarantine", getContinueBinaryPath()).start().waitFor()
|
||||
elevatePermissions()
|
||||
}
|
||||
|
||||
private fun elevatePermissions() {
|
||||
val path = getContinueBinaryPath()
|
||||
val permissions = setOf(
|
||||
PosixFilePermission.OWNER_READ,
|
||||
PosixFilePermission.OWNER_WRITE,
|
||||
PosixFilePermission.OWNER_EXECUTE
|
||||
)
|
||||
Files.setPosixFilePermissions(Paths.get(path), permissions)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`.process
|
||||
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
|
||||
interface ContinueProcess {
|
||||
|
||||
val input: InputStream
|
||||
val output: OutputStream
|
||||
|
||||
fun close()
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`.process
|
||||
|
||||
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
|
||||
import com.intellij.openapi.components.service
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import java.io.BufferedReader
|
||||
import java.io.IOException
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
|
||||
class ContinueProcessHandler(
|
||||
parentScope: CoroutineScope,
|
||||
private val process: ContinueProcess,
|
||||
handleMessage: (String) -> (Unit)
|
||||
) {
|
||||
private val innerJob = Job()
|
||||
private val scope = CoroutineScope(parentScope.coroutineContext + innerJob)
|
||||
private val pendingWrites = Channel<String>(Channel.UNLIMITED)
|
||||
private val writer = OutputStreamWriter(process.output)
|
||||
private val reader = BufferedReader(InputStreamReader(process.input))
|
||||
|
||||
init {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
while (isActive) {
|
||||
val line = reader.readLine()
|
||||
if (line != null && line.isNotEmpty()) {
|
||||
try {
|
||||
handleMessage(line)
|
||||
} catch (e: Exception) {
|
||||
service<ContinueErrorService>().report(e, "Error handling message: $line")
|
||||
}
|
||||
} else
|
||||
delay(100)
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
service<ContinueErrorService>().report(e)
|
||||
}
|
||||
}
|
||||
scope.launch(Dispatchers.IO) {
|
||||
for (message in pendingWrites) {
|
||||
writer.write(message)
|
||||
writer.write("\r\n")
|
||||
writer.flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun write(message: String) =
|
||||
pendingWrites.trySend(message)
|
||||
|
||||
fun close() {
|
||||
innerJob.cancel()
|
||||
scope.launch(Dispatchers.IO) {
|
||||
reader.close()
|
||||
writer.close()
|
||||
process.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`.process
|
||||
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.net.Socket
|
||||
|
||||
class ContinueSocketProcess : ContinueProcess {
|
||||
|
||||
private val socket = Socket("127.0.0.1", 3000)
|
||||
override val input: InputStream = socket.inputStream
|
||||
override val output: OutputStream = socket.outputStream
|
||||
|
||||
override fun close() =
|
||||
socket.close()
|
||||
|
||||
}
|
||||
|
|
@ -70,6 +70,13 @@
|
|||
<override-text place="GoToAction" text="Continue: Accept Diff"/>
|
||||
</action>
|
||||
|
||||
<action id="continue.restartProcess"
|
||||
class="com.github.continuedev.continueintellijextension.actions.RestartContinueProcess"
|
||||
text="Restart Process"
|
||||
description="Restart Process">
|
||||
<override-text place="GoToAction" text="Continue: Restart Process"/>
|
||||
</action>
|
||||
|
||||
<action id="continue.rejectDiff"
|
||||
class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction"
|
||||
text="Reject Diff" description="Reject Diff">
|
||||
|
|
|
|||
|
|
@ -0,0 +1,51 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcess
|
||||
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.joinAll
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.Assertions
|
||||
import org.junit.jupiter.api.RepeatedTest
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
|
||||
class ContinueProcessHandlerTest {
|
||||
|
||||
@RepeatedTest(5)
|
||||
fun `test concurrent writes with queue`() = runTest {
|
||||
val process = StringContinueProcess()
|
||||
val handler = ContinueProcessHandler(this, process) {}
|
||||
|
||||
(0..100).map { i -> launch(Dispatchers.Default) { handler.write("message number $i") } }
|
||||
.joinAll()
|
||||
|
||||
handler.close()
|
||||
|
||||
// assert all message lines are present (order is not important)
|
||||
val lines = process.string.split("\r\n").filter { it.isNotBlank() }
|
||||
for (i in 0..100)
|
||||
Assertions.assertTrue(lines.contains("message number $i"))
|
||||
|
||||
// note: this test will fail if the handler writes messages directly to the output stream
|
||||
// this problem can be easily reproduced by removing the channel<string> from the handler code
|
||||
}
|
||||
|
||||
class StringContinueProcess : ContinueProcess {
|
||||
val string = StringBuilder()
|
||||
override val input: InputStream = InputStream.nullInputStream()
|
||||
override val output: OutputStream = object : OutputStream() {
|
||||
override fun write(b: Int) {
|
||||
string.append(b.toChar())
|
||||
}
|
||||
|
||||
override fun write(b: ByteArray, off: Int, len: Int) {
|
||||
string.append(String(b, off, len))
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -357,20 +357,6 @@ describe("GUI Test", () => {
|
|||
await messageInput.sendKeys(Key.ENTER);
|
||||
await messageInput.sendKeys(Key.ENTER);
|
||||
|
||||
// Open the context items peek
|
||||
const contextItemsPeek = await GUISelectors.getContextItemsPeek(view);
|
||||
await contextItemsPeek.click();
|
||||
|
||||
await TestUtils.waitForSuccess(async () => {
|
||||
const firstContextItemInPeek =
|
||||
await GUISelectors.getFirstContextItemsPeekItem(view);
|
||||
await firstContextItemInPeek.click();
|
||||
|
||||
// Check that item is there with correct name
|
||||
const description = await firstContextItemInPeek.getText();
|
||||
expect(description).to.include("Terminal");
|
||||
});
|
||||
|
||||
// Check that the contents match what we expect (repeated back by the mock LLM)
|
||||
await TestUtils.waitForSuccess(() => {
|
||||
return GUISelectors.getThreadMessageByText(
|
||||
|
|
|
|||
6
extensions/vscode/package-lock.json
generated
6
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "1.1.55",
|
||||
"version": "1.1.59",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "1.1.55",
|
||||
"version": "1.1.59",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
@ -173,6 +173,8 @@
|
|||
"@babel/preset-env": "^7.24.7",
|
||||
"@biomejs/biome": "1.6.4",
|
||||
"@google/generative-ai": "^0.11.4",
|
||||
"@shikijs/colorized-brackets": "^3.7.0",
|
||||
"@shikijs/transformers": "^3.7.0",
|
||||
"@types/diff": "^7.0.1",
|
||||
"@types/follow-redirects": "^1.14.4",
|
||||
"@types/jest": "^29.5.12",
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.1.57",
|
||||
"version": "1.1.60",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ const PLATFORMS = [
|
|||
const args = process.argv.slice(2);
|
||||
const isPreRelease = args.includes("--pre-release");
|
||||
|
||||
(async () => {
|
||||
void (async () => {
|
||||
for (const i in PLATFORMS) {
|
||||
const platform = PLATFORMS[i];
|
||||
const pkgCommand = isPreRelease
|
||||
|
|
@ -23,4 +23,5 @@ const isPreRelease = args.includes("--pre-release");
|
|||
});
|
||||
execSync(pkgCommand, { stdio: "inherit" });
|
||||
}
|
||||
process.exit(0);
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -6,14 +6,17 @@
|
|||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const { rimrafSync } = require("rimraf");
|
||||
|
||||
const {
|
||||
validateFilesPresent,
|
||||
autodetectPlatformAndArch,
|
||||
} = require("../../../scripts/util/index");
|
||||
|
||||
const { generateAndCopyConfigYamlSchema } = require("./generate-copy-config");
|
||||
const { npmInstall } = require("./npm-install");
|
||||
const {
|
||||
copyConfigSchema,
|
||||
installNodeModules,
|
||||
buildGui,
|
||||
copyOnnxRuntimeFromNodeModules,
|
||||
copyTreeSitterWasms,
|
||||
|
|
@ -48,10 +51,10 @@ if (args[2] === "--target") {
|
|||
|
||||
let os;
|
||||
let arch;
|
||||
if (!target) {
|
||||
[os, arch] = autodetectPlatformAndArch();
|
||||
} else {
|
||||
if (target) {
|
||||
[os, arch] = target.split("-");
|
||||
} else {
|
||||
[os, arch] = autodetectPlatformAndArch();
|
||||
}
|
||||
|
||||
if (os === "alpine") {
|
||||
|
|
@ -71,26 +74,14 @@ function ghAction() {
|
|||
return !!process.env.GITHUB_ACTIONS;
|
||||
}
|
||||
|
||||
function isArm() {
|
||||
return (
|
||||
target === "darwin-arm64" ||
|
||||
target === "linux-arm64" ||
|
||||
target === "win32-arm64"
|
||||
);
|
||||
}
|
||||
|
||||
function isWin() {
|
||||
return target?.startsWith("win");
|
||||
}
|
||||
|
||||
async function package(target, os, arch, exe) {
|
||||
console.log("[info] Packaging extension for target ", target);
|
||||
|
||||
// Copy config_schema to intellij
|
||||
copyConfigSchema();
|
||||
await generateAndCopyConfigYamlSchema();
|
||||
|
||||
// Install node_modules
|
||||
installNodeModules();
|
||||
await npmInstall();
|
||||
|
||||
// Build gui and copy to extensions
|
||||
await buildGui(ghAction());
|
||||
|
|
@ -214,4 +205,5 @@ async function package(target, os, arch, exe) {
|
|||
|
||||
void (async () => {
|
||||
await package(target, os, arch, exe);
|
||||
process.exit(0);
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -174,9 +174,12 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
// Clear deletion buffer
|
||||
await this.insertDeletionBuffer();
|
||||
|
||||
await this.reapplyWithMyersDiff(diffLines);
|
||||
const myersDiffs = await this.reapplyWithMyersDiff(diffLines);
|
||||
|
||||
const range = new vscode.Range(this.startLine, 0, this.startLine, 0);
|
||||
// Scroll to the first diff
|
||||
const scrollToLine =
|
||||
this.getFirstChangedLine(myersDiffs) ?? this.startLine;
|
||||
const range = new vscode.Range(scrollToLine, 0, scrollToLine, 0);
|
||||
this.editor.revealRange(range, vscode.TextEditorRevealType.Default);
|
||||
|
||||
this.options.onStatusUpdate(
|
||||
|
|
@ -370,6 +373,8 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
|
||||
this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks);
|
||||
this.refreshCodeLens();
|
||||
|
||||
return myersDiffs;
|
||||
}
|
||||
|
||||
private async insertDeletionBuffer() {
|
||||
|
|
@ -550,4 +555,17 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
|
||||
this.refreshCodeLens();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the first line number that was changed in a diff
|
||||
*/
|
||||
private getFirstChangedLine(diff: DiffLine[]): number | null {
|
||||
for (let i = 0; i < diff.length; i++) {
|
||||
const item = diff[i];
|
||||
if (item.type === "old" || item.type === "new") {
|
||||
return this.startLine + i;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -77,6 +77,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
|
|||
{ promise: Promise<string>; cancel: EventEmitter<void> }
|
||||
>();
|
||||
private _refreshInterval: NodeJS.Timeout | null = null;
|
||||
private _isRefreshing = false;
|
||||
|
||||
private static EXPIRATION_TIME_MS = 1000 * 60 * 15; // 15 minutes
|
||||
private static REFRESH_INTERVAL_MS = 1000 * 60 * 10; // 10 minutes
|
||||
|
|
@ -100,11 +101,11 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
|
|||
this.secretStorage = new SecretStorage(context);
|
||||
|
||||
// Immediately refresh any existing sessions
|
||||
this.refreshSessions();
|
||||
void this.refreshSessions();
|
||||
|
||||
// Set up a regular interval to refresh tokens
|
||||
this._refreshInterval = setInterval(() => {
|
||||
this.refreshSessions();
|
||||
void this.refreshSessions();
|
||||
}, WorkOsAuthProvider.REFRESH_INTERVAL_MS);
|
||||
}
|
||||
|
||||
|
|
@ -182,10 +183,18 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
|
|||
}
|
||||
|
||||
async refreshSessions() {
|
||||
// Prevent concurrent refresh operations
|
||||
if (this._isRefreshing) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this._isRefreshing = true;
|
||||
await this._refreshSessions();
|
||||
} catch (e) {
|
||||
console.error(`Error refreshing sessions: ${e}`);
|
||||
} finally {
|
||||
this._isRefreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -198,12 +207,9 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
|
|||
const finalSessions = [];
|
||||
for (const session of sessions) {
|
||||
try {
|
||||
// For expired tokens, don't use retries - if refresh fails, we drop the session
|
||||
const refreshMethod = this.jwtIsExpiredOrInvalid(session.accessToken)
|
||||
? this._refreshSession.bind(this) // Direct refresh for expired tokens
|
||||
: this._refreshSessionWithRetry.bind(this); // Retry for valid tokens
|
||||
|
||||
const newSession = await refreshMethod(session.refreshToken);
|
||||
const newSession = await this._refreshSessionWithRetry(
|
||||
session.refreshToken,
|
||||
);
|
||||
finalSessions.push({
|
||||
...session,
|
||||
accessToken: newSession.accessToken,
|
||||
|
|
@ -232,7 +238,6 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
|
|||
private async _refreshSessionWithRetry(
|
||||
refreshToken: string,
|
||||
attempt = 1,
|
||||
maxAttempts = 3,
|
||||
baseDelay = 1000,
|
||||
): Promise<{
|
||||
accessToken: string;
|
||||
|
|
@ -242,30 +247,25 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
|
|||
try {
|
||||
return await this._refreshSession(refreshToken);
|
||||
} catch (error: any) {
|
||||
// Don't retry for auth errors (401 Unauthorized) or if we've reached max attempts
|
||||
// Don't retry for auth errors
|
||||
if (
|
||||
error.message?.includes("401") ||
|
||||
error.message?.includes("Invalid refresh token") ||
|
||||
error.message?.includes("Unauthorized") ||
|
||||
attempt >= maxAttempts
|
||||
error.message?.includes("Unauthorized")
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// For network errors or transient server issues, retry with backoff
|
||||
// Calculate exponential backoff delay with jitter
|
||||
const delay =
|
||||
baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5);
|
||||
const delay = Math.min(
|
||||
baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5),
|
||||
2 * 60 * 1000, // 2 minutes
|
||||
);
|
||||
|
||||
// Schedule retry after delay
|
||||
return new Promise((resolve, reject) => {
|
||||
setTimeout(() => {
|
||||
this._refreshSessionWithRetry(
|
||||
refreshToken,
|
||||
attempt + 1,
|
||||
maxAttempts,
|
||||
baseDelay,
|
||||
)
|
||||
this._refreshSessionWithRetry(refreshToken, attempt + 1, baseDelay)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
}, delay);
|
||||
|
|
@ -360,7 +360,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
|
|||
|
||||
return session;
|
||||
} catch (e) {
|
||||
window.showErrorMessage(`Sign in failed: ${e}`);
|
||||
void window.showErrorMessage(`Sign in failed: ${e}`);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -641,7 +641,7 @@ it("should preserve valid tokens during network errors by retrying", async () =>
|
|||
}
|
||||
});
|
||||
|
||||
it("should remove expired tokens when refresh fails", async () => {
|
||||
it("should remove expired tokens when refresh fails with a 401 error", async () => {
|
||||
// Mock Date.now to return a time that makes tokens appear expired
|
||||
const originalDateNow = Date.now;
|
||||
const futureTime = Date.now() + 7200000; // 2 hours in the future
|
||||
|
|
@ -675,7 +675,7 @@ it("should remove expired tokens when refresh fails", async () => {
|
|||
global.setInterval = vi.fn().mockReturnValue(123 as any);
|
||||
|
||||
// Refresh will fail with network error
|
||||
fetchMock.mockRejectedValueOnce(new Error("Network error"));
|
||||
fetchMock.mockRejectedValueOnce(new Error("401"));
|
||||
|
||||
// Setup storage
|
||||
mockSecretStorageGet.mockResolvedValue(JSON.stringify([expiredSession]));
|
||||
|
|
|
|||
|
|
@ -3,6 +3,9 @@ import { AutocompleteCodeSnippet } from "core/autocomplete/snippets/types";
|
|||
import { GetLspDefinitionsFunction } from "core/autocomplete/types";
|
||||
import { ConfigHandler } from "core/config/ConfigHandler";
|
||||
import { RecentlyEditedRange } from "core/nextEdit/types";
|
||||
import { getContinueGlobalPath, isFileWithinFolder } from "core/util/paths";
|
||||
import fs from "fs";
|
||||
import { resolve } from "path";
|
||||
import * as vscode from "vscode";
|
||||
import { ContinueCompletionProvider } from "../autocomplete/completionProvider";
|
||||
|
||||
|
|
@ -18,23 +21,33 @@ export const getBeforeCursorPos = (range: Range, activePos: Position) => {
|
|||
}
|
||||
};
|
||||
|
||||
const getWorkspaceDirInfo = async (
|
||||
event: vscode.TextDocumentChangeEvent,
|
||||
ide: IDE,
|
||||
) => {
|
||||
// gets the workspace dir uri and checks if it's the open-source continue repo
|
||||
const isEditLoggingAllowed = async (editedFileURI: string) => {
|
||||
const globalContinuePath = getContinueGlobalPath();
|
||||
const editLogDirsPath = resolve(globalContinuePath, ".editlogdirs");
|
||||
|
||||
try {
|
||||
const fileContent = await fs.promises.readFile(editLogDirsPath, "utf-8");
|
||||
const stringItems = fileContent
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
|
||||
return stringItems.some((dir) => isFileWithinFolder(editedFileURI, dir));
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const getWorkspaceDirUri = async (event: vscode.TextDocumentChangeEvent) => {
|
||||
const workspaceFolder = vscode.workspace.getWorkspaceFolder(
|
||||
event.document.uri,
|
||||
);
|
||||
if (!workspaceFolder) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const workspaceDirUri = workspaceFolder.uri.toString();
|
||||
const repoName = await ide.getRepoName(workspaceDirUri);
|
||||
return {
|
||||
workspaceDirUri: workspaceDirUri,
|
||||
isContinueRepo: repoName === "continuedev/continue",
|
||||
};
|
||||
return workspaceDirUri;
|
||||
};
|
||||
|
||||
export const handleTextDocumentChange = async (
|
||||
|
|
@ -52,10 +65,10 @@ export const handleTextDocumentChange = async (
|
|||
if (!editor) return;
|
||||
if (event.contentChanges.length === 0) return;
|
||||
|
||||
// Ensure that loggin will only happen in the open-source continue repo
|
||||
const workspaceDirInfo = await getWorkspaceDirInfo(event, ide);
|
||||
if (!workspaceDirInfo) return;
|
||||
// if (!workspaceDirInfo.isContinueRepo) return;
|
||||
// Ensure that logging will only happen in the open-source continue repo
|
||||
const workspaceDirUri = await getWorkspaceDirUri(event);
|
||||
if (!workspaceDirUri) return;
|
||||
if (!(await isEditLoggingAllowed(event.document.uri.toString()))) return;
|
||||
|
||||
const activeCursorPos = editor.selection.active;
|
||||
const editActions: RangeInFileWithNextEditInfo[] = changes.map((change) => ({
|
||||
|
|
@ -68,7 +81,7 @@ export const handleTextDocumentChange = async (
|
|||
editText: change.text,
|
||||
beforeCursorPos: getBeforeCursorPos(change.range, activeCursorPos),
|
||||
afterCursorPos: activeCursorPos as Position,
|
||||
workspaceDir: workspaceDirInfo.workspaceDirUri,
|
||||
workspaceDir: workspaceDirUri,
|
||||
}));
|
||||
|
||||
let recentlyEditedRanges: RecentlyEditedRange[] = [];
|
||||
|
|
|
|||
1310
gui/package-lock.json
generated
1310
gui/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -19,6 +19,7 @@
|
|||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@headlessui/react": "^2.2.0",
|
||||
"@heroicons/react": "^2.0.18",
|
||||
"@panzoom/panzoom": "^4.6.0",
|
||||
"@reduxjs/toolkit": "^2.3.0",
|
||||
"@tiptap/core": "^2.3.2",
|
||||
"@tiptap/extension-document": "^2.3.2",
|
||||
|
|
@ -43,6 +44,7 @@
|
|||
"handlebars": "^4.7.8",
|
||||
"lodash": "^4.17.21",
|
||||
"lowlight": "^3.3.0",
|
||||
"mermaid": "^11.6.0",
|
||||
"minisearch": "^7.0.2",
|
||||
"mustache": "^4.2.0",
|
||||
"posthog-js": "^1.130.1",
|
||||
|
|
|
|||
Binary file not shown.
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 12 KiB |
177
gui/src/components/StyledMarkdownPreview/MermaidBlock.tsx
Normal file
177
gui/src/components/StyledMarkdownPreview/MermaidBlock.tsx
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
import {
|
||||
ArrowPathRoundedSquareIcon,
|
||||
MagnifyingGlassMinusIcon,
|
||||
MagnifyingGlassPlusIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
// @ts-ignore
|
||||
import Panzoom from "@panzoom/panzoom";
|
||||
// @ts-ignore
|
||||
import mermaid from "mermaid";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { useDebouncedEffect } from "../find/useDebounce";
|
||||
import { ToolTip } from "../gui/Tooltip";
|
||||
|
||||
const MINIMUM_ZOOM_STEP = 0.05;
|
||||
|
||||
const MERMAID_THEME_COLORS = {
|
||||
background: "#1e1e1e",
|
||||
primaryColor: "#4d8bf0",
|
||||
primaryTextColor: "#ffffff",
|
||||
primaryBorderColor: "#4d8bf0",
|
||||
secondaryColor: "#3a6db3",
|
||||
secondaryTextColor: "#ffffff",
|
||||
secondaryBorderColor: "#3a6db3",
|
||||
tertiaryColor: "#59bc89",
|
||||
tertiaryTextColor: "#ffffff",
|
||||
tertiaryBorderColor: "#59bc89",
|
||||
noteBkgColor: "#2d2d2d",
|
||||
noteTextColor: "#e6e6e6",
|
||||
noteBorderColor: "#555555",
|
||||
lineColor: "#8c8c8c",
|
||||
textColor: "#e6e6e6",
|
||||
mainBkg: "#252525",
|
||||
errorBkgColor: "#f44336",
|
||||
errorTextColor: "#ffffff",
|
||||
nodeBorder: "#555555",
|
||||
clusterBkg: "#2a2a2a",
|
||||
clusterBorder: "#555555",
|
||||
defaultLinkColor: "#8c8c8c",
|
||||
titleColor: "#e6e6e6",
|
||||
edgeLabelBackground: "#252525",
|
||||
activeTaskBkgColor: "#4caf50",
|
||||
activeTaskBorderColor: "#388e3c",
|
||||
doneTaskBkgColor: "#388e3c",
|
||||
doneTaskBorderColor: "#2e7d32",
|
||||
critBkgColor: "#f44336",
|
||||
critBorderColor: "#d32f2f",
|
||||
taskTextColor: "#e6e6e6",
|
||||
taskTextOutsideColor: "#e6e6e6",
|
||||
taskTextLightColor: "#b3b3b3",
|
||||
sectionBkgColor: "#2a2a2a",
|
||||
altSectionBkgColor: "#303030",
|
||||
sectionBkgColor2: "#252525",
|
||||
excludeBkgColor: "#2d2d2d",
|
||||
fillType0: "#264f78",
|
||||
fillType1: "#3a6db3",
|
||||
fillType2: "#59bc89",
|
||||
fillType3: "#4d8bf0",
|
||||
fillType4: "#3a6db3",
|
||||
fillType5: "#264f78",
|
||||
fillType6: "#59bc89",
|
||||
fillType7: "#4d8bf0",
|
||||
};
|
||||
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: "loose",
|
||||
theme: "dark",
|
||||
themeVariables: {
|
||||
...MERMAID_THEME_COLORS,
|
||||
fontSize: "14px",
|
||||
fontFamily: "var(--vscode-font-family)",
|
||||
},
|
||||
});
|
||||
|
||||
export default function MermaidDiagram({ code }: { code: string }) {
|
||||
const mermaidRenderContainerRef = useRef<HTMLDivElement>(null);
|
||||
const zoomInButtonRef = useRef<SVGSVGElement>(null);
|
||||
const zoomOutButtonRef = useRef<SVGSVGElement>(null);
|
||||
const resetZoomButtonRef = useRef<SVGSVGElement>(null);
|
||||
|
||||
const zoomInButtonId = useId();
|
||||
const zoomOutButtonId = useId();
|
||||
const resetZoomButtonId = useId();
|
||||
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setIsLoading(true);
|
||||
}, [code]);
|
||||
|
||||
useDebouncedEffect(
|
||||
() => {
|
||||
if (mermaidRenderContainerRef.current) {
|
||||
mermaidRenderContainerRef.current.innerHTML = "";
|
||||
}
|
||||
const diagramId = `mermaid-id-${Math.random().toString(36).substring(2)}`;
|
||||
void (async () => {
|
||||
if (!mermaidRenderContainerRef.current) return;
|
||||
try {
|
||||
await mermaid.parse(code);
|
||||
const renderedSVG = await mermaid.render(diagramId, code);
|
||||
mermaidRenderContainerRef.current.innerHTML = renderedSVG.svg;
|
||||
setError("");
|
||||
const panzoom = Panzoom(mermaidRenderContainerRef.current, {
|
||||
step: MINIMUM_ZOOM_STEP,
|
||||
});
|
||||
zoomInButtonRef.current?.addEventListener("click", () =>
|
||||
panzoom.zoomIn({ step: MINIMUM_ZOOM_STEP * 4 }),
|
||||
);
|
||||
zoomOutButtonRef.current?.addEventListener("click", () =>
|
||||
panzoom.zoomOut({ step: MINIMUM_ZOOM_STEP * 4 }),
|
||||
);
|
||||
resetZoomButtonRef.current?.addEventListener("click", () =>
|
||||
panzoom.reset(),
|
||||
);
|
||||
mermaidRenderContainerRef.current.parentElement?.addEventListener(
|
||||
"wheel",
|
||||
(event) => {
|
||||
if (!event.shiftKey) return;
|
||||
panzoom.zoomWithWheel(event);
|
||||
},
|
||||
);
|
||||
} catch (err: any) {
|
||||
if (err.message) {
|
||||
setError(err.message);
|
||||
} else {
|
||||
setError(
|
||||
"Unknown error when parsing or rendering the Mermaid diagram.",
|
||||
);
|
||||
}
|
||||
}
|
||||
setIsLoading(false);
|
||||
})();
|
||||
},
|
||||
500,
|
||||
[code],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isLoading && (
|
||||
<div className="text-vsc-foreground text-xs">Generating diagram...</div>
|
||||
)}
|
||||
{!!error ? (
|
||||
<div className="text-error whitespace-pre text-sm">{error}</div>
|
||||
) : (
|
||||
<div className="relative">
|
||||
<div className="absolute right-0 z-10 m-2 flex items-center gap-x-1">
|
||||
<MagnifyingGlassPlusIcon
|
||||
data-tooltip-id={zoomInButtonId}
|
||||
ref={zoomInButtonRef}
|
||||
className="h-4 w-4 cursor-pointer"
|
||||
/>
|
||||
<ToolTip id={zoomInButtonId}>Zoom In</ToolTip>
|
||||
<MagnifyingGlassMinusIcon
|
||||
data-tooltip-id={zoomOutButtonId}
|
||||
ref={zoomOutButtonRef}
|
||||
className="h-4 w-4 cursor-pointer"
|
||||
/>
|
||||
<ToolTip id={zoomOutButtonId}>Zoom Out</ToolTip>
|
||||
<ArrowPathRoundedSquareIcon
|
||||
data-tooltip-id={resetZoomButtonId}
|
||||
ref={resetZoomButtonRef}
|
||||
className="h-4 w-4 cursor-pointer"
|
||||
/>
|
||||
<ToolTip id={resetZoomButtonId}>Reset Zoom</ToolTip>
|
||||
</div>
|
||||
<div
|
||||
className="flex min-h-5 justify-center"
|
||||
ref={mermaidRenderContainerRef}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
import { ReactNode, useMemo } from "react";
|
||||
import { Tooltip } from "react-tooltip";
|
||||
import { getFontSize } from "../../../util";
|
||||
import { ToolTip } from "../../gui/Tooltip";
|
||||
|
||||
interface ToolbarButtonWithTooltipProps {
|
||||
onClick: () => void;
|
||||
|
|
@ -22,20 +21,20 @@ export function ToolbarButtonWithTooltip({
|
|||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
onClick={onClick}
|
||||
style={{
|
||||
fontSize: `${getFontSize() - 2}px`,
|
||||
<div
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onClick();
|
||||
}}
|
||||
data-tooltip-id={tooltipId}
|
||||
data-testid={testId}
|
||||
className="text-foreground flex items-center border-none bg-transparent px-0.5 outline-none hover:cursor-pointer hover:brightness-125"
|
||||
className="hover:description-muted/30 cursor-pointer select-none rounded bg-transparent px-1 py-0.5 hover:opacity-80"
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
<Tooltip id={tooltipId} place="top">
|
||||
</div>
|
||||
<ToolTip id={tooltipId} place="top">
|
||||
{tooltipContent}
|
||||
</Tooltip>
|
||||
</ToolTip>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -219,7 +219,6 @@ export function StepContainerPreToolbar({
|
|||
if (isGeneratingCodeBlock) {
|
||||
return (
|
||||
<span className="text-lightgray inline-flex items-center gap-2 text-right">
|
||||
{!isExpanded ? `${numLines} line${plural}` : "Generating"}{" "}
|
||||
<div>
|
||||
<Spinner />
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ import { ToolTip } from "../gui/Tooltip";
|
|||
import FilenameLink from "./FilenameLink";
|
||||
import "./katex.css";
|
||||
import "./markdown.css";
|
||||
import MermaidBlock from "./MermaidBlock";
|
||||
import { rehypeHighlightPlugin } from "./rehypeHighlightPlugin";
|
||||
import { StepContainerPreToolbar } from "./StepContainerPreToolbar";
|
||||
import SymbolLink from "./SymbolLink";
|
||||
|
|
@ -333,6 +334,10 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
}
|
||||
}
|
||||
}
|
||||
if (codeProps.className?.includes("language-mermaid")) {
|
||||
const codeText = String(codeProps.children || "");
|
||||
return <MermaidBlock code={codeText} />;
|
||||
}
|
||||
return <code {...codeProps}>{codeProps.children}</code>;
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,64 +0,0 @@
|
|||
import { usePostHog } from "posthog-js/react";
|
||||
import { setDialogMessage } from "../../redux/slices/uiSlice";
|
||||
import { useAppDispatch } from "../../redux/hooks";
|
||||
|
||||
export default function FeedbackDialog() {
|
||||
const posthog = usePostHog();
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
return (
|
||||
<div className="p-4 text-center">
|
||||
👋 Thanks for using Continue. We are always trying to improve and love
|
||||
hearing from users. If you're interested in speaking, enter your name and
|
||||
email. We won't use this information for anything other than reaching out.
|
||||
<br />
|
||||
<br />
|
||||
<form
|
||||
onSubmit={(e: any) => {
|
||||
e.preventDefault();
|
||||
posthog?.capture("user_interest_form", {
|
||||
name: e.target.elements[0].value,
|
||||
email: e.target.elements[1].value,
|
||||
});
|
||||
dispatch(
|
||||
setDialogMessage(
|
||||
<div className="p-4 text-center">
|
||||
Thanks! We'll be in touch soon.
|
||||
</div>,
|
||||
),
|
||||
);
|
||||
}}
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: "10px",
|
||||
}}
|
||||
>
|
||||
<input
|
||||
style={{ padding: "10px", borderRadius: "5px" }}
|
||||
type="text"
|
||||
name="name"
|
||||
placeholder="Name"
|
||||
required
|
||||
/>
|
||||
<input
|
||||
style={{ padding: "10px", borderRadius: "5px" }}
|
||||
type="email"
|
||||
name="email"
|
||||
placeholder="Email"
|
||||
required
|
||||
/>
|
||||
<button
|
||||
style={{
|
||||
padding: "10px",
|
||||
borderRadius: "5px",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
type="submit"
|
||||
>
|
||||
Submit
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -18,7 +18,7 @@ import {
|
|||
SearchMatch,
|
||||
searchWithinContainer,
|
||||
} from "./findWidgetSearch";
|
||||
import useDebounceValue from "./useDebounce";
|
||||
import { useDebounceValue } from "./useDebounce";
|
||||
import { useElementSize } from "./useElementSize";
|
||||
|
||||
interface HighlightOverlayProps {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
function useDebounceValue<T>(value: T, delay: number = 500): T {
|
||||
export function useDebounceValue<T>(value: T, delay: number = 500): T {
|
||||
const [debouncedValue, setDebouncedValue] = useState<T>(value);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -16,4 +16,32 @@ function useDebounceValue<T>(value: T, delay: number = 500): T {
|
|||
return debouncedValue;
|
||||
}
|
||||
|
||||
export default useDebounceValue;
|
||||
export function useDebouncedEffect(
|
||||
effect: () => void,
|
||||
delay: number,
|
||||
deps: unknown[],
|
||||
) {
|
||||
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const callBackRef = useRef(() => {});
|
||||
|
||||
useEffect(() => {
|
||||
// do not want the timeout to reset on effect dep change
|
||||
callBackRef.current = effect;
|
||||
}, [effect]);
|
||||
|
||||
useEffect(() => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
callBackRef.current();
|
||||
}, delay);
|
||||
|
||||
return () => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, [delay, ...deps]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ export function EditToolbar() {
|
|||
Back to {mode.charAt(0).toUpperCase() + mode.slice(1)}
|
||||
</span>
|
||||
<span className="truncate">
|
||||
Editing{" "}
|
||||
Editing:{" "}
|
||||
<span className="italic">
|
||||
{getEditFilenameAndRangeText(codeToEdit)}
|
||||
</span>
|
||||
|
|
|
|||
|
|
@ -36,8 +36,8 @@ const isCancelToolCallShortcut = (
|
|||
};
|
||||
|
||||
export function LumpToolbar() {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const dispatch = useAppDispatch();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const ttsActive = useAppSelector((state) => state.ui.ttsActive);
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
const isInEdit = useAppSelector((state) => state.session.isInEdit);
|
||||
|
|
@ -71,7 +71,6 @@ export function LumpToolbar() {
|
|||
} else if (isCancelToolCallShortcut(event, jetbrains)) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
void dispatch(
|
||||
cancelToolCall({
|
||||
toolCallId: firstPendingToolCall.toolCallId,
|
||||
|
|
|
|||
|
|
@ -29,6 +29,14 @@ const MINISEARCH_OPTIONS = {
|
|||
|
||||
const MAX_LENGTH = 70;
|
||||
|
||||
// Enhanced search result interface for intelligent sorting
|
||||
interface EnhancedSearchResult
|
||||
extends SearchResult,
|
||||
Omit<ContextSubmenuItemWithProvider, "id"> {
|
||||
sortPriority: number;
|
||||
matchQuality: number;
|
||||
}
|
||||
|
||||
interface SubtextContextProvidersContextType {
|
||||
getSubmenuContextItems: (
|
||||
providerTitle: string | undefined,
|
||||
|
|
@ -43,6 +51,91 @@ const initialContextProviders: SubtextContextProvidersContextType = {
|
|||
const SubmenuContextProvidersContext =
|
||||
createContext<SubtextContextProvidersContextType>(initialContextProviders);
|
||||
|
||||
// Helper functions for intelligent file sorting
|
||||
function hasExactWordMatch(text: string, query: string): boolean {
|
||||
const words = text.split(/[^a-zA-Z0-9]+/);
|
||||
return words.some((word) => word === query);
|
||||
}
|
||||
|
||||
function isCommonDevFile(fileName: string): boolean {
|
||||
const commonExtensions = [
|
||||
".ts",
|
||||
".tsx",
|
||||
".js",
|
||||
".jsx",
|
||||
".py",
|
||||
".java",
|
||||
".cpp",
|
||||
".c",
|
||||
".h",
|
||||
".vue",
|
||||
".svelte",
|
||||
];
|
||||
const commonNames = [
|
||||
"index",
|
||||
"main",
|
||||
"app",
|
||||
"component",
|
||||
"service",
|
||||
"util",
|
||||
"helper",
|
||||
"config",
|
||||
"types",
|
||||
];
|
||||
|
||||
const extension = fileName.substring(fileName.lastIndexOf("."));
|
||||
const baseName = fileName
|
||||
.substring(0, fileName.lastIndexOf("."))
|
||||
.toLowerCase();
|
||||
|
||||
return commonExtensions.includes(extension) || commonNames.includes(baseName);
|
||||
}
|
||||
|
||||
function isInCommonDirectory(filePath: string): boolean {
|
||||
const commonDirs = [
|
||||
"src/",
|
||||
"lib/",
|
||||
"components/",
|
||||
"utils/",
|
||||
"helpers/",
|
||||
"services/",
|
||||
"pages/",
|
||||
"views/",
|
||||
"hooks/",
|
||||
"store/",
|
||||
"types/",
|
||||
"interfaces/",
|
||||
"models/",
|
||||
"api/",
|
||||
];
|
||||
return commonDirs.some((dir) => filePath.includes(dir));
|
||||
}
|
||||
|
||||
function matchesCamelCaseOrAbbreviation(
|
||||
fileName: string,
|
||||
query: string,
|
||||
): boolean {
|
||||
// Extract capital letters for camel case matching
|
||||
const capitals = fileName.match(/[A-Z]/g)?.join("").toLowerCase() || "";
|
||||
|
||||
// Check if query matches the capital letters pattern
|
||||
if (capitals.length > 0 && capitals.includes(query)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for abbreviation matches (first letters of words)
|
||||
const words = fileName.split(/[^a-zA-Z0-9]+/).filter((w) => w.length > 0);
|
||||
if (words.length > 1) {
|
||||
const abbreviation = words
|
||||
.map((word) => word[0])
|
||||
.join("")
|
||||
.toLowerCase();
|
||||
return abbreviation.includes(query);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export const SubmenuContextProvidersProvider = ({
|
||||
children,
|
||||
}: {
|
||||
|
|
@ -128,6 +221,98 @@ export const SubmenuContextProvidersProvider = ({
|
|||
new Map<ContextProviderName, AbortController>(),
|
||||
).current;
|
||||
|
||||
const calculateFileSortPriority = useCallback(
|
||||
(
|
||||
result: SearchResult & ContextSubmenuItemWithProvider,
|
||||
query: string,
|
||||
openFiles: ContextSubmenuItemWithProvider[],
|
||||
): number => {
|
||||
const fileName = result.title.toLowerCase();
|
||||
const filePath = result.description.toLowerCase();
|
||||
const queryLower = query.toLowerCase();
|
||||
|
||||
// Priority 1: Exact filename match
|
||||
if (fileName === queryLower) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Priority 2: Recently opened files
|
||||
if (openFiles.some((f) => f.id === result.id)) {
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Priority 3: Filename starts with query
|
||||
if (fileName.startsWith(queryLower)) {
|
||||
return 3;
|
||||
}
|
||||
|
||||
// Priority 4: Exact word match in filename
|
||||
if (hasExactWordMatch(fileName, queryLower)) {
|
||||
return 4;
|
||||
}
|
||||
|
||||
// Priority 5: Common development files
|
||||
if (isCommonDevFile(fileName)) {
|
||||
return 5;
|
||||
}
|
||||
|
||||
// Priority 6: Files in common directories
|
||||
if (isInCommonDirectory(filePath)) {
|
||||
return 6;
|
||||
}
|
||||
|
||||
// Priority 7: CamelCase/abbreviation matches
|
||||
if (matchesCamelCaseOrAbbreviation(fileName, queryLower)) {
|
||||
return 7;
|
||||
}
|
||||
|
||||
// Priority 8: Path starts with query
|
||||
if (filePath.startsWith(queryLower)) {
|
||||
return 8;
|
||||
}
|
||||
|
||||
// Priority 9: Default
|
||||
return 9;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const calculateMatchQuality = useCallback(
|
||||
(
|
||||
result: SearchResult & ContextSubmenuItemWithProvider,
|
||||
query: string,
|
||||
): number => {
|
||||
const fileName = result.title.toLowerCase();
|
||||
const queryLower = query.toLowerCase();
|
||||
let quality = 0;
|
||||
|
||||
// Exact match bonus
|
||||
if (fileName === queryLower) quality += 100;
|
||||
|
||||
// Prefix match bonus
|
||||
if (fileName.startsWith(queryLower)) quality += 50;
|
||||
|
||||
// Contains match bonus
|
||||
if (fileName.includes(queryLower)) quality += 25;
|
||||
|
||||
// Shorter filename bonus (prefer concise names)
|
||||
quality += Math.max(0, 50 - fileName.length);
|
||||
|
||||
// Extension preference (common dev files)
|
||||
if (
|
||||
fileName.endsWith(".ts") ||
|
||||
fileName.endsWith(".tsx") ||
|
||||
fileName.endsWith(".js") ||
|
||||
fileName.endsWith(".jsx")
|
||||
) {
|
||||
quality += 10;
|
||||
}
|
||||
|
||||
return quality;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const getSubmenuContextItems = useCallback(
|
||||
(
|
||||
providerTitle: string | undefined,
|
||||
|
|
@ -168,9 +353,57 @@ export const SubmenuContextProvidersProvider = ({
|
|||
});
|
||||
}
|
||||
}
|
||||
searchResults.sort((a, b) => b.score - a.score);
|
||||
|
||||
// 2. Add fallback results if no search results
|
||||
// 2. Enhanced sorting for file provider
|
||||
if (
|
||||
providerTitle === "file" ||
|
||||
(!providerTitle &&
|
||||
searchResults.some((r) => r.providerTitle === "file"))
|
||||
) {
|
||||
const enhancedResults: EnhancedSearchResult[] = searchResults.map(
|
||||
(result): EnhancedSearchResult => ({
|
||||
...result,
|
||||
id: result.id,
|
||||
title: result.title,
|
||||
description: result.description,
|
||||
providerTitle: result.providerTitle,
|
||||
sortPriority: calculateFileSortPriority(
|
||||
result,
|
||||
query,
|
||||
lastOpenFilesRef.current,
|
||||
),
|
||||
matchQuality: calculateMatchQuality(result, query),
|
||||
}),
|
||||
);
|
||||
|
||||
// Sort by multiple criteria
|
||||
enhancedResults.sort((a, b) => {
|
||||
// Primary: Sort priority (lower = better)
|
||||
if (a.sortPriority !== b.sortPriority) {
|
||||
return a.sortPriority - b.sortPriority;
|
||||
}
|
||||
|
||||
// Secondary: Match quality (higher = better)
|
||||
if (a.matchQuality !== b.matchQuality) {
|
||||
return b.matchQuality - a.matchQuality;
|
||||
}
|
||||
|
||||
// Tertiary: MiniSearch relevance score (higher = better)
|
||||
if (a.score !== b.score) {
|
||||
return b.score - a.score;
|
||||
}
|
||||
|
||||
// Quaternary: Path length (shorter = better)
|
||||
return a.description.length - b.description.length;
|
||||
});
|
||||
|
||||
searchResults = enhancedResults;
|
||||
} else {
|
||||
// Default sorting for non-file providers
|
||||
searchResults.sort((a, b) => b.score - a.score);
|
||||
}
|
||||
|
||||
// 3. Add fallback results if no search results
|
||||
if (searchResults.length === 0) {
|
||||
const fallbackItems = (
|
||||
providerTitle ? (fallbackResults[providerTitle] ?? []) : []
|
||||
|
|
@ -223,7 +456,12 @@ export const SubmenuContextProvidersProvider = ({
|
|||
return [];
|
||||
}
|
||||
},
|
||||
[fallbackResults, minisearches],
|
||||
[
|
||||
fallbackResults,
|
||||
minisearches,
|
||||
calculateFileSortPriority,
|
||||
calculateMatchQuality,
|
||||
],
|
||||
);
|
||||
|
||||
const loadSubmenuItems = useCallback(
|
||||
|
|
|
|||
|
|
@ -16,7 +16,6 @@ import {
|
|||
import { ErrorBoundary } from "react-error-boundary";
|
||||
import styled from "styled-components";
|
||||
import { Button, lightGray, vscBackground } from "../../components";
|
||||
import FeedbackDialog from "../../components/dialogs/FeedbackDialog";
|
||||
import { useFindWidget } from "../../components/find/FindWidget";
|
||||
import TimelineItem from "../../components/gui/TimelineItem";
|
||||
import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton";
|
||||
|
|
@ -38,11 +37,6 @@ import {
|
|||
newSession,
|
||||
updateToolCallOutput,
|
||||
} from "../../redux/slices/sessionSlice";
|
||||
import {
|
||||
setDialogEntryOn,
|
||||
setDialogMessage,
|
||||
setShowDialog,
|
||||
} from "../../redux/slices/uiSlice";
|
||||
import { streamEditThunk } from "../../redux/thunks/edit";
|
||||
import { loadLastSession } from "../../redux/thunks/session";
|
||||
import { streamResponseThunk } from "../../redux/thunks/streamResponse";
|
||||
|
|
@ -50,7 +44,6 @@ import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
|
|||
import { ToolCallDiv } from "./ToolCallDiv";
|
||||
|
||||
import { cancelStream } from "../../redux/thunks/cancelStream";
|
||||
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
|
||||
import { EmptyChatBody } from "./EmptyChatBody";
|
||||
import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
|
||||
import { useAutoScroll } from "./useAutoScroll";
|
||||
|
|
@ -222,19 +215,6 @@ export function Chat() {
|
|||
editorToClearOnSend.commands.clearContent();
|
||||
}
|
||||
}
|
||||
|
||||
// Increment localstorage counter for popup
|
||||
const currentCount = getLocalStorage("mainTextEntryCounter");
|
||||
if (currentCount) {
|
||||
setLocalStorage("mainTextEntryCounter", currentCount + 1);
|
||||
if (currentCount === 300) {
|
||||
dispatch(setDialogMessage(<FeedbackDialog />));
|
||||
dispatch(setDialogEntryOn(false));
|
||||
dispatch(setShowDialog(true));
|
||||
}
|
||||
} else {
|
||||
setLocalStorage("mainTextEntryCounter", 1);
|
||||
}
|
||||
},
|
||||
[
|
||||
history,
|
||||
|
|
|
|||
|
|
@ -6,15 +6,14 @@ type EditToolCallProps = {
|
|||
changes: string;
|
||||
historyIndex: number;
|
||||
toolCallId?: string;
|
||||
expandCodeblocks?: boolean;
|
||||
};
|
||||
|
||||
export function EditFile(props: EditToolCallProps) {
|
||||
if (!props.relativeFilePath || !props.changes) {
|
||||
if (!props.relativeFilePath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.changes}\n\`\`\``;
|
||||
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath)} ${props.relativeFilePath}\n${props.changes}\n\`\`\``;
|
||||
|
||||
return (
|
||||
<StyledMarkdownPreview
|
||||
|
|
|
|||
|
|
@ -36,7 +36,6 @@ function FunctionSpecificToolCallDiv({
|
|||
case BuiltInToolNames.SearchAndReplaceInFile:
|
||||
return (
|
||||
<EditFile
|
||||
expandCodeblocks
|
||||
relativeFilePath={args.filepath ?? ""}
|
||||
changes={args.diff ?? ""}
|
||||
toolCallId={toolCall.id}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { CodeBracketIcon } from "@heroicons/react/24/outline";
|
||||
import { useMemo } from "react";
|
||||
import { ToolTip } from "../../../components/gui/Tooltip";
|
||||
import { ToolbarButtonWithTooltip } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip";
|
||||
|
||||
interface ArgsToggleIconProps {
|
||||
isShowing: boolean;
|
||||
|
|
@ -13,26 +12,15 @@ export const ArgsToggleIcon = ({
|
|||
setIsShowing,
|
||||
toolCallId,
|
||||
}: ArgsToggleIconProps) => {
|
||||
const argsTooltipId = useMemo(() => {
|
||||
return "args-hover-" + toolCallId;
|
||||
}, [toolCallId]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
data-tooltip-id={argsTooltipId}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setIsShowing(!isShowing);
|
||||
}}
|
||||
className={`hover:description-muted/30 cursor-pointer select-none rounded px-1 py-0.5 hover:opacity-80 ${isShowing ? "bg-description-muted/30" : "bg-transparent"}`}
|
||||
>
|
||||
<CodeBracketIcon className="h-3 w-3 flex-shrink-0 opacity-60" />
|
||||
</div>
|
||||
<ToolTip id={argsTooltipId}>
|
||||
{isShowing ? "Hide args" : "Show args"}
|
||||
</ToolTip>
|
||||
</>
|
||||
<ToolbarButtonWithTooltip
|
||||
tooltipContent={isShowing ? "Hide args" : "Show args"}
|
||||
onClick={() => {
|
||||
setIsShowing(!isShowing);
|
||||
}}
|
||||
>
|
||||
<CodeBracketIcon className="h-3 w-3 flex-shrink-0 opacity-60" />
|
||||
</ToolbarButtonWithTooltip>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -19,9 +19,11 @@ export function ToolTruncateHistoryIcon({
|
|||
}, [history]);
|
||||
const dispatch = useAppDispatch();
|
||||
const { mainEditor } = useMainEditor();
|
||||
|
||||
if (historyIndex === lastMessageIndex) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<ToolbarButtonWithTooltip
|
||||
tooltipContent={isStreaming ? "" : "Trim chat to this message"}
|
||||
|
|
@ -38,7 +40,7 @@ export function ToolTruncateHistoryIcon({
|
|||
}}
|
||||
>
|
||||
<BarsArrowUpIcon
|
||||
className={`h-3 w-3 flex-shrink-0 ${isStreaming ? "cursor-not-allowed" : "cursor-pointer"}`}
|
||||
className={`h-3 w-3 flex-shrink-0 opacity-60 ${isStreaming ? "cursor-not-allowed" : ""}`}
|
||||
/>
|
||||
</ToolbarButtonWithTooltip>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -107,6 +107,7 @@ export function ToolCallDiv({
|
|||
);
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<div>
|
||||
{toolCallStates.map((toolCallState) => (
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ test("should render input box", async () => {
|
|||
|
||||
test("should be able to toggle modes", async () => {
|
||||
await renderWithProviders(<Chat />);
|
||||
await getElementByText("Chat");
|
||||
await getElementByText("Agent");
|
||||
|
||||
// Simulate cmd+. keyboard shortcut to toggle modes
|
||||
act(() => {
|
||||
|
|
@ -27,6 +27,18 @@ test("should be able to toggle modes", async () => {
|
|||
);
|
||||
});
|
||||
|
||||
// Check that it switched to Chat mode
|
||||
await getElementByText("Chat");
|
||||
|
||||
act(() => {
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: ".",
|
||||
metaKey: true, // cmd key on Mac
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// Check that it switched to Plan mode
|
||||
await getElementByText("Plan");
|
||||
|
||||
|
|
@ -39,19 +51,7 @@ test("should be able to toggle modes", async () => {
|
|||
);
|
||||
});
|
||||
|
||||
// Check that it switched to Agent mode
|
||||
await getElementByText("Agent");
|
||||
|
||||
act(() => {
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: ".",
|
||||
metaKey: true, // cmd key on Mac
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
await getElementByText("Chat");
|
||||
});
|
||||
|
||||
test("should send a message and receive a response", async () => {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
418
gui/src/redux/slices/sessionSlice.test.ts
Normal file
418
gui/src/redux/slices/sessionSlice.test.ts
Normal file
|
|
@ -0,0 +1,418 @@
|
|||
import { ChatMessage } from "core";
|
||||
import { renderChatMessage } from "core/util/messageContent";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { addToolCallDeltaToState } from "../../util/toolCallState";
|
||||
import { ChatHistoryItemWithMessageId, sessionSlice } from "./sessionSlice";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("uuid");
|
||||
vi.mock("core/util/messageContent");
|
||||
vi.mock("../../util/toolCallState");
|
||||
|
||||
const mockUuidv4 = vi.mocked(uuidv4);
|
||||
const mockRenderChatMessage = vi.mocked(renderChatMessage);
|
||||
const mockAddToolCallDeltaToState = vi.mocked(addToolCallDeltaToState);
|
||||
|
||||
describe("sessionSlice streamUpdate", () => {
|
||||
beforeEach(() => {
|
||||
// Reset mocks before each test
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Mock uuidv4 to return predictable values
|
||||
let callCount = 0;
|
||||
mockUuidv4.mockImplementation(() => `mock-uuid-${++callCount}`);
|
||||
|
||||
// Mock renderChatMessage to return content as is
|
||||
mockRenderChatMessage.mockImplementation((message: ChatMessage) => {
|
||||
if (typeof message.content === "string") {
|
||||
return message.content;
|
||||
}
|
||||
return "";
|
||||
});
|
||||
|
||||
// Mock addToolCallDeltaToState
|
||||
mockAddToolCallDeltaToState.mockImplementation((delta, state) => {
|
||||
return {
|
||||
status: "generating" as const,
|
||||
toolCall: {
|
||||
id: delta.id || "mock-tool-id",
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: delta.function?.name || "mock-function",
|
||||
arguments: delta.function?.arguments || "{}",
|
||||
},
|
||||
},
|
||||
toolCallId: delta.id || "mock-tool-id",
|
||||
parsedArgs: {},
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
const createInitialState = () => ({
|
||||
lastSessionId: undefined,
|
||||
allSessionMetadata: [],
|
||||
history: [
|
||||
{
|
||||
message: {
|
||||
role: "user" as const,
|
||||
content: "This is a test.",
|
||||
id: "initial-user-message",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
] as ChatHistoryItemWithMessageId[],
|
||||
isStreaming: false,
|
||||
title: "Test Session",
|
||||
id: "test-session-id",
|
||||
streamAborter: new AbortController(),
|
||||
symbols: {},
|
||||
mode: "chat" as const,
|
||||
isInEdit: false,
|
||||
codeBlockApplyStates: {
|
||||
states: [],
|
||||
curIndex: 0,
|
||||
},
|
||||
newestToolbarPreviewForInput: {},
|
||||
isSessionMetadataLoading: false,
|
||||
});
|
||||
|
||||
describe("Basic Chat Message", () => {
|
||||
it("should append assistant message to history", () => {
|
||||
const initialState = createInitialState();
|
||||
const action = {
|
||||
type: "session/streamUpdate",
|
||||
payload: [
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "Here is a response to your message without thinking.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const newState = sessionSlice.reducer(initialState, action);
|
||||
|
||||
expect(newState.history).toHaveLength(2);
|
||||
expect(newState.history[1].message.role).toBe("assistant");
|
||||
expect(newState.history[1].message.content).toBe(
|
||||
"Here is a response to your message without thinking.",
|
||||
);
|
||||
expect(newState.history[1].message.id).toBe("mock-uuid-1");
|
||||
expect(newState.history[1].contextItems).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Chat Message With Thinking", () => {
|
||||
it("should split thinking and assistant content correctly", () => {
|
||||
const initialState = createInitialState();
|
||||
const action = {
|
||||
type: "session/streamUpdate",
|
||||
payload: [
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content:
|
||||
"<think>I should send the user a response.</think> Here is a response to your message with thinking.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const newState = sessionSlice.reducer(initialState, action);
|
||||
|
||||
expect(newState.history).toHaveLength(2);
|
||||
|
||||
// Check reasoning
|
||||
expect(newState.history[0].reasoning?.text).toBe(
|
||||
"I should send the user a response.",
|
||||
);
|
||||
|
||||
// Check assistant message
|
||||
expect(newState.history[1].message.role).toBe("assistant");
|
||||
expect(newState.history[1].message.content).toBe(
|
||||
"Here is a response to your message with thinking.",
|
||||
);
|
||||
expect(newState.history[1].message.id).toBe("mock-uuid-1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Tool Call With Response", () => {
|
||||
it("should handle tool call followed by tool response and assistant message", () => {
|
||||
const initialState = createInitialState();
|
||||
const toolCallAction = {
|
||||
type: "session/streamUpdate",
|
||||
payload: [
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "<think>I should use a tool call.</think>",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "1234",
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "builtin_ls",
|
||||
arguments: '{"dirPath":".","recursive":false}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let newState = sessionSlice.reducer(initialState, toolCallAction);
|
||||
expect(newState.history).toHaveLength(2);
|
||||
|
||||
// Check reasoning
|
||||
expect(newState.history[0].reasoning?.text).toBe(
|
||||
"I should use a tool call.",
|
||||
);
|
||||
|
||||
// Check generating message
|
||||
expect(newState.history[1].message.role).toBe("assistant");
|
||||
expect(newState.history[1].message.content).toBe("");
|
||||
expect(newState.history[1].toolCallStates?.[0]?.status).toBe("generating");
|
||||
expect(newState.history[1].toolCallStates?.[0]?.toolCallId).toBe("1234");
|
||||
|
||||
const toolResponseAction = {
|
||||
type: "session/streamUpdate",
|
||||
payload: [
|
||||
{
|
||||
role: "tool" as const,
|
||||
toolCallId: "1234",
|
||||
content: "foo.txt\nbar.txt\nexample.php",
|
||||
},
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "I see, the tool found 3 files.",
|
||||
},
|
||||
],
|
||||
};
|
||||
newState = sessionSlice.reducer(newState, toolResponseAction);
|
||||
expect(newState.history).toHaveLength(4);
|
||||
|
||||
// Check tool message
|
||||
expect(newState.history[2].message.role).toBe("tool");
|
||||
expect(newState.history[2].message.content).toBe(
|
||||
"foo.txt\nbar.txt\nexample.php",
|
||||
);
|
||||
expect((newState.history[2].message as any).toolCallId).toBe("1234");
|
||||
|
||||
// Check final assistant message
|
||||
expect(newState.history[3].message.role).toBe("assistant");
|
||||
expect(newState.history[3].message.content).toBe(
|
||||
"I see, the tool found 3 files.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Tool Call With Streaming Response", () => {
|
||||
it("should handle streaming assistant response after tool call", () => {
|
||||
const initialState = createInitialState();
|
||||
const toolCallAction = {
|
||||
type: "session/streamUpdate",
|
||||
payload: [
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "<think>I should use a tool call.</think>",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "1234",
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "builtin_ls",
|
||||
arguments: '{"dirPath":".","recursive":false}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let newState = sessionSlice.reducer(initialState, toolCallAction);
|
||||
expect(newState.history).toHaveLength(2);
|
||||
|
||||
// Check reasoning
|
||||
expect(newState.history[0].reasoning?.text).toBe(
|
||||
"I should use a tool call.",
|
||||
);
|
||||
|
||||
// Check generating message
|
||||
expect(newState.history[1].message.role).toBe("assistant");
|
||||
expect(newState.history[1].message.content).toBe("");
|
||||
expect(newState.history[1].toolCallStates?.[0]?.status).toBe("generating");
|
||||
expect(newState.history[1].toolCallStates?.[0]?.toolCallId).toBe("1234");
|
||||
|
||||
const toolResponseAction = {
|
||||
type: "session/streamUpdate",
|
||||
payload: [
|
||||
{
|
||||
role: "tool" as const,
|
||||
toolCallId: "1234",
|
||||
content: "foo.txt\nbar.txt\nexample.php",
|
||||
},
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "<think>",
|
||||
},
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "Good, ",
|
||||
},
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "I received a list",
|
||||
},
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: " of files.",
|
||||
},
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "</think>",
|
||||
},
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "\n",
|
||||
},
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "I see, ",
|
||||
},
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "the tool ",
|
||||
},
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "found 3 ",
|
||||
},
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "files.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
newState = sessionSlice.reducer(newState, toolResponseAction);
|
||||
|
||||
expect(newState.history).toHaveLength(4);
|
||||
|
||||
// Check tool message
|
||||
expect(newState.history[2].message.role).toBe("tool");
|
||||
expect(newState.history[2].message.content).toBe(
|
||||
"foo.txt\nbar.txt\nexample.php",
|
||||
);
|
||||
|
||||
// Check response message
|
||||
expect(newState.history[3].message.role).toBe("assistant");
|
||||
expect(newState.history[3].message.content).toBe(
|
||||
"I see, the tool found 3 files.",
|
||||
);
|
||||
expect(newState.history[3].reasoning?.text).toBe(
|
||||
"Good, I received a list of files.",
|
||||
);
|
||||
expect(newState.history[3].reasoning?.active).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Edge Cases", () => {
|
||||
it("should handle empty history gracefully", () => {
|
||||
const initialState = createInitialState();
|
||||
initialState.history = [];
|
||||
|
||||
const action = {
|
||||
type: "session/streamUpdate",
|
||||
payload: [
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "Hello",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const newState = sessionSlice.reducer(initialState, action);
|
||||
|
||||
// Should not crash and history should remain empty
|
||||
expect(newState.history).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should handle redacted thinking messages", () => {
|
||||
const initialState = createInitialState();
|
||||
const action = {
|
||||
type: "session/streamUpdate",
|
||||
payload: [
|
||||
{
|
||||
role: "thinking" as const,
|
||||
content: "This should be hidden",
|
||||
redactedThinking: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const newState = sessionSlice.reducer(initialState, action);
|
||||
|
||||
expect(newState.history).toHaveLength(2);
|
||||
expect(newState.history[1].message.role).toBe("thinking");
|
||||
expect(newState.history[1].message.content).toBe(
|
||||
"internal reasoning is hidden due to safety reasons",
|
||||
);
|
||||
expect((newState.history[1].message as any).redactedThinking).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle signature updates for thinking messages", () => {
|
||||
const initialState = createInitialState();
|
||||
// First add a thinking message
|
||||
initialState.history.push({
|
||||
message: {
|
||||
role: "thinking",
|
||||
content: "Some thinking",
|
||||
id: "thinking-message",
|
||||
},
|
||||
contextItems: [],
|
||||
});
|
||||
|
||||
const action = {
|
||||
type: "session/streamUpdate",
|
||||
payload: [
|
||||
{
|
||||
role: "thinking" as const,
|
||||
signature: "test-signature",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const newState = sessionSlice.reducer(initialState, action);
|
||||
|
||||
expect(newState.history).toHaveLength(2);
|
||||
expect((newState.history[1].message as any).signature).toBe(
|
||||
"test-signature",
|
||||
);
|
||||
});
|
||||
|
||||
it("should accumulate content for same role messages", () => {
|
||||
const initialState = createInitialState();
|
||||
// Add an assistant message first
|
||||
initialState.history.push({
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "Hello ",
|
||||
id: "assistant-message",
|
||||
},
|
||||
contextItems: [],
|
||||
});
|
||||
|
||||
const action = {
|
||||
type: "session/streamUpdate",
|
||||
payload: [
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "world!",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const newState = sessionSlice.reducer(initialState, action);
|
||||
|
||||
expect(newState.history).toHaveLength(2);
|
||||
expect(newState.history[1].message.content).toBe("Hello world!");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -8,6 +8,7 @@ import {
|
|||
import { JSONContent } from "@tiptap/react";
|
||||
import {
|
||||
ApplyState,
|
||||
AssistantChatMessage,
|
||||
ChatHistoryItem,
|
||||
ChatMessage,
|
||||
ContextItem,
|
||||
|
|
@ -18,6 +19,7 @@ import {
|
|||
RuleWithSource,
|
||||
Session,
|
||||
SessionMetadata,
|
||||
ThinkingChatMessage,
|
||||
Tool,
|
||||
ToolCallState,
|
||||
} from "core";
|
||||
|
|
@ -71,7 +73,7 @@ const initialState: SessionState = {
|
|||
id: uuidv4(),
|
||||
streamAborter: new AbortController(),
|
||||
symbols: {},
|
||||
mode: "chat",
|
||||
mode: "agent",
|
||||
isInEdit: false,
|
||||
codeBlockApplyStates: {
|
||||
states: [],
|
||||
|
|
@ -333,12 +335,10 @@ export const sessionSlice = createSlice({
|
|||
streamUpdate: (state, action: PayloadAction<ChatMessage[]>) => {
|
||||
if (state.history.length) {
|
||||
for (const message of action.payload) {
|
||||
const lastItem = state.history[state.history.length - 1];
|
||||
const lastMessage = lastItem.message;
|
||||
let lastItem = state.history[state.history.length - 1];
|
||||
let lastMessage = lastItem.message;
|
||||
|
||||
if (message.role === "thinking" && message.redactedThinking) {
|
||||
console.log("add redacted_thinking blocks");
|
||||
|
||||
state.history.push({
|
||||
message: {
|
||||
role: "thinking",
|
||||
|
|
@ -351,6 +351,67 @@ export const sessionSlice = createSlice({
|
|||
continue;
|
||||
}
|
||||
|
||||
const messageContent = message.content
|
||||
? renderChatMessage(message)
|
||||
: "";
|
||||
|
||||
// OpenAI-compatible models in agent mode sometimes send
|
||||
// all of their data in one message, so we handle that case early.
|
||||
if (messageContent) {
|
||||
const thinkMatches = messageContent.match(
|
||||
/<think>([\s\S]*)<\/think>([\s\S]*)/,
|
||||
);
|
||||
if (thinkMatches) {
|
||||
// The order that they seem to consistently use is:
|
||||
//
|
||||
// <think>Thinking text</think>
|
||||
// Text to show to the user
|
||||
|
||||
lastItem.reasoning = {
|
||||
text: thinkMatches[1].trim(),
|
||||
startAt: Date.now(),
|
||||
endAt: Date.now(),
|
||||
active: false,
|
||||
};
|
||||
|
||||
// This is the chat message that we should show to the user.
|
||||
// We always need to push this even if it is empty,
|
||||
// because we cannot attach tool calls to a Thinking message.
|
||||
// That would break `messageHasToolCallId`.
|
||||
state.history.push({
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: thinkMatches[2].trim(),
|
||||
id: uuidv4(),
|
||||
},
|
||||
contextItems: [],
|
||||
});
|
||||
lastItem = state.history[state.history.length - 1];
|
||||
lastMessage = lastItem.message;
|
||||
|
||||
if (
|
||||
(message.role === "assistant" || message.role === "thinking") &&
|
||||
message.toolCalls?.length
|
||||
) {
|
||||
// Handle multiple tool calls
|
||||
lastItem.toolCallStates = message.toolCalls.map(
|
||||
(toolCallDelta) =>
|
||||
addToolCallDeltaToState(toolCallDelta, undefined),
|
||||
);
|
||||
// We know this is one of these two types because we just added it
|
||||
const curMessage = lastMessage as
|
||||
| AssistantChatMessage
|
||||
| ThinkingChatMessage;
|
||||
curMessage.toolCalls = lastItem.toolCallStates.map(
|
||||
(state) => state.toolCall,
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// The remainder of this function handles streaming messages
|
||||
if (
|
||||
lastMessage.role !== message.role ||
|
||||
message.role === "tool" // Tool messages should always create new messages
|
||||
|
|
@ -371,104 +432,96 @@ export const sessionSlice = createSlice({
|
|||
(toolCallDelta) =>
|
||||
addToolCallDeltaToState(toolCallDelta, undefined),
|
||||
);
|
||||
// Set toolCalls on the message for compatibility
|
||||
(historyItem.message as any).toolCalls = historyItem.toolCallStates.map(
|
||||
(state) => state.toolCall,
|
||||
);
|
||||
}
|
||||
state.history.push(historyItem);
|
||||
} else {
|
||||
// Add to the existing message
|
||||
lastItem = state.history[state.history.length - 1];
|
||||
lastMessage = lastItem.message;
|
||||
}
|
||||
|
||||
// Handle tool calls being added to existing assistant message
|
||||
if (
|
||||
message.role === "assistant" &&
|
||||
(message as any).toolCalls?.length &&
|
||||
!lastItem.toolCallStates
|
||||
// Add to the existing message
|
||||
if (messageContent) {
|
||||
if (messageContent.includes("<think>")) {
|
||||
lastItem.reasoning = {
|
||||
startAt: Date.now(),
|
||||
active: true,
|
||||
text: messageContent.replace("<think>", "").trim(),
|
||||
};
|
||||
} else if (
|
||||
lastItem.reasoning?.active &&
|
||||
messageContent.includes("</think>")
|
||||
) {
|
||||
lastItem.toolCallStates = (message as any).toolCalls.map(
|
||||
(toolCallDelta: any) =>
|
||||
addToolCallDeltaToState(toolCallDelta, undefined),
|
||||
);
|
||||
(lastMessage as any).toolCalls = lastItem.toolCallStates?.map(
|
||||
(state) => state.toolCall,
|
||||
);
|
||||
}
|
||||
|
||||
// CRITICAL: Always ensure message.toolCalls is synchronized with toolCallStates
|
||||
if (lastItem.toolCallStates && lastItem.toolCallStates.length > 0) {
|
||||
(lastMessage as any).toolCalls = lastItem.toolCallStates.map(
|
||||
(state) => state.toolCall,
|
||||
);
|
||||
}
|
||||
|
||||
if (message.content) {
|
||||
const messageContent = renderChatMessage(message);
|
||||
if (messageContent.includes("<think>")) {
|
||||
lastItem.reasoning = {
|
||||
startAt: Date.now(),
|
||||
active: true,
|
||||
text: messageContent.replace("<think>", "").trim(),
|
||||
};
|
||||
} else if (
|
||||
lastItem.reasoning?.active &&
|
||||
messageContent.includes("</think>")
|
||||
const [reasoningEnd, answerStart] =
|
||||
messageContent.split("</think>");
|
||||
lastItem.reasoning.text += reasoningEnd.trimEnd();
|
||||
lastItem.reasoning.active = false;
|
||||
lastItem.reasoning.endAt = Date.now();
|
||||
lastMessage.content += answerStart.trimStart();
|
||||
} else if (lastItem.reasoning?.active) {
|
||||
if (
|
||||
lastItem.reasoning.text.length > 0 ||
|
||||
messageContent.trim().length > 0
|
||||
) {
|
||||
const [reasoningEnd, answerStart] =
|
||||
messageContent.split("</think>");
|
||||
lastItem.reasoning.text += reasoningEnd.trimEnd();
|
||||
lastItem.reasoning.active = false;
|
||||
lastItem.reasoning.endAt = Date.now();
|
||||
lastMessage.content += answerStart.trimStart();
|
||||
} else if (lastItem.reasoning?.active) {
|
||||
lastItem.reasoning.text += messageContent;
|
||||
} else {
|
||||
// Note this only works because new message above
|
||||
// was already rendered from parts to string
|
||||
}
|
||||
} else {
|
||||
// Note this only works because new message above
|
||||
// was already rendered from parts to string
|
||||
if (
|
||||
lastMessage.content.length > 0 ||
|
||||
messageContent.trim().length > 0
|
||||
) {
|
||||
lastMessage.content += messageContent;
|
||||
}
|
||||
} else if (message.role === "thinking" && message.signature) {
|
||||
if (lastMessage.role === "thinking") {
|
||||
lastMessage.signature = message.signature;
|
||||
}
|
||||
} else if (
|
||||
message.role === "assistant" &&
|
||||
message.toolCalls?.length &&
|
||||
lastMessage.role === "assistant"
|
||||
) {
|
||||
// Handle multiple tool calls in streaming updates - ID-based approach
|
||||
const existingToolCallStates = lastItem.toolCallStates || [];
|
||||
const updatedToolCallStates: ToolCallState[] = [
|
||||
...existingToolCallStates,
|
||||
];
|
||||
|
||||
// Process each incoming tool call delta by ID
|
||||
for (const toolCallDelta of message.toolCalls) {
|
||||
// Find existing state by toolCallId
|
||||
const existingStateIndex = updatedToolCallStates.findIndex(
|
||||
(state) => state.toolCallId === toolCallDelta.id,
|
||||
);
|
||||
|
||||
const existingState =
|
||||
existingStateIndex >= 0
|
||||
? updatedToolCallStates[existingStateIndex]
|
||||
: undefined;
|
||||
|
||||
const updatedState = addToolCallDeltaToState(
|
||||
toolCallDelta,
|
||||
existingState,
|
||||
);
|
||||
|
||||
if (existingStateIndex >= 0) {
|
||||
// Update existing state
|
||||
updatedToolCallStates[existingStateIndex] = updatedState;
|
||||
} else {
|
||||
// Add new state
|
||||
updatedToolCallStates.push(updatedState);
|
||||
}
|
||||
}
|
||||
|
||||
lastItem.toolCallStates = updatedToolCallStates;
|
||||
(lastMessage as any).toolCalls = updatedToolCallStates.map(
|
||||
(state) => state.toolCall,
|
||||
);
|
||||
}
|
||||
} else if (message.role === "thinking" && message.signature) {
|
||||
if (lastMessage.role === "thinking") {
|
||||
lastMessage.signature = message.signature;
|
||||
}
|
||||
} else if (
|
||||
message.role === "assistant" &&
|
||||
message.toolCalls?.length &&
|
||||
lastMessage.role === "assistant"
|
||||
) {
|
||||
// Handle multiple tool calls in streaming updates - ID-based approach
|
||||
const existingToolCallStates = lastItem.toolCallStates || [];
|
||||
const updatedToolCallStates: ToolCallState[] = [
|
||||
...existingToolCallStates,
|
||||
];
|
||||
|
||||
// Process each incoming tool call delta by ID
|
||||
for (const toolCallDelta of message.toolCalls) {
|
||||
// Find existing state by toolCallId
|
||||
const existingStateIndex = updatedToolCallStates.findIndex(
|
||||
(state) => state.toolCallId === toolCallDelta.id,
|
||||
);
|
||||
|
||||
const existingState =
|
||||
existingStateIndex >= 0
|
||||
? updatedToolCallStates[existingStateIndex]
|
||||
: undefined;
|
||||
|
||||
const updatedState = addToolCallDeltaToState(
|
||||
toolCallDelta,
|
||||
existingState,
|
||||
);
|
||||
|
||||
if (existingStateIndex >= 0) {
|
||||
// Update existing state
|
||||
updatedToolCallStates[existingStateIndex] = updatedState;
|
||||
} else {
|
||||
// Add new state
|
||||
updatedToolCallStates.push(updatedState);
|
||||
}
|
||||
}
|
||||
|
||||
lastItem.toolCallStates = updatedToolCallStates;
|
||||
(lastMessage as any).toolCalls = updatedToolCallStates.map(
|
||||
(state) => state.toolCall,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -83,12 +83,6 @@ export const uiSlice = createSlice({
|
|||
) => {
|
||||
state.dialogMessage = action.payload;
|
||||
},
|
||||
setDialogEntryOn: (
|
||||
state,
|
||||
action: PayloadAction<UIState["dialogEntryOn"]>,
|
||||
) => {
|
||||
state.dialogEntryOn = action.payload;
|
||||
},
|
||||
setShowDialog: (state, action: PayloadAction<UIState["showDialog"]>) => {
|
||||
state.showDialog = action.payload;
|
||||
},
|
||||
|
|
@ -98,9 +92,6 @@ export const uiSlice = createSlice({
|
|||
) => {
|
||||
state.isExploreDialogOpen = action.payload;
|
||||
},
|
||||
setHasDismissedExploreDialog: (state, action: PayloadAction<boolean>) => {
|
||||
state.hasDismissedExploreDialog = action.payload;
|
||||
},
|
||||
// Tools
|
||||
addTool: (state, action: PayloadAction<Tool>) => {
|
||||
state.toolSettings[action.payload.function.name] =
|
||||
|
|
@ -173,10 +164,8 @@ export const uiSlice = createSlice({
|
|||
export const {
|
||||
setOnboardingCard,
|
||||
setDialogMessage,
|
||||
setDialogEntryOn,
|
||||
setShowDialog,
|
||||
setIsExploreDialogOpen,
|
||||
setHasDismissedExploreDialog,
|
||||
toggleToolSetting,
|
||||
setToolPolicy,
|
||||
clearToolPolicy,
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { selectSelectedChatModel } from "../slices/configSlice";
|
|||
import {
|
||||
acceptToolCall,
|
||||
errorToolCall,
|
||||
setInactive,
|
||||
setToolCallCalling,
|
||||
updateToolCallOutput,
|
||||
} from "../slices/sessionSlice";
|
||||
|
|
@ -30,7 +31,6 @@ export const callToolById = createAsyncThunk<
|
|||
return;
|
||||
}
|
||||
|
||||
|
||||
const selectedChatModel = selectSelectedChatModel(state);
|
||||
|
||||
if (!selectedChatModel) {
|
||||
|
|
@ -146,5 +146,7 @@ export const callToolById = createAsyncThunk<
|
|||
}),
|
||||
);
|
||||
unwrapResult(wrapped);
|
||||
} else {
|
||||
dispatch(setInactive());
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -133,6 +133,14 @@ export const enterEdit = createAsyncThunk<
|
|||
return;
|
||||
}
|
||||
|
||||
if (!state.editModeState.codeToEdit[0]) {
|
||||
extra.ideMessenger.post("showToast", [
|
||||
"info",
|
||||
"Please open a file to use Edit mode",
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch(setMainEditorContentTrigger({}));
|
||||
dispatch(setPreviousModeEditorContent(editorContent));
|
||||
|
||||
|
|
@ -148,9 +156,5 @@ export const enterEdit = createAsyncThunk<
|
|||
);
|
||||
|
||||
dispatch(setIsInEdit(true));
|
||||
|
||||
if (!state.editModeState.codeToEdit[0]) {
|
||||
extra.ideMessenger.post("edit/addCurrentSelection", undefined);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -11,9 +11,10 @@ import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
|
|||
|
||||
/**
|
||||
* This thunk is used to move a terminal command to the background
|
||||
* when the user clicks the "Continue" button in the UI
|
||||
* when the user clicks the "Move to background" link in the UI
|
||||
*
|
||||
* It marks the command as visually complete without stopping
|
||||
* It preserves all existing terminal output, marks the command as
|
||||
* visually complete, and stops listening to further output from
|
||||
* the already running process
|
||||
*/
|
||||
export const moveTerminalProcessToBackground = createAsyncThunk<
|
||||
|
|
@ -32,6 +33,12 @@ export const moveTerminalProcessToBackground = createAsyncThunk<
|
|||
return;
|
||||
}
|
||||
|
||||
// Find existing terminal output to preserve it
|
||||
const existingOutput = toolCall.output?.find(
|
||||
(item) => item.name === "Terminal",
|
||||
);
|
||||
const existingContent = existingOutput?.content || "";
|
||||
|
||||
const status =
|
||||
"Command moved to background. Further output will be ignored.";
|
||||
|
||||
|
|
@ -39,7 +46,7 @@ export const moveTerminalProcessToBackground = createAsyncThunk<
|
|||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: "\n" + status,
|
||||
content: existingContent + (existingContent ? "\n\n" : "") + status,
|
||||
status: status,
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ type LocalStorageTypes = {
|
|||
hasDismissedExploreDialog: boolean;
|
||||
onboardingStatus?: OnboardingStatus;
|
||||
hasDismissedOnboardingCard: boolean;
|
||||
mainTextEntryCounter: number;
|
||||
ide: "vscode" | "jetbrains";
|
||||
vsCodeUriScheme: string;
|
||||
ftc: number;
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue