Merge branch 'main' into tomasz/con-3426

This commit is contained in:
Tomasz Stefaniak 2025-08-13 13:23:33 -07:00
commit af8e4ec6af
63 changed files with 1306 additions and 436 deletions

View file

@ -16,7 +16,7 @@ jobs:
contents: write # Needed for creating releases
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Get version from package.json
id: get_version
@ -45,7 +45,7 @@ jobs:
contents: write # Needed for creating releases
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0

View file

@ -101,7 +101,7 @@ jobs:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
@ -134,7 +134,7 @@ jobs:
if: ${{ !github.event.pull_request.draft }}
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Check required files
run: |

View file

@ -33,7 +33,7 @@ jobs:
steps:
- name: Checkout Repository
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0 # Fetch full history for better context

View file

@ -14,7 +14,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4

View file

@ -56,7 +56,7 @@ jobs:
# steps:
# # 0. Setup git
# - name: Checkout
# uses: actions/checkout@v4
# uses: actions/checkout@v5
# - name: Set up Git
# run: |
@ -102,7 +102,7 @@ jobs:
steps:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
ref: ${{ github.event.release.tag_name }}
@ -362,7 +362,7 @@ jobs:
steps:
# 1. Check-out repository
- name: Check-out repository
uses: actions/checkout@v4
uses: actions/checkout@v5
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
@ -429,7 +429,7 @@ jobs:
steps:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
# Set up Java environment for the next steps
- name: Setup Java
@ -482,7 +482,7 @@ jobs:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
# Set up Java environment for the next steps
- name: Setup Java
@ -513,7 +513,7 @@ jobs:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
# Set up Java environment for the next steps
- name: Setup Java

View file

@ -13,7 +13,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Check if author is in tier list
id: check-author

View file

@ -18,7 +18,7 @@ jobs:
matrix:
platform: [Linux, macOS]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 2 # Get the last 2 commits to find the merge commit

View file

@ -66,7 +66,7 @@ jobs:
arch: arm64
npm_config_arch: arm64
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
@ -92,7 +92,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0 # This ensures all tags are fetched
@ -112,7 +112,7 @@ jobs:
- build
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |
@ -145,7 +145,7 @@ jobs:
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |

View file

@ -24,7 +24,7 @@ jobs:
runner: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0

View file

@ -14,7 +14,7 @@ jobs:
prettier-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -35,7 +35,7 @@ jobs:
core-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -71,7 +71,7 @@ jobs:
gui-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -101,7 +101,7 @@ jobs:
binary-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -123,7 +123,7 @@ jobs:
vscode-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -156,7 +156,7 @@ jobs:
outputs:
packages: ${{ steps.get-packages.outputs.packages }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Get package list
id: get-packages
run: |
@ -171,7 +171,7 @@ jobs:
matrix:
package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
@ -197,7 +197,7 @@ jobs:
outputs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -257,7 +257,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
@ -289,7 +289,7 @@ jobs:
test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }}
command: ["e2e:ci:run", "e2e:ci:run-yaml"]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Run VS Code E2E test
uses: ./.github/actions/run-vscode-e2e-test
with:
@ -303,7 +303,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Run JetBrains tests
uses: ./.github/actions/run-jetbrains-tests
with:

View file

@ -66,7 +66,7 @@ jobs:
arch: arm64
npm_config_arch: arm64
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
@ -96,7 +96,7 @@ jobs:
- build
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |
@ -131,7 +131,7 @@ jobs:
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |

View file

@ -47,7 +47,7 @@ jobs:
working-directory: ${{ inputs.package-path }}
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0

View file

@ -7,6 +7,8 @@ on:
jobs:
analyze:
# Disabling for now due to bugs
if: false
runs-on: ubuntu-latest
permissions:
issues: write
@ -14,30 +16,30 @@ jobs:
steps:
- name: Checkout deja-view
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
repository: 'bdougie/deja-view'
repository: "bdougie/deja-view"
# Option 1: Pin to specific commit (most secure)
ref: '45e7696' # Pin to specific commit for stability
ref: "45e7696" # Pin to specific commit for stability
# Option 2: Use a tag (recommended after creating releases)
# ref: 'v1.0.0'
# Option 3: Use main branch (least secure, gets latest changes)
# ref: 'main'
path: deja-view
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
python-version: "3.11"
- name: Install dependencies
run: |
cd deja-view
pip install -r requirements.txt
- name: Index repository if needed
env:
CHROMA_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }}
@ -46,10 +48,10 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cd deja-view
# Index the repository (this will update existing index)
python cli.py index "${{ github.repository }}" --max-issues 200 || true
- name: Search for similar issues
id: search
env:
@ -59,7 +61,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cd deja-view
# Determine if this is an issue or PR
if [ "${{ github.event_name }}" = "pull_request" ]; then
ISSUE_URL="https://github.com/${{ github.repository }}/pull/${{ github.event.pull_request.number }}"
@ -70,26 +72,26 @@ jobs:
THRESHOLD="0.7"
TOP_K="5"
fi
# Create a Python script to search and format as JSON
cat << 'PYTHON_SCRIPT' > search_similar.py
import sys
import json
import os
from github_similarity_service import SimilarityService
issue_url = sys.argv[1]
threshold = float(sys.argv[2])
top_k = int(sys.argv[3])
# Parse issue number from URL
issue_number = int(issue_url.split('/')[-1])
repo_parts = issue_url.split('/')
owner = repo_parts[3]
repo = repo_parts[4]
service = SimilarityService()
# Find similar issues
similar = service.find_similar_issues(
owner=owner,
@ -98,26 +100,26 @@ jobs:
top_k=top_k,
min_similarity=threshold
)
# Format as JSON
print(json.dumps(similar))
PYTHON_SCRIPT
# Search for similar issues
SIMILAR_ISSUES=$(python search_similar.py "$ISSUE_URL" "$THRESHOLD" "$TOP_K")
# Save to output
echo "similar_issues<<EOF" >> $GITHUB_OUTPUT
echo "$SIMILAR_ISSUES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
# Check if any similar issues found
if [ "$(echo "$SIMILAR_ISSUES" | jq '. | length')" -gt 0 ]; then
echo "has_similar=true" >> $GITHUB_OUTPUT
else
echo "has_similar=false" >> $GITHUB_OUTPUT
fi
- name: Check if issue should be a discussion
id: discussion_check
if: github.event_name == 'issues'
@ -128,19 +130,19 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cd deja-view
# Create a Python script to analyze the issue
cat << 'PYTHON_SCRIPT' > check_discussion.py
import os
import json
import re
from github_similarity_service import SimilarityService
# Get issue details from environment
issue_title = os.environ.get('ISSUE_TITLE', '')
issue_body = os.environ.get('ISSUE_BODY', '')
issue_labels = json.loads(os.environ.get('ISSUE_LABELS', '[]'))
# Mock Issue object for analysis
class MockIssue:
def __init__(self):
@ -152,41 +154,41 @@ jobs:
self.created_at = ''
self.updated_at = ''
self.url = ''
service = SimilarityService()
issue = MockIssue()
score, reasons = service._calculate_discussion_score(issue)
result = {
'score': score,
'reasons': reasons,
'should_be_discussion': score >= 0.5,
'confidence': 'high' if score >= 0.7 else 'medium' if score >= 0.5 else 'low'
}
print(json.dumps(result))
PYTHON_SCRIPT
# Run the analysis
DISCUSSION_ANALYSIS=$(ISSUE_TITLE="${{ github.event.issue.title }}" \
ISSUE_BODY='${{ github.event.issue.body }}' \
ISSUE_LABELS='${{ toJson(github.event.issue.labels.*.name) }}' \
ISSUE_NUMBER="${{ github.event.issue.number }}" \
python check_discussion.py)
echo "analysis<<EOF" >> $GITHUB_OUTPUT
echo "$DISCUSSION_ANALYSIS" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
# Extract whether it should be a discussion
SHOULD_BE_DISCUSSION=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.should_be_discussion')
echo "should_be_discussion=$SHOULD_BE_DISCUSSION" >> $GITHUB_OUTPUT
# Extract confidence level
CONFIDENCE=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.confidence')
echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT
- name: Comment with analysis
uses: actions/github-script@v7
with:
@ -195,7 +197,7 @@ jobs:
const hasSimilar = '${{ steps.search.outputs.has_similar }}' === 'true';
const isPR = '${{ github.event_name }}' === 'pull_request';
const shouldBeDiscussion = !isPR && '${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true';
// Add similar issues section if found
if (hasSimilar) {
const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`);
@ -243,7 +245,7 @@ jobs:
comment += '\n';
}
}
// Add discussion suggestion if applicable
if (shouldBeDiscussion) {
const analysis = JSON.parse(`${{ steps.discussion_check.outputs.analysis }}`);
@ -280,7 +282,7 @@ jobs:
comment += '_Consider converting this to a discussion if it\'s not a bug report or actionable task._\n';
}
// Only comment if we have something to say
if (comment) {
comment += '\n---\n';
@ -302,14 +304,14 @@ jobs:
});
}
}
- name: Add labels
if: github.event_name == 'issues'
uses: actions/github-script@v7
with:
script: |
const labels = [];
// Check for duplicate
if ('${{ steps.search.outputs.has_similar }}' === 'true') {
const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`);
@ -319,7 +321,7 @@ jobs:
labels.push('potential-duplicate');
}
}
// Check for discussion suggestion
if ('${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true') {
const confidence = '${{ steps.discussion_check.outputs.confidence }}';
@ -330,7 +332,7 @@ jobs:
labels.push('discussion');
}
}
// Add labels if any
if (labels.length > 0) {
await github.rest.issues.addLabels({

View file

@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Setup Java
uses: actions/setup-java@v4
with:

View file

@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0 # Fetch all history and tags

View file

@ -428,6 +428,7 @@ async function configYamlToContinueConfig(options: {
timeout: server.connectionTimeout,
})),
false,
{ ide },
);
return { config: continueConfig, errors: localErrors };

View file

@ -1,12 +1,16 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import {
SSEClientTransport,
SseError,
} from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import {
IDE,
MCPConnectionStatus,
MCPOptions,
MCPPrompt,
@ -16,6 +20,7 @@ import {
MCPTool,
} from "../..";
import { getEnvPathFromUserShell } from "../../util/shellPath";
import { getOauthToken } from "./MCPOauth";
const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds
@ -30,10 +35,23 @@ const WINDOWS_BATCH_COMMANDS = [
"bunx",
];
function is401Error(error: unknown) {
return (
(error instanceof SseError && error.code === 401) ||
(error instanceof Error && error.message.includes("401")) ||
(error instanceof Error && error.message.includes("Unauthorized"))
);
}
export type MCPExtras = {
ide: IDE;
};
class MCPConnection {
public client: Client;
public abortController: AbortController;
public status: MCPConnectionStatus = "not-connected";
public isProtectedResource = false;
public errors: string[] = [];
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
@ -46,7 +64,10 @@ class MCPConnection {
stderr: "",
};
constructor(public options: MCPOptions) {
constructor(
public options: MCPOptions,
public extras?: MCPExtras,
) {
// Don't construct transport in constructor to avoid blocking
this.transport = {} as Transport; // Will be set in connectClient
@ -78,6 +99,7 @@ class MCPConnection {
resourceTemplates: this.resourceTemplates,
tools: this.tools,
status: this.status,
isProtectedResource: this.isProtectedResource,
};
}
@ -106,6 +128,26 @@ class MCPConnection {
this.abortController.abort();
this.abortController = new AbortController();
// currently support oauth for sse transports only
if (this.options.transport.type === "sse") {
if (!this.options.transport.requestOptions) {
this.options.transport.requestOptions = {
headers: {},
};
}
const accessToken = await getOauthToken(
this.options.transport.url,
this.extras?.ide!,
);
if (accessToken) {
this.isProtectedResource = true;
this.options.transport.requestOptions.headers = {
...this.options.transport.requestOptions.headers,
Authorization: `Bearer ${accessToken}`,
};
}
}
this.connectionPromise = Promise.race([
// If aborted by a refresh or other, cancel and don't do anything
new Promise((resolve) => {
@ -244,6 +286,10 @@ class MCPConnection {
}
}
if (is401Error(error)) {
this.isProtectedResource = true;
}
// Include stdio output if available for stdio transport
if (
this.options.transport.type === "stdio" &&

View file

@ -1,7 +1,6 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
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", () => ({
@ -143,6 +142,7 @@ describe("MCPConnection", () => {
expect(status).toEqual({
...options,
errors: [],
isProtectedResource: false,
prompts: [],
resources: [],
resourceTemplates: [],

View file

@ -6,7 +6,7 @@ import {
StdioOptions,
TransportOptions,
} from "../..";
import MCPConnection from "./MCPConnection";
import MCPConnection, { MCPExtras } from "./MCPConnection";
export class MCPManagerSingleton {
private static instance: MCPManagerSingleton;
@ -26,12 +26,12 @@ export class MCPManagerSingleton {
}
createConnection(id: string, options: MCPOptions): MCPConnection {
if (!this.connections.has(id)) {
if (this.connections.has(id)) {
return this.connections.get(id)!;
} else {
const connection = new MCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
return this.connections.get(id)!;
}
}
@ -48,7 +48,11 @@ export class MCPManagerSingleton {
this.connections.delete(id);
}
setConnections(servers: MCPOptions[], forceRefresh: boolean) {
setConnections(
servers: MCPOptions[],
forceRefresh: boolean,
extras?: MCPExtras,
) {
let refresh = false;
// Remove any connections that are no longer in config
@ -73,15 +77,15 @@ export class MCPManagerSingleton {
// Add any connections that are not yet in manager
servers.forEach((server) => {
if (!this.connections.has(server.id)) {
refresh = true;
this.connections.set(server.id, new MCPConnection(server));
} else {
if (this.connections.has(server.id)) {
const conn = this.connections.get(server.id);
if (conn) {
// We need to update it. Some attributes may have changed, such as name, faviconUrl, etc.
conn.options = server;
}
} else {
refresh = true;
this.connections.set(server.id, new MCPConnection(server, extras));
}
});
@ -162,6 +166,10 @@ export class MCPManagerSingleton {
}));
}
setStatus(server: MCPServerStatus, status: MCPServerStatus["status"]) {
this.connections.get(server.id)!.status = status;
}
async getPrompt(
serverName: string,
promptName: string,

View file

@ -0,0 +1,227 @@
import {
OAuthClientProvider,
auth,
} from "@modelcontextprotocol/sdk/client/auth.js";
import {
OAuthClientInformationFull,
OAuthClientInformationSchema,
OAuthTokens,
OAuthTokensSchema,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import { IDE, MCPServerStatus, SSEOptions } from "../..";
import http from "http";
import url from "url";
import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
let authenticatingMCPContext = null as {
authenticatingServer: MCPServerStatus;
ide: IDE;
} | null;
const PORT = 3000;
const server = http.createServer((req, res) => {
try {
if (!req.url) {
throw new Error("no url found");
}
const parsedUrl = url.parse(req.url, true);
if (!parsedUrl.query["code"]) {
throw new Error("no query params found");
}
void handleMCPOauthCode(parsedUrl.query["code"] as string);
const html = `
<!DOCTYPE html>
<html>
<head><title>Authentication Complete</title></head>
<body>Authentication Complete. You can close this page now.</body>
</html>`;
res.writeHead(200, {
"Content-Type": "text/html",
});
res.end(html);
} catch (error) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end(`Unexpected redirect error: ${(error as Error).message}`);
}
});
type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string];
type MCPOauthStorageKey = keyof MCPOauthStorage;
class MCPConnectionOauthProvider implements OAuthClientProvider {
private globalContext: GlobalContext;
constructor(
public oauthServerUrl: string,
private ide: IDE,
) {
this.globalContext = new GlobalContext();
}
get redirectUrl() {
return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server?
}
get clientMetadata() {
return {
redirect_uris: [this.redirectUrl],
token_endpoint_auth_method: "none",
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
client_name: "Continue Dev, Inc", // get this from package.json?
client_uri: "https://continue.dev", // get this from package.json?
};
}
private _getOauthStorage<K extends MCPOauthStorageKey>(key: K) {
return this.globalContext.get("mcpOauthStorage")?.[this.oauthServerUrl]?.[
key
];
}
private _updateOauthStorage<K extends MCPOauthStorageKey>(
key: K,
value: MCPOauthStorage[K],
) {
const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
const existingServerStorage = existingStorage[this.oauthServerUrl] ?? {};
this.globalContext.update("mcpOauthStorage", {
...existingStorage,
[this.oauthServerUrl]: {
...existingServerStorage,
[key]: value,
},
});
}
private _clearOauthStorage() {
const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
delete existingStorage[this.oauthServerUrl];
this.globalContext.update("mcpOauthStorage", existingStorage);
}
saveClientInformation(clientInformation: OAuthClientInformationFull) {
this._updateOauthStorage("clientInformation", clientInformation);
}
async clientInformation() {
const existingClientInformation =
this._getOauthStorage("clientInformation");
if (!existingClientInformation) {
return undefined;
}
return await OAuthClientInformationSchema.parseAsync(
existingClientInformation,
);
}
async tokens() {
const existingTokens = this._getOauthStorage("tokens");
if (!existingTokens) {
return undefined;
}
return await OAuthTokensSchema.parseAsync(existingTokens);
}
saveTokens(tokens: OAuthTokens) {
this._updateOauthStorage("tokens", tokens);
}
codeVerifier(): string | Promise<string> {
const existingCodeVerifier = this._getOauthStorage("codeVerifier");
if (!existingCodeVerifier) {
return "";
}
return existingCodeVerifier;
}
saveCodeVerifier(codeVerifier: string) {
this._updateOauthStorage("codeVerifier", codeVerifier);
}
clear() {
this._clearOauthStorage();
}
async redirectToAuthorization(authorizationUrl: URL) {
if (!server.listening) {
server.listen(PORT, () => {
console.debug(
`Server started for MCP Oauth process at http://localhost:${PORT}/`,
);
});
}
void this.ide.openUrl(authorizationUrl.toString());
}
}
export async function getOauthToken(mcpServerUrl: string, ide: IDE) {
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
const tokens = await authProvider.tokens();
return tokens?.access_token;
}
/**
* checks if the authentication is already done for the current server
* if not, starts the authentication process by opening a webpage url
*/
export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
authenticatingMCPContext = {
authenticatingServer: mcpServer,
ide,
};
return await auth(authProvider, {
serverUrl: mcpServerUrl,
});
}
/**
* handle the authentication code received from the oauth redirect
*/
async function handleMCPOauthCode(authorizationCode: string) {
if (!authenticatingMCPContext) {
return;
}
const { ide, authenticatingServer } = authenticatingMCPContext;
const serverUrl = (authenticatingServer.transport as SSEOptions).url;
if (!serverUrl) {
void ide.showToast("error", "No MCP server url found for authentication");
return;
}
if (!authorizationCode) {
void ide.showToast(
"error",
`No MCP authorization code found for ${serverUrl}`,
);
return;
}
server.close(() => console.debug("Server for MCP Oauth process was closed"));
const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
const authStatus = await auth(authProvider, {
serverUrl,
authorizationCode,
});
if (authStatus === "AUTHORIZED") {
const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports
await MCPManagerSingleton.getInstance().refreshConnection(
authenticatingServer.id,
);
}
authenticatingMCPContext = null;
}
export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) {
const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
authProvider.clear();
}

View file

@ -0,0 +1,181 @@
import fs from "node:fs";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { GlobalContext } from "../../util/GlobalContext";
import { getGlobalContextFilePath } from "../../util/paths";
import { getOauthToken, performAuth, removeMCPAuth } from "./MCPOauth";
// Mock the MCP SDK auth module
vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
auth: vi.fn(),
}));
// Mock the MCPManagerSingleton to avoid circular imports
vi.mock("./MCPManagerSingleton", () => ({
MCPManagerSingleton: {
getInstance: vi.fn(() => ({
refreshConnection: vi.fn(),
})),
},
}));
describe("MCPOauth", () => {
let globalContextFilePath: string;
let mockIde: any;
let mockMcpServer: any;
beforeEach(() => {
// file is present in the core/test directory
globalContextFilePath = getGlobalContextFilePath();
if (fs.existsSync(globalContextFilePath)) {
fs.unlinkSync(globalContextFilePath);
}
mockIde = {
openUrl: vi.fn(),
showToast: vi.fn(),
};
mockMcpServer = {
id: "test-server",
transport: {
type: "sse",
url: "https://test-server.com",
},
};
vi.clearAllMocks();
});
afterEach(() => {
if (fs.existsSync(globalContextFilePath)) {
fs.unlinkSync(globalContextFilePath);
}
});
describe("getOauthToken", () => {
test("should return undefined when no tokens are stored", async () => {
const result = await getOauthToken("https://test-server.com", mockIde);
expect(result).toBeUndefined();
});
test("should return access token when tokens are stored", async () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://test-server.com": {
tokens: {
access_token: "test-access-token",
token_type: "Bearer",
},
},
});
const result = await getOauthToken("https://test-server.com", mockIde);
expect(result).toBe("test-access-token");
});
test("should handle different server URLs independently", async () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://server1.com": {
tokens: {
access_token: "token1",
token_type: "Bearer",
},
},
"https://server2.com": {
tokens: {
access_token: "token2",
token_type: "Bearer",
},
},
});
const result1 = await getOauthToken("https://server1.com", mockIde);
const result2 = await getOauthToken("https://server2.com", mockIde);
const result3 = await getOauthToken("https://server3.com", mockIde);
expect(result1).toBe("token1");
expect(result2).toBe("token2");
expect(result3).toBeUndefined();
});
});
describe("performAuth", () => {
test("should call auth with correct parameters and return auth result", async () => {
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
const result = await performAuth(mockMcpServer, mockIde);
expect(mockAuth).toHaveBeenCalledWith(
expect.any(Object), // MCPConnectionOauthProvider instance
{
serverUrl: "https://test-server.com",
},
);
expect(result).toBe("AUTHORIZED");
});
});
describe("removeMCPAuth", () => {
test("should clear oauth storage for the server", () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://test-server.com": {
tokens: {
access_token: "test-access-token",
token_type: "Bearer",
},
clientInformation: {
client_id: "test-client-id",
redirect_uris: ["http://localhost:3000"],
},
codeVerifier: "test-code-verifier",
},
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
removeMCPAuth(mockMcpServer, mockIde);
const updatedStorage = globalContext.get("mcpOauthStorage");
expect(updatedStorage).toEqual({
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
});
test("should handle non-existent server gracefully", () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
removeMCPAuth(mockMcpServer, mockIde);
const updatedStorage = globalContext.get("mcpOauthStorage");
expect(updatedStorage).toEqual({
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
});
});
});

View file

@ -43,9 +43,13 @@ class DocsContextProvider extends BaseContextProvider {
try {
const scores = await reranker.rerank(fullInput, chunksCopy);
chunksCopy.sort(
(a, b) => scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
);
if (Array.isArray(scores)) {
// reranker model has returned a valid array
chunksCopy.sort(
(a, b) =>
scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
);
}
chunksCopy = chunksCopy.splice(
0,

View file

@ -27,7 +27,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
let embeddingsChunks: Chunk[] = [];
try {
embeddingsChunks = !!config.selectedModelByRole.embed
embeddingsChunks = Boolean(config.selectedModelByRole.embed)
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
} catch (error) {
@ -116,7 +116,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
const chunkIndexMap = new Map<Chunk, number>();
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
results.sort(
results?.sort(
(a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!],
);
results = results.slice(0, this.options.nFinal);

View file

@ -61,6 +61,7 @@ import {
} from "./config/onboarding";
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth";
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
import { ApplyAbortManager } from "./edit/applyAbortManager";
import { streamDiffLines } from "./edit/streamDiffLines";
@ -76,6 +77,7 @@ import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { OnboardingModes } from "./protocol/core";
import type { IMessenger, Message } from "./protocol/messenger";
import { getUriPathBasename } from "./util/uri";
import { PrefetchQueue } from "./nextEdit/NextEditPrefetchQueue";
const hasRulesFiles = (uris: string[]): boolean => {
for (const uri of uris) {
@ -417,6 +419,19 @@ export class Core {
description: prompt.description,
};
});
on("mcp/startAuthentication", async (msg) => {
await new Promise((resolve) => setTimeout(resolve, 5000));
MCPManagerSingleton.getInstance().setStatus(msg.data, "authenticating");
const status = await performAuth(msg.data, this.ide);
if (status === "AUTHORIZED") {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
}
});
on("mcp/removeAuthentication", async (msg) => {
removeMCPAuth(msg.data, this.ide);
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
});
// Context providers
on("context/addDocs", async (msg) => {
void this.docsService.indexAndAdd(msg.data);
@ -578,18 +593,80 @@ export class Core {
// Next Edit
on("nextEdit/predict", async (msg) => {
const outcome = await this.nextEditProvider.provideInlineCompletionItems(
msg.data,
msg.data.input,
undefined,
{ withChain: false, usingFullFileDiff: true },
{
withChain: msg.data.options?.withChain ?? false,
usingFullFileDiff: msg.data.options?.usingFullFileDiff ?? true,
},
);
return outcome ? [outcome.completion, outcome.originalEditableRange] : [];
return outcome;
// ? [outcome.completion, outcome.originalEditableRange]
});
on("nextEdit/accept", async (msg) => {
console.log("nextEdit/accept");
this.nextEditProvider.accept(msg.data.completionId);
});
on("nextEdit/reject", async (msg) => {
console.log("nextEdit/reject");
this.nextEditProvider.reject(msg.data.completionId);
});
on("nextEdit/startChain", async (msg) => {
console.log("nextEdit/startChain");
NextEditProvider.getInstance().startChain();
return;
});
on("nextEdit/deleteChain", async (msg) => {
console.log("nextEdit/deleteChain");
await NextEditProvider.getInstance().deleteChain();
return;
});
on("nextEdit/isChainAlive", async (msg) => {
console.log("nextEdit/isChainAlive");
return NextEditProvider.getInstance().chainExists();
});
on("nextEdit/queue/getProcessedCount", async (msg) => {
console.log("nextEdit/queue/getProcessedCount");
const queue = PrefetchQueue.getInstance();
console.log(queue.processedCount);
return queue.processedCount;
});
on("nextEdit/queue/dequeueProcessed", async (msg) => {
console.log("nextEdit/queue/dequeueProcessed");
const queue = PrefetchQueue.getInstance();
return queue.dequeueProcessed() || null;
});
on("nextEdit/queue/processOne", async (msg) => {
console.log("nextEdit/queue/processOne");
const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data;
const queue = PrefetchQueue.getInstance();
await queue.process({
...ctx,
recentlyVisitedRanges,
recentlyEditedRanges,
});
return;
});
on("nextEdit/queue/clear", async (msg) => {
console.log("nextEdit/queue/clear");
const queue = PrefetchQueue.getInstance();
queue.clear();
return;
});
on("nextEdit/queue/abort", async (msg) => {
console.log("nextEdit/queue/abort");
const queue = PrefetchQueue.getInstance();
queue.abort();
return;
});
on("streamDiffLines", async (msg) => {
const { config } = await this.configHandler.loadConfig();

2
core/index.d.ts vendored
View file

@ -1278,6 +1278,7 @@ export type MCPConnectionStatus =
| "connecting"
| "connected"
| "error"
| "authenticating"
| "not-connected";
export type MCPPromptArgs = {
@ -1323,6 +1324,7 @@ export interface MCPTool {
export interface MCPServerStatus extends MCPOptions {
status: MCPConnectionStatus;
errors: string[];
isProtectedResource: boolean;
prompts: MCPPrompt[];
tools: MCPTool[];

View file

@ -56,7 +56,7 @@ export class CodebaseIndexer {
// and only need to `await` it for tests.
public initPromise: Promise<void>;
private config!: ContinueConfig;
private indexingCancellationController: AbortController | undefined;
private indexingCancellationController: AbortController;
private codebaseIndexingState: IndexingProgressUpdate;
private readonly pauseToken: PauseToken;
@ -97,6 +97,9 @@ export class CodebaseIndexer {
this.pauseToken = new PauseToken(initialPaused);
this.initPromise = this.init(configHandler);
this.indexingCancellationController = new AbortController();
this.indexingCancellationController.abort(); // initialize and abort so that a new one can be created
}
// Initialization - load config and attach config listener
@ -693,7 +696,7 @@ export class CodebaseIndexer {
}
public async refreshCodebaseIndex(paths: string[]) {
if (this.indexingCancellationController) {
if (!this.indexingCancellationController.signal.aborted) {
this.indexingCancellationController.abort();
}
const localController = new AbortController();
@ -735,16 +738,13 @@ export class CodebaseIndexer {
});
}
if (this.indexingCancellationController === localController) {
this.indexingCancellationController = undefined;
this.indexingCancellationController.abort();
}
}
public async refreshCodebaseIndexFiles(files: string[]) {
// Can be cancelled by codebase index but not vice versa
if (
this.indexingCancellationController &&
!this.indexingCancellationController.signal.aborted
) {
if (!this.indexingCancellationController.signal.aborted) {
return;
}
const localController = new AbortController();
@ -770,7 +770,7 @@ export class CodebaseIndexer {
});
}
if (this.indexingCancellationController === localController) {
this.indexingCancellationController = undefined;
this.indexingCancellationController.abort();
}
}

View file

@ -178,7 +178,7 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired(
// update core/nextEdit/templating/NextEditPromptEngine.ts as well.
const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
NEXT_EDIT_MODELS.MODEL_1,
NEXT_EDIT_MODELS.INSTINCT,
];
function modelSupportsNextEdit(

View file

@ -245,8 +245,10 @@ describe("modelSupportsNextEdit", () => {
).toBe(true);
});
it("should return true for model-1", () => {
expect(modelSupportsNextEdit(undefined, "model-1", undefined)).toBe(true);
it("should return true for instinct", () => {
expect(modelSupportsNextEdit(undefined, "instinct", undefined)).toBe(
true,
);
});
it("should return true when model contains supported model name as substring", () => {
@ -269,9 +271,9 @@ describe("modelSupportsNextEdit", () => {
).toBe(true);
});
it("should return true when title contains model-1", () => {
it("should return true when title contains instinct", () => {
expect(
modelSupportsNextEdit(undefined, "some-model", "model-1 deployment"),
modelSupportsNextEdit(undefined, "some-model", "instinct deployment"),
).toBe(true);
});
@ -317,7 +319,7 @@ describe("modelSupportsNextEdit", () => {
it("should handle case sensitivity correctly", () => {
expect(
modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "MODEL-1"),
modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"),
).toBe(true);
});

View file

@ -21,7 +21,7 @@ export enum LLMConfigurationStatuses {
export enum NEXT_EDIT_MODELS {
MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
MODEL_1 = "model-1",
INSTINCT = "instinct",
}
export {

View file

@ -1,7 +1,21 @@
import { Chunk, LLMOptions } from "../../index.js";
import { z } from "zod";
import { Chunk, LLMOptions } from "../../index.js";
import OpenAI from "./OpenAI.js";
/**used to check a valid response from voyage is received
* reference: https://docs.voyageai.com/reference/reranker-api
*/
const VoyageRerankSuccessResponseSchema = z.object({
data: z.array(
z.object({
index: z.number(),
relevance_score: z.number(),
document: z.string(),
}),
),
});
class Voyage extends OpenAI {
static providerName = "voyage";
static defaultOptions: Partial<LLMOptions> | undefined = {
@ -36,7 +50,10 @@ class Voyage extends OpenAI {
const data = (await resp.json()) as {
data: Array<{ index: number; relevance_score: number }>;
};
const results = data.data.sort((a, b) => a.index - b.index);
const parsedData = VoyageRerankSuccessResponseSchema.parse(data);
const results = parsedData.data.sort((a, b) => a.index - b.index);
return results.map((result) => result.relevance_score);
}
}

View file

@ -1,11 +1,9 @@
import Parser from "web-tree-sitter";
import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from "..";
import { getAst } from "../autocomplete/util/ast";
import { NEXT_EDIT_MODELS } from "../llm/constants";
import { DocumentHistoryTracker } from "./DocumentHistoryTracker";
import {
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "./constants";
import { MODEL_WINDOW_SIZES } from "./constants";
export enum EditableRegionStrategy {
Naive = "naive",
@ -60,16 +58,16 @@ function naiveJump(ctx: any): RangeInFile[] | null {
// Sliding splits the file using into sliding window.
function slidingJump(ctx: any): RangeInFile[] | null {
const { fileLines, filepath } = ctx;
if (!fileLines || !filepath) {
console.warn("Missing required context for naive jump");
const { fileLines, filepath, modelName, currentCursorPos } = ctx;
if (!fileLines || !filepath || !modelName || !currentCursorPos) {
console.warn("Missing required context for sliding jump");
return null;
}
const windowSize =
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN +
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN +
1; // 1 for current line;
const topMargin = MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].topMargin;
const bottomMargin =
MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].bottomMargin;
const windowSize = topMargin + bottomMargin + 1; // 1 for current line
if (fileLines.length <= windowSize) {
return [
@ -86,29 +84,74 @@ function slidingJump(ctx: any): RangeInFile[] | null {
];
}
const slidingStep = Math.max(1, Math.floor(windowSize / 2));
const ranges: RangeInFile[] = [];
const cursorLine = currentCursorPos.line;
for (
let startLine = 0;
startLine < fileLines.length;
startLine += slidingStep
) {
const endLine = Math.min(startLine + windowSize - 1, fileLines.length - 1);
// Create the first window centered around the cursor position
const firstWindowStart = Math.max(0, cursorLine - topMargin);
const firstWindowEnd = Math.min(
fileLines.length - 1,
cursorLine + bottomMargin,
);
ranges.push({
filepath,
range: {
start: { line: startLine, character: 0 },
end: {
line: endLine,
character: fileLines[endLine].length,
},
ranges.push({
filepath,
range: {
start: { line: firstWindowStart, character: 0 },
end: {
line: firstWindowEnd,
character: fileLines[firstWindowEnd].length,
},
});
},
});
if (endLine >= fileLines.length - 1) {
break;
// Alternating pattern: down once, up once, repeat
const slidingStep = Math.max(1, Math.floor(windowSize / 2));
let currentStartDown = firstWindowEnd + 1;
let currentStartUp = firstWindowStart - slidingStep;
while (currentStartDown < fileLines.length || currentStartUp >= 0) {
// Go down once
if (currentStartDown < fileLines.length) {
const windowStart = currentStartDown;
const windowEnd = Math.min(
windowStart + windowSize - 1,
fileLines.length - 1,
);
ranges.push({
filepath,
range: {
start: { line: windowStart, character: 0 },
end: {
line: windowEnd,
character: fileLines[windowEnd].length,
},
},
});
currentStartDown += slidingStep;
}
// Go up once
if (currentStartUp >= 0) {
const windowStart = Math.max(0, currentStartUp);
const windowEnd = Math.min(
windowStart + windowSize - 1,
fileLines.length - 1,
);
ranges.push({
filepath,
range: {
start: { line: windowStart, character: 0 },
end: {
line: windowEnd,
character: fileLines[windowEnd].length,
},
},
});
currentStartUp -= slidingStep;
}
}

View file

@ -2,7 +2,7 @@ import { RangeInFile } from "..";
import { NextEditProvider } from "./NextEditProvider";
import { NextEditOutcome } from "./types";
interface ProcessedItem {
export interface ProcessedItem {
location: RangeInFile;
outcome: NextEditOutcome; // Result from the model
}
@ -59,6 +59,11 @@ export class PrefetchQueue {
!this.abortController.signal.aborted
) {
const location = this.dequeueUnprocessed();
console.log("processing:");
console.log(
location?.range.start.line + " to " + location?.range.end.line,
);
if (!location) break;
try {
@ -70,12 +75,20 @@ export class PrefetchQueue {
this.usingFullFileDiff,
);
if (!outcome) continue;
if (!outcome) {
console.log("outcome is undefined");
continue;
}
this.enqueueProcessed({
location,
outcome,
});
console.log(
"the length of processed queue after processing is:",
this.processedQueue.length,
);
} catch (error) {
if (!this.abortController.signal.aborted) {
// Handle error
@ -115,6 +128,16 @@ export class PrefetchQueue {
return this.processedQueue[0];
}
peekThreeProcessed(): void {
const count = Math.min(3, this.processedQueue.length);
const firstThree = this.processedQueue.slice(0, count);
firstThree.forEach((item, index) => {
console.log(
`Item ${index + 1}: ${item.location.range.start.line} to ${item.location.range.end.line}`,
);
});
}
setPreetchLimit(limit: number): void {
this.prefetchLimit = limit;
}

View file

@ -35,11 +35,10 @@ import { countTokens } from "../llm/countTokens.js";
import { localPathOrUriToPath } from "../util/pathToUri.js";
import { replaceEscapedCharacters } from "../util/text.js";
import {
INSTINCT_SYSTEM_PROMPT,
MERCURY_CODE_TO_EDIT_OPEN,
MERCURY_SYSTEM_PROMPT,
MODEL_1_SYSTEM_PROMPT,
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
MODEL_WINDOW_SIZES,
} from "./constants.js";
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
import {
@ -83,7 +82,7 @@ export class NextEditProvider {
private loggingService: NextEditLoggingService;
private contextRetrievalService: ContextRetrievalService;
private endpointType: "default" | "fineTuned";
private diffContext: string = "";
private diffContext: string[] = [];
private autocompleteContext: string = "";
private promptMetadata: PromptMetadata | null = null;
private currentEditChainId: string | null = null;
@ -136,7 +135,10 @@ export class NextEditProvider {
}
public addDiffToContext(diff: string): void {
this.diffContext = diff;
this.diffContext.push(diff);
if (this.diffContext.length > 5) {
this.diffContext.shift();
}
}
public addAutocompleteContext(ctx: string): void {
@ -390,16 +392,20 @@ export class NextEditProvider {
this.ide.getWorkspaceDirs(),
]);
const modelName = helper.modelName.includes("mercury-coder-nextedit")
? "mercury-coder-nextedit"
: "instinct";
const { editableRegionStartLine, editableRegionEndLine } =
opts?.usingFullFileDiff
? this._calculateOptimalEditableRegion(helper, "tokenizer")
: {
editableRegionStartLine: Math.max(
helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin,
0,
),
editableRegionEndLine: Math.min(
helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin,
helper.fileLines.length - 1,
),
};
@ -558,7 +564,7 @@ export class NextEditProvider {
editDiffHistory: this.diffContext,
currentFilePath: helper.filepath,
};
} else if (modelName.includes("model-1")) {
} else if (modelName.includes("instinct")) {
// Calculate the window around the cursor position (25 lines above and below).
const windowStart = Math.max(0, helper.pos.line - 25);
const windowEnd = Math.min(
@ -566,23 +572,29 @@ export class NextEditProvider {
helper.pos.line + 25,
);
// The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive).
const actualEditableStart = Math.max(0, helper.pos.line - 1);
const actualEditableEnd = Math.min(
helper.fileLines.length - 1,
helper.pos.line + 5,
);
// // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive).
// const actualEditableStart = Math.max(
// 0,
// helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin,
// );
// const actualEditableEnd = Math.min(
// helper.fileLines.length - 1,
// helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin,
// );
// Ensure editable region boundaries are within the window.
const adjustedEditableStart = Math.max(windowStart, actualEditableStart);
const adjustedEditableEnd = Math.min(windowEnd, actualEditableEnd);
const adjustedEditableStart = Math.max(
windowStart,
editableRegionStartLine,
);
const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine);
ctx = {
contextSnippets: this.autocompleteContext,
currentFileContent: helper.fileContents,
windowStart,
windowEnd,
adjustedEditableStart,
adjustedEditableEnd,
editableRegionStartLine: adjustedEditableStart,
editableRegionEndLine: adjustedEditableEnd,
editDiffHistory: this.diffContext,
currentFilePath: helper.filepath,
languageShorthand: helper.lang.name,
@ -598,7 +610,7 @@ export class NextEditProvider {
role: "system",
content: modelName.includes("mercury-coder-nextedit")
? MERCURY_SYSTEM_PROMPT
: MODEL_1_SYSTEM_PROMPT,
: INSTINCT_SYSTEM_PROMPT,
};
return [systemPrompt, promptMetadata.prompt];
@ -666,6 +678,8 @@ export class NextEditProvider {
if (!llm) return undefined;
const msg: ChatMessage = await llm.chat(prompts, token);
console.log("message");
console.log(msg.content);
if (typeof msg.content !== "string") {
return undefined;
@ -677,16 +691,17 @@ export class NextEditProvider {
? replaceEscapedCharacters(
msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1],
).replace(/\n$/, "")
: "";
: replaceEscapedCharacters(msg.content);
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
return await this._handlePartialFileDiff(
// we could use fillFileDiff
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
editableRegionStartLine,
editableRegionEndLine,
);
} else {
return await this._handleFullFileDiff(
@ -702,11 +717,11 @@ export class NextEditProvider {
private async _handlePartialFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
editableRegionStartLine: number,
editableRegionEndLine: number,
): Promise<NextEditOutcome | undefined> {
const oldEditRangeSlice = helper.fileContents
.split("\n")
@ -1016,6 +1031,7 @@ export class NextEditProvider {
try {
const previousOutcome = this.getPreviousCompletion();
if (!previousOutcome) {
console.log("previousOutcome is undefined");
return undefined;
}
@ -1026,6 +1042,7 @@ export class NextEditProvider {
ctx,
);
if (!input) {
console.log("input is undefined");
return undefined;
}

View file

@ -1,14 +1,27 @@
import { NEXT_EDIT_MODELS } from "../llm/constants";
export const IS_NEXT_EDIT_ACTIVE = false;
export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 0;
export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
export const MODEL_WINDOW_SIZES: Record<
NEXT_EDIT_MODELS,
{ topMargin: number; bottomMargin: number }
> = {
"mercury-coder-nextedit": {
topMargin: 0,
bottomMargin: 5,
}, // mercury coder nextedit uses full file diff, so this should be unnecessary
instinct: { topMargin: 1, bottomMargin: 5 },
};
// Model 1-specific tokens.
export const MODEL_1_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
export const MODEL_1_CONTEXT_FILE_TOKEN = "<|context_file|>";
export const MODEL_1_SNIPPET_TOKEN = "<|snippet|>";
export const MODEL_1_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags.
export const INSTINCT_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
export const INSTINCT_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
export const INSTINCT_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
export const INSTINCT_CONTEXT_FILE_TOKEN = "<|context_file|>";
export const INSTINCT_SNIPPET_TOKEN = "<|snippet|>";
export const INSTINCT_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags.
You have access to the following information to help you make informed suggestions:
@ -31,7 +44,7 @@ Your task is to predict and complete the changes the developer would have made n
- Provide only the revised code within the tags. Do not include the tags in your output.
- Ensure that you do not output duplicate code that exists outside of these tags.
- Avoid undoing or reverting the developer's last change unless there are obvious typos or errors.`;
export const MODEL_1_USER_PROMPT_PREFIX =
export const INSTINCT_USER_PROMPT_PREFIX =
"Reference the user excerpt, user edits, and the snippets to understand the developer's intent. Update the editable region of the user excerpt by predicting and completing the changes they would have made next. This may be a deletion, addition, or modification of code.";
// Mercury Coder Next Edit-specific tokens.

View file

@ -4,35 +4,33 @@ import { SnippetPayload } from "../../autocomplete/snippets";
import { HelperVars } from "../../autocomplete/util/HelperVars";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
import {
INSTINCT_USER_PROMPT_PREFIX,
MERCURY_CURRENT_FILE_CONTENT_CLOSE,
MERCURY_CURRENT_FILE_CONTENT_OPEN,
MERCURY_CURSOR,
MERCURY_EDIT_DIFF_HISTORY_CLOSE,
MERCURY_EDIT_DIFF_HISTORY_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
MODEL_1_USER_PROMPT_PREFIX,
} from "../constants";
import {
InstinctTemplateVars,
MercuryTemplateVars,
Model1TemplateVars,
NextEditTemplate,
PromptMetadata,
SystemPrompt,
TemplateVars,
UserPrompt,
} from "../types";
import {
contextSnippetsBlock,
currentFileContentBlock as instinctCurrentFileContentBlock,
editHistoryBlock as instinctEditHistoryBlock,
} from "./instinct";
import {
currentFileContentBlock,
editHistoryBlock,
recentlyViewedCodeSnippetsBlock,
} from "./mercuryCoderNextEdit";
import {
contextSnippetsBlock,
currentFileContentBlock as model1CurrentFileContentBlock,
editHistoryBlock as model1EditHistoryBlock,
} from "./model1";
import {
insertCursorToken,
insertEditableRegionTokensWithStaticRange,
@ -44,8 +42,8 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = {
"mercury-coder-nextedit": {
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`,
},
"model-1": {
template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`,
instinct: {
template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,
},
};
@ -95,11 +93,11 @@ export async function renderPrompt(
case "mercury-coder-nextedit": {
userEdits = ctx.editDiffHistory;
editedCodeWithTokens = insertTokens(
helper.fileContents.split("\n"),
helper.pos,
MERCURY_CURSOR,
);
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// MERCURY_CURSOR,
// );
const mercuryCtx: MercuryTemplateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
@ -117,20 +115,22 @@ export async function renderPrompt(
tv = mercuryCtx;
editedCodeWithTokens = mercuryCtx.currentFileContent;
break;
}
case "model-1": {
case "instinct": {
userEdits = ctx.editDiffHistory;
editedCodeWithTokens = insertTokens(
helper.fileContents.split("\n"),
helper.pos,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
);
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
// );
const model1Ctx: Model1TemplateVars = {
const instinctCtx: InstinctTemplateVars = {
contextSnippets: contextSnippetsBlock(ctx.contextSnippets),
currentFileContent: model1CurrentFileContentBlock(
currentFileContent: instinctCurrentFileContentBlock(
ctx.currentFileContent,
ctx.windowStart,
ctx.windowEnd,
@ -138,12 +138,14 @@ export async function renderPrompt(
ctx.editableRegionEndLine,
helper.pos,
),
editDiffHistory: model1EditHistoryBlock(ctx.editDiffHistory),
editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
languageShorthand: ctx.languageShorthand,
};
tv = model1Ctx;
tv = instinctCtx;
editedCodeWithTokens = instinctCtx.currentFileContent;
break;
}

View file

@ -5,6 +5,8 @@ import { AutocompleteSnippetType } from "../../autocomplete/snippets/types";
import { HelperVars } from "../../autocomplete/util/HelperVars";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
import {
INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
INSTINCT_USER_PROMPT_PREFIX,
MERCURY_CURRENT_FILE_CONTENT_CLOSE,
MERCURY_CURRENT_FILE_CONTENT_OPEN,
MERCURY_CURSOR,
@ -12,8 +14,6 @@ import {
MERCURY_EDIT_DIFF_HISTORY_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
MODEL_1_USER_PROMPT_PREFIX,
} from "../constants";
import {
renderDefaultSystemPrompt,
@ -24,7 +24,7 @@ import {
describe("NextEditPromptEngine", () => {
describe("renderPrompt", () => {
let mercuryHelper: HelperVars;
let model1Helper: HelperVars;
let instinctHelper: HelperVars;
let testHelper: HelperVars;
let unsupportedHelper: HelperVars;
let ctx: any;
@ -36,8 +36,8 @@ describe("NextEditPromptEngine", () => {
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
model1Helper = {
modelName: "continuedev/model-1" as NEXT_EDIT_MODELS,
instinctHelper = {
modelName: "continuedev/instinct" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
@ -54,7 +54,7 @@ describe("NextEditPromptEngine", () => {
{ filepath: "/path/to/file1.ts", content: "const b = 2;" },
],
currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@",
editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
editableRegionStartLine: 0,
editableRegionEndLine: 3,
userEdits: "Added constant a",
@ -81,35 +81,35 @@ describe("NextEditPromptEngine", () => {
expect(result.userExcerpts).toContain(MERCURY_CURSOR);
});
it("should render model-1 prompt correctly", async () => {
// Create proper model-1 context structure matching NextEditProvider.ts
const model1Ctx = {
it("should render instinct prompt correctly", async () => {
// Create proper instinct context structure matching NextEditProvider.ts
const instinctCtx = {
contextSnippets:
"+++++ /path/to/context.ts\nconst contextVar = 'test';",
currentFileContent: model1Helper.fileContents,
currentFileContent: instinctHelper.fileContents,
windowStart: 0, // Math.max(0, helper.pos.line - 25)
windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25)
adjustedEditableStart: 0, // Math.max(0, helper.pos.line - 1) within window
adjustedEditableEnd: 2, // Math.min(helper.pos.line + 5) within window
editDiffHistory:
"diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }", // unified diff
editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window
editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window
editDiffHistory: [
"diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }",
], // unified diff
currentFilePath: "/path/to/file.ts",
languageShorthand: "ts",
};
const result = await renderPrompt(model1Helper, model1Ctx);
const result = await renderPrompt(instinctHelper, instinctCtx);
console.log(result);
expect(result).toHaveProperty("prompt");
expect(result.prompt.role).toBe("user");
expect(result.prompt.content).toContain(MODEL_1_USER_PROMPT_PREFIX);
expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX);
expect(result.prompt.content).toContain("### Context:");
expect(result.prompt.content).toContain("### User Edits:");
expect(result.prompt.content).toContain("### User Excerpts:");
expect(result.prompt.content).toContain("```ts");
expect(result.userEdits).toBe(model1Ctx.editDiffHistory);
expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN);
expect(result.userEdits).toBe(instinctCtx.editDiffHistory);
expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN);
});
it("should throw error for unsupported model name", async () => {
@ -223,7 +223,7 @@ describe("NextEditPromptEngine", () => {
{ filepath: "/path/to/file1.ts", content: "const b = 2;" },
],
currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@",
editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
editableRegionStartLine: 0,
editableRegionEndLine: 3,
userEdits: "Added constant a",

View file

@ -0,0 +1,129 @@
import { Position } from "../..";
import {
INSTINCT_CONTEXT_FILE_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
INSTINCT_SNIPPET_TOKEN,
INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
} from "../constants";
import { insertCursorToken } from "./utils";
/**
* @param contextSnippets Codestral style snippet with +++++ filename\ncontent or an empty string.
*/
export function contextSnippetsBlock(contextSnippets: string) {
const headerRegex = /^(\+\+\+\+\+ )(.*)/;
const lines = contextSnippets.split("\n");
return lines
.reduce<string[]>((acc, line) => {
const matches = line.match(headerRegex);
if (matches) {
const filename = matches[2];
acc.push(`${INSTINCT_CONTEXT_FILE_TOKEN}: ${filename}`);
} else {
if (
acc.length > 0 &&
acc[acc.length - 1].startsWith(INSTINCT_CONTEXT_FILE_TOKEN) // if header was added just before
) {
acc.push(`${INSTINCT_SNIPPET_TOKEN}`);
}
acc.push(line);
}
return acc;
}, [])
.join("\n");
}
export function currentFileContentBlock(
currentFileContent: string,
windowStart: number,
windowEnd: number,
editableRegionStartLine: number,
editableRegionEndLine: number,
cursorPosition: Position,
) {
const currentFileContentLines = currentFileContent.split("\n");
const insertedCursorLines = insertCursorToken(
currentFileContentLines,
cursorPosition,
INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
);
const instrumentedLines = [
...insertedCursorLines.slice(windowStart, editableRegionStartLine),
INSTINCT_EDITABLE_REGION_START_TOKEN,
...insertedCursorLines.slice(
editableRegionStartLine,
editableRegionEndLine + 1,
),
INSTINCT_EDITABLE_REGION_END_TOKEN,
...insertedCursorLines.slice(editableRegionEndLine + 1, windowEnd + 1),
];
return instrumentedLines.join("\n");
}
export function editHistoryBlock(
editDiffHistories: string[], // array of unified diffs with Index headers
) {
if (!editDiffHistories.length) {
return "";
}
const blocks: string[] = [];
for (const editDiffHistory of editDiffHistories) {
if (!editDiffHistory.trim()) {
continue;
}
// Split on Index: lines to get the unified diff.
const diffSections = editDiffHistory
.split(/^Index: /m)
.filter((section) => section.trim());
for (const section of diffSections) {
const lines = section.split("\n");
// Extract filename from the first line (after "Index: " was split off).
const filename = lines[0];
// Find the start of the actual diff content (skip ---, +++, and === lines).
const diffLines = lines
.filter(
(line) =>
!line.startsWith("---") &&
!line.startsWith("+++") &&
!line.startsWith("===") &&
line.trim() !== "", // remove empty lines from header section
)
.slice(1); // remove the filename line
// Only include lines that are actual diff content (@@, +, -, or context lines).
const actualDiffContent = diffLines.filter(
(line) =>
line.startsWith("@@") ||
line.startsWith("+") ||
line.startsWith("-") ||
line.startsWith(" "), // context lines
);
if (actualDiffContent.length === 0) continue;
const diffBlock = [
`User edited file "${filename}"`,
"",
"```diff",
actualDiffContent.join("\n"),
"```",
].join("\n");
blocks.push(diffBlock);
}
}
return blocks.join("\n");
}

View file

@ -4,7 +4,7 @@ import {
contextSnippetsBlock,
currentFileContentBlock,
editHistoryBlock,
} from "./model1";
} from "./instinct";
describe("contextSnippetsBlock", () => {
test("should format empty context snippets", () => {
@ -291,7 +291,7 @@ line 3`;
describe("editHistoryBlock", () => {
test("should format empty edit history", () => {
const result = editHistoryBlock("");
const result = editHistoryBlock([]);
expect(result).toBe("");
});
@ -306,7 +306,7 @@ describe("editHistoryBlock", () => {
+ console.log("new");
}`;
const result = editHistoryBlock(diff);
const result = editHistoryBlock([diff]);
const expected = `User edited file "test.js"
\`\`\`diff
@ -337,7 +337,45 @@ Index: file2.js
-let x = "old";
+let x = "new";`;
const result = editHistoryBlock(unifiedDiff);
const result = editHistoryBlock([unifiedDiff]);
const expected = `User edited file "file1.js"
\`\`\`diff
@@ -1 +1 @@
-const old = 1;
+const new = 1;
\`\`\`
User edited file "file2.js"
\`\`\`diff
@@ -1 +1 @@
-let x = "old";
+let x = "new";
\`\`\``;
expect(result).toBe(expected);
});
test("should format multiple diff history entries", () => {
// Multiple diffs should be concatenated into a single string
const unifiedDiffs = [
`Index: file1.js
===================================================================
--- a/file1.js 2023-01-01 10:00:00.000000000 +0000
+++ b/file1.js 2023-01-01 10:01:00.000000000 +0000
@@ -1 +1 @@
-const old = 1;
+const new = 1;`,
`Index: file2.js
===================================================================
--- a/file2.js 2023-01-01 10:02:00.000000000 +0000
+++ b/file2.js 2023-01-01 10:03:00.000000000 +0000
@@ -1 +1 @@
-let x = "old";
+let x = "new";`,
];
const result = editHistoryBlock(unifiedDiffs);
const expected = `User edited file "file1.js"
\`\`\`diff
@ -366,7 +404,7 @@ User edited file "file2.js"
-export const Button = () => <button>Old</button>;
+export const Button = () => <button>New</button>;`;
const result = editHistoryBlock(diff);
const result = editHistoryBlock([diff]);
const expected = `User edited file "src/components/Button/Button.tsx"
\`\`\`diff
@ -388,7 +426,7 @@ User edited file "file2.js"
+ return "hello world";
+}`;
const result = editHistoryBlock(diff);
const result = editHistoryBlock([diff]);
const expected = `User edited file "newfile.js"
\`\`\`diff
@ -411,7 +449,7 @@ User edited file "file2.js"
- return "goodbye";
-}`;
const result = editHistoryBlock(diff);
const result = editHistoryBlock([diff]);
const expected = `User edited file "deletedfile.js"
\`\`\`diff
@ -431,7 +469,7 @@ User edited file "file2.js"
-old text
+new text`;
const result = editHistoryBlock(diff);
const result = editHistoryBlock([diff]);
const expected = `User edited file "simple.txt"
\`\`\`diff

View file

@ -50,12 +50,15 @@ export function currentFileContentBlock(
}
export function editHistoryBlock(
editDiffHistory: string, // could be a singe large unified diff
editDiffHistory: string[], // could be a singe large unified diff
) {
// diffHistory is made from createDiff.
// This uses createPatch from npm diff library, which includes an index line and a separator.
// We get rid of these first two lines.
return editDiffHistory.split("\n").slice(2).join("\n");
return editDiffHistory
.map((diff) => diff.split("\n").slice(2).join("\n"))
.join("\n");
// return editDiffHistory.split("\n").slice(2).join("\n");
}
function mercuryNextEditTemplateBuilder(

View file

@ -108,12 +108,12 @@ describe("mercuryCoderNextEdit", () => {
it("should return the edit diff history unchanged", () => {
const diffHistory =
"diff --git a/file.ts b/file.ts\n==============================\n@@ -1,3 +1,4 @@";
const result = editHistoryBlock(diffHistory);
const result = editHistoryBlock([diffHistory]);
expect(result).toBe("@@ -1,3 +1,4 @@");
});
it("should handle empty diff history", () => {
const result = editHistoryBlock("");
const result = editHistoryBlock([]);
expect(result).toBe("");
});
});

View file

@ -1,123 +0,0 @@
import { Position } from "../..";
import {
MODEL_1_CONTEXT_FILE_TOKEN,
MODEL_1_EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
MODEL_1_SNIPPET_TOKEN,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
} from "../constants";
import { insertCursorToken } from "./utils";
/**
* @param contextSnippets Codestral style snippet with +++++ filename\ncontent or an empty string.
*/
export function contextSnippetsBlock(contextSnippets: string) {
const headerRegex = /^(\+\+\+\+\+ )(.*)/;
const lines = contextSnippets.split("\n");
return lines
.reduce<string[]>((acc, line) => {
const matches = line.match(headerRegex);
if (matches) {
const filename = matches[2];
acc.push(`${MODEL_1_CONTEXT_FILE_TOKEN}: ${filename}`);
} else {
if (
acc.length > 0 &&
acc[acc.length - 1].startsWith(MODEL_1_CONTEXT_FILE_TOKEN) // if header was added just before
) {
acc.push(`${MODEL_1_SNIPPET_TOKEN}`);
}
acc.push(line);
}
return acc;
}, [])
.join("\n");
}
export function currentFileContentBlock(
currentFileContent: string,
windowStart: number,
windowEnd: number,
editableRegionStartLine: number,
editableRegionEndLine: number,
cursorPosition: Position,
) {
const currentFileContentLines = currentFileContent.split("\n");
const insertedCursorLines = insertCursorToken(
currentFileContentLines,
cursorPosition,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
);
const instrumentedLines = [
...insertedCursorLines.slice(windowStart, editableRegionStartLine),
MODEL_1_EDITABLE_REGION_START_TOKEN,
...insertedCursorLines.slice(
editableRegionStartLine,
editableRegionEndLine + 1,
),
MODEL_1_EDITABLE_REGION_END_TOKEN,
...insertedCursorLines.slice(editableRegionEndLine + 1, windowEnd + 1),
];
return instrumentedLines.join("\n");
}
export function editHistoryBlock(
editDiffHistories: string, // unified diffs with Index headers
) {
if (!editDiffHistories.trim()) {
return "";
}
const blocks: string[] = [];
// Split on Index: lines to get the unified diff.
const diffSections = editDiffHistories
.split(/^Index: /m)
.filter((section) => section.trim());
for (const section of diffSections) {
const lines = section.split("\n");
// Extract filename from the first line (after "Index: " was split off).
const filename = lines[0];
// Find the start of the actual diff content (skip ---, +++, and === lines).
const diffLines = lines
.filter(
(line) =>
!line.startsWith("---") &&
!line.startsWith("+++") &&
!line.startsWith("===") &&
line.trim() !== "", // remove empty lines from header section
)
.slice(1); // remove the filename line
// Only include lines that are actual diff content (@@, +, -, or context lines).
const actualDiffContent = diffLines.filter(
(line) =>
line.startsWith("@@") ||
line.startsWith("+") ||
line.startsWith("-") ||
line.startsWith(" "), // context lines
);
if (actualDiffContent.length === 0) continue;
const diffBlock = [
`User edited file "${filename}"`,
"",
"```diff",
actualDiffContent.join("\n"),
"```",
].join("\n");
blocks.push(diffBlock);
}
return blocks.join("\n");
}

View file

@ -1,7 +1,7 @@
import { Position } from "../..";
import {
MODEL_1_EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "../constants";
@ -53,9 +53,9 @@ export function insertEditableRegionTokensWithStaticRange(
const instrumentedLines = [
...lines.slice(0, editableRegionStart),
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
...lines.slice(editableRegionStart, editableRegionEnd + 1),
MODEL_1_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
...lines.slice(editableRegionEnd + 1),
];

View file

@ -1,8 +1,8 @@
import { describe, expect, it } from "vitest";
import { Position } from "../..";
import {
MODEL_1_EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "../constants";
@ -88,9 +88,9 @@ describe("insertEditableRegionTokensWithStaticRange", () => {
const expected = [
...lines.slice(0, expectedStart),
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
...lines.slice(expectedStart, expectedEnd + 1),
MODEL_1_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
...lines.slice(expectedEnd + 1),
];
@ -112,11 +112,11 @@ describe("insertEditableRegionTokensWithStaticRange", () => {
const expected = [
"line 0",
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
"line 1",
"line 2",
"line 3",
MODEL_1_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
"line 4",
];

View file

@ -90,7 +90,7 @@ export interface NextEditTemplate {
export interface TemplateVars {}
export interface Model1TemplateVars extends TemplateVars {
export interface InstinctTemplateVars extends TemplateVars {
contextSnippets: string;
currentFileContent: string;
editDiffHistory: string; // could be a singe large unified diff

View file

@ -26,6 +26,7 @@ import {
FileSymbolMap,
IdeSettings,
LLMFullCompletionOptions,
MCPServerStatus,
MessageOption,
ModelDescription,
PromptLog,
@ -48,6 +49,8 @@ import {
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes";
import { FreeTrialStatus } from "../control-plane/client";
import { NextEditOutcome } from "../nextEdit/types";
import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
export enum OnboardingModes {
API_KEY = "API Key",
@ -128,6 +131,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
ContextItemWithId[],
];
"mcp/reloadServer": [
{
id: string;
@ -145,6 +149,9 @@ export type ToCoreFromIdeOrWebviewProtocol = {
description: string | undefined;
},
];
"mcp/startAuthentication": [MCPServerStatus, void];
"mcp/removeAuthentication": [MCPServerStatus, void];
"context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
"autocomplete/complete": [AutocompleteInput, string[]];
@ -153,9 +160,44 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"context/indexDocs": [{ reIndex: boolean }, void];
"autocomplete/cancel": [undefined, void];
"autocomplete/accept": [{ completionId: string }, void];
"nextEdit/predict": [AutocompleteInput, string[]];
"nextEdit/predict": [
{
input: AutocompleteInput;
options?: {
withChain?: boolean;
usingFullFileDiff?: boolean;
};
},
NextEditOutcome | undefined,
];
"nextEdit/reject": [{ completionId: string }, void];
"nextEdit/accept": [{ completionId: string }, void];
"nextEdit/startChain": [undefined, void];
"nextEdit/deleteChain": [undefined, void];
"nextEdit/isChainAlive": [undefined, boolean];
"nextEdit/queue/getProcessedCount": [undefined, number];
"nextEdit/queue/dequeueProcessed": [undefined, ProcessedItem | null];
"nextEdit/queue/processOne": [
{
ctx: {
completionId: string;
manuallyPassFileContents?: string;
manuallyPassPrefix?: string;
selectedCompletionInfo?: {
text: string;
range: Range;
};
isUntitledFile: boolean;
recentlyVisitedRanges: AutocompleteCodeSnippet[];
recentlyEditedRanges: RecentlyEditedRange[];
};
recentlyVisitedRanges: AutocompleteCodeSnippet[];
recentlyEditedRanges: RecentlyEditedRange[];
},
void,
];
"nextEdit/queue/clear": [undefined, void];
"nextEdit/queue/abort": [undefined, void];
"llm/complete": [
{
prompt: string;

View file

@ -28,6 +28,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/updateSelectedModel",
"mcp/reloadServer",
"mcp/getPrompt",
"mcp/startAuthentication",
"mcp/removeAuthentication",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
@ -40,6 +42,14 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"nextEdit/predict",
"nextEdit/reject",
"nextEdit/accept",
"nextEdit/startChain",
"nextEdit/deleteChain",
"nextEdit/isChainAlive",
"nextEdit/queue/getProcessedCount",
"nextEdit/queue/dequeueProcessed",
"nextEdit/queue/processOne",
"nextEdit/queue/clear",
"nextEdit/queue/abort",
"tts/kill",
"llm/complete",
"llm/streamChat",

View file

@ -15,6 +15,7 @@ const createMcpServer = (name: string): MCPServerStatus => ({
type: "sse",
url: "",
},
isProtectedResource: false,
});
const createMCPTool = (name: string): MCPTool => ({

View file

@ -9,6 +9,10 @@ import {
SharedConfigSchema,
} from "../config/sharedConfig";
import {
OAuthClientInformationFull,
OAuthTokens,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import { getGlobalContextFilePath } from "./paths";
export type GlobalContextModelSelections = Partial<
@ -39,6 +43,14 @@ export type GlobalContextType = {
isSupportedLanceDbCpuTargetForLinux: boolean;
sharedConfig: SharedConfigSchema;
failedDocs: SiteIndexingConfig[];
mcpOauthStorage: Record<
string,
{
clientInformation?: OAuthClientInformationFull;
tokens?: OAuthTokens;
codeVerifier?: string;
}
>;
shownDeprecatedProviderWarnings: {
[providerTitle: string]: boolean;
};

View file

@ -5,12 +5,6 @@ slug: ../azure
Azure AI Foundry is a cloud-based service that provides access to models from OpenAI, Mistral AI, and others, integrated with the security and enterprise features of the Microsoft Azure platform. To get started, create an Azure AI Foundry resource in the [Azure portal](https://portal.azure.com).
<Info>
For details on OpenAI model setup, see [Azure OpenAI Service configuration](#azure-openai-service-configuration).
</Info>
## Chat model
We recommend configuring **GPT-4o** as your chat model.
@ -27,6 +21,7 @@ We recommend configuring **GPT-4o** as your chat model.
env:
deployment: <YOUR_DEPLOYMENT_NAME>
apiType: azure-foundry # Or "azure-openai" if using OpenAI models
apiVersion: 2023-07-01-preview # Azure API version
```
</Tab>
<Tab title="JSON">
@ -48,10 +43,13 @@ We recommend configuring **GPT-4o** as your chat model.
## Autocomplete model
We recommend configuring **Codestral** as your autocomplete model.
We recommend configuring **Codestral** as your autocomplete model.
<Info>
**Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint required for autocomplete functionality. To use Codestral for autocomplete, deploy it through **Azure Machine Learning Studio** instead, which provides the necessary `/v1/fim/completions` endpoint.
**Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint
required for autocomplete functionality. To use Codestral for autocomplete,
deploy it through **Azure Machine Learning Studio** instead, which provides
the necessary `/v1/fim/completions` endpoint.
</Info>
If you use Azure Machine Learning Studio to deploy Codestral:
@ -100,6 +98,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model.
env:
deployment: <YOUR_DEPLOYMENT_NAME>
apiType: azure
apiVersion: 2023-07-01-preview
```
</Tab>
<Tab title="JSON">

View file

@ -2,9 +2,16 @@
title: "Introduction"
---
**Continue enables developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
**Continue enables developers to ship faster with Continuous AI.**
- [Chat](/features/chat/quick-start) to understand and iterate on code in the sidebar
**You can use Continue to build and run custom agents across your IDE, terminal, and CI.**
1. Get started with Continue in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions:
- [Agent](/features/agent/quick-start) to work on development tasks together with AI
- [Chat](/features/chat/quick-start) to ask general questions and clarify code sections
- [Edit](/features/edit/quick-start) to modify code section without leaving your current file
- [Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
- [Edit](/features/edit/quick-start) to modify code without leaving your current file
- [Agent](/features/agent/quick-start) to make more substantial changes to your codebase
2. Try out [Continue CLI (cn)](https://docs.continue.dev/guides/cli) and give us feedback
3. Discover the models, rules, and MCP tools you need to create a custom AI coding agent on [Continue Hub](https://hub.continue.dev/)

View file

@ -175,11 +175,11 @@ The `models` section defines the language models used in your configuration. Mod
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for detailed information. Supported capabilities include:
- `tool_use`: Enables function/tool calling support (required for Agent mode)
- `image_input`: Enables image upload and processing support
Continue automatically detects these capabilities for most models, but you can override this when using custom deployments or if autodetection isn't working correctly.
- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.

View file

@ -105,6 +105,14 @@ class MessageTypes {
"nextEdit/predict",
"nextEdit/reject",
"nextEdit/accept",
"nextEdit/startChain",
"nextEdit/deleteChain",
"nextEdit/isChainAlive",
"nextEdit/queue/getProcessedCount",
"nextEdit/queue/dequeueProcessed",
"nextEdit/queue/processOne",
"nextEdit/queue/clear",
"nextEdit/queue/abort",
"tts/kill",
"llm/complete",
"llm/streamChat",

View file

@ -261,18 +261,15 @@ export class ContinueCompletionProvider
let outcome: AutocompleteOutcome | NextEditOutcome | undefined;
// console.log(
// "chain exists?",
// this.nextEditProvider.chainExists(),
// ", length:",
// this.nextEditProvider.getChainLength(),
// ", next regions queue:",
// this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength(),
// );
// TODO: We can probably decide here if we want to do the jumping logic.
// If we aren't going to jump anyways, then we should be not be using the prefetch queue or the jump manager.
// It would simplify the logic quite substantially.
// Determine why this method was triggered.
const isJumping = this.jumpManager.isJumpInProgress();
const chainExists = this.nextEditProvider.chainExists();
console.log("isJumping:", isJumping, "/ chainExists:", chainExists);
this.prefetchQueue.peekThreeProcessed();
if (isJumping && chainExists) {
// Case 2: Jumping (chain exists, jump was taken)
@ -340,7 +337,6 @@ export class ContinueCompletionProvider
if (isJumpSuggested) {
// Store completion to be rendered after a jump.
// TODO: setCompletionAfterJump must have a 1-1 correspondence to the jump location.
this.jumpManager.setCompletionAfterJump({
completionId: completionId,
outcome,

View file

@ -86,6 +86,7 @@ export class VsCodeExtension {
constructor(context: vscode.ExtensionContext) {
// Register auth provider
this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler);
void this.workOsAuthProvider.refreshSessions();
context.subscriptions.push(this.workOsAuthProvider);
@ -113,7 +114,8 @@ export class VsCodeExtension {
Date.now() - state.lastDocumentChangeTime;
if (
state.isTypingSession &&
timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY
timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY &&
!NextEditWindowManager.getInstance().hasAccepted()
) {
console.log("VsCodeExtension: typing in progress, preserving chain");
return true;

View file

@ -1,10 +1,13 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
import { renderContextItems } from "core/util/messageContent";
import { useContext, useEffect, useMemo, useState } from "react";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useIdeMessengerRequest } from "../../../hooks/useIdeMessengerRequest";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import { getStatusIcon } from "../../../pages/gui/ToolCallDiv/utils";
import { useAppSelector } from "../../../redux/hooks";
import { selectToolCallById } from "../../../redux/selectors/selectToolCalls";
import {
selectApplyStateByStreamId,
selectApplyStateByToolCallId,
@ -21,6 +24,7 @@ import { InsertButton } from "./InsertButton";
import { RunInTerminalButton } from "./RunInTerminalButton";
export interface StepContainerPreToolbarProps {
showToolCallStatusIcon?: boolean;
codeBlockContent: string;
language: string | null;
relativeFilepath?: string;
@ -37,6 +41,7 @@ export interface StepContainerPreToolbarProps {
}
export function StepContainerPreToolbar({
showToolCallStatusIcon,
codeBlockContent,
language,
relativeFilepath,
@ -81,6 +86,30 @@ export function StepContainerPreToolbar({
selectApplyStateByToolCallId(state, forceToolCallId),
);
const toolCallState = useAppSelector((state) =>
forceToolCallId ? selectToolCallById(state, forceToolCallId) : undefined,
);
const toolCallStatusIcon =
showToolCallStatusIcon &&
(toolCallState?.status === "canceled" ||
toolCallState?.status === "errored" ||
toolCallState?.status === "done") ? (
<div
className={`mr-1 h-4 w-4 ${toolCallState.output ? "cursor-pointer" : ""}`}
onClick={() => {
if (toolCallState.output) {
ideMessenger.post("showVirtualFile", {
name: "Edit output",
content: renderContextItems(toolCallState.output),
});
}
}}
>
{getStatusIcon(toolCallState.status)}
</div>
) : null;
/**
* In the case where `relativeFilepath` is defined, this will just be `relativeFilepathUri`.
* However, if no `relativeFilepath` is defined, then this will
@ -269,6 +298,7 @@ export function StepContainerPreToolbar({
style={{ fontSize: `${getFontSize() - 2}px` }}
>
<div className="flex max-w-[50%] flex-row items-center">
{toolCallStatusIcon}
<ChevronDownIcon
data-testid="toggle-codeblock"
onClick={() => setIsExpanded(!isExpanded)}

View file

@ -123,6 +123,7 @@ const StyledMarkdown = styled.div<{
`;
interface StyledMarkdownPreviewProps {
showToolCallStatusIcon?: boolean;
source?: string;
className?: string;
isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks
@ -300,6 +301,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
return (
<StepContainerPreToolbar
showToolCallStatusIcon={props.showToolCallStatusIcon}
codeBlockContent={codeBlockContent}
itemIndex={itemIndexRef.current}
codeBlockIndex={codeBlockIndex}
@ -357,6 +359,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const uiConfig = useAppSelector(selectUIConfig);
const codeWrapState = uiConfig?.codeWrap ? "pre-wrap" : "pre";
return (
<StyledMarkdown
fontSize={getFontSize()}

View file

@ -3,7 +3,10 @@ import {
ArrowPathIcon,
CircleStackIcon,
CommandLineIcon,
GlobeAltIcon,
InformationCircleIcon,
ShieldCheckIcon,
ShieldExclamationIcon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { MCPServerStatus } from "core";
@ -30,8 +33,9 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
const promptsTooltipId = `${server.id}-prompts`;
const resourcesTooltipId = `${server.id}-resources`;
const errorsTooltipId = `${server.id}-errors`;
const mcpAuthTooltipId = `${server.id}-auth`;
async function onRefresh() {
const updateMCPServerStatus = (status: MCPServerStatus["status"]) => {
// optimistic config update
dispatch(
updateConfig({
@ -40,23 +44,37 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
s.id === server.id
? {
...s,
status: "connecting",
status,
}
: s,
),
}),
);
};
const onAuthenticate = async () => {
updateMCPServerStatus("authenticating");
await ideMessenger.request("mcp/startAuthentication", server);
};
const onRemoveAuth = async () => {
updateMCPServerStatus("authenticating");
await ideMessenger.request("mcp/removeAuthentication", server);
};
const onRefresh = async () => {
updateMCPServerStatus("connecting");
ideMessenger.post("mcp/reloadServer", {
id: server.id,
});
}
};
return (
<div
style={{
fontSize: fontSize(-2),
}}
className="flex flex-row items-center justify-between gap-3"
className={`flex flex-row items-center justify-between gap-3 ${server.status === "authenticating" ? "my-0.5" : ""}`}
>
<div className="flex flex-row items-center gap-3">
{/* Name and Status */}
@ -159,8 +177,33 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
</div>
</div>
{/* Refresh button */}
<div className="flex items-center gap-2">
{server.isProtectedResource && (
<>
<div
className="text-lightgray flex cursor-pointer items-center hover:text-white hover:opacity-80"
data-tooltip-id={
server.status !== "authenticating" ? mcpAuthTooltipId : ""
}
>
{server.status === "error" ? (
<ShieldExclamationIcon
className="h-3 w-3"
onClick={onAuthenticate}
/>
) : server.status === "authenticating" ? (
<GlobeAltIcon className="animate-spin-slow h-3 w-3" />
) : (
<ShieldCheckIcon className="h-3 w-3" onClick={onRemoveAuth} />
)}
</div>
{server.status !== "authenticating" && (
<ToolTip place="left" id={mcpAuthTooltipId}>
{server.status === "error" ? "Authenticate" : "Logout"}
</ToolTip>
)}
</>
)}
<EditBlockButton
blockType={"mcpServers"}
block={serverFromYaml}

View file

@ -118,7 +118,7 @@ function ToolPolicyItem(props: ToolDropdownItemProps) {
</div>
<div
className={`flex w-8 flex-row items-center justify-end gap-2 px-2 py-0.5 sm:w-16 ${disabled ? "cursor-not-allowed" : "hover:text-list-active-foreground cursor-pointer hover:brightness-125"}`}
className={`flex w-8 select-none flex-row items-center justify-end gap-2 px-2 py-0.5 sm:w-16 ${disabled ? "cursor-not-allowed" : "hover:text-list-active-foreground cursor-pointer hover:brightness-125"}`}
data-testid={`tool-policy-item-${props.tool.function.name}`}
data-tooltip-id={disabled ? disabledTooltipId : undefined}
onClick={

View file

@ -1,11 +1,15 @@
import { ContextItem, ToolCallState } from "core";
import { getMarkdownLanguageTagForFile } from "core/util";
import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview";
type EditToolCallProps = {
showToolCallStatusIcon?: boolean;
relativeFilePath: string;
changes: string;
historyIndex: number;
toolCallId?: string;
output?: undefined | ContextItem[];
status?: ToolCallState["status"];
};
export function EditFile(props: EditToolCallProps) {
@ -17,6 +21,7 @@ export function EditFile(props: EditToolCallProps) {
return (
<StyledMarkdownPreview
showToolCallStatusIcon={props.showToolCallStatusIcon}
expandCodeblocks={false}
isRenderingInStepContainer
disableManualApply

View file

@ -38,8 +38,11 @@ function FunctionSpecificToolCallDiv({
? args.diffs.join("\n\n---\n\n")
: args.diffs
: "";
return (
<EditFile
showToolCallStatusIcon={true}
status={toolCallState.status}
relativeFilePath={args?.filepath ?? ""}
changes={changes}
toolCallId={toolCall.id}

View file

@ -63,7 +63,7 @@ export function SimpleToolCallUI({
}
return (
<div className="flex flex-col">
<div className="mt-1 flex flex-col px-4">
<div className="flex min-w-0 flex-row items-center justify-between gap-2">
<div
className={`text-description flex min-w-0 flex-row items-center justify-between gap-1.5 text-xs transition-colors duration-200 ease-in-out ${

View file

@ -26,40 +26,35 @@ export function ToolCallDisplay({
}, [toolCallState.parsedArgs]);
return (
<>
<div className="flex flex-col justify-center">
<div className="mb-2 flex flex-col">
<div className="flex flex-row items-center justify-between gap-1.5">
<div className="flex min-w-0 flex-row items-center gap-2">
<div className="mt-[1px] h-4 w-4 flex-shrink-0 font-semibold">
{icon}
</div>
{tool?.faviconUrl && (
<img src={tool.faviconUrl} className="h-4 w-4 rounded-sm" />
)}
<ToolCallStatusMessage
tool={tool}
toolCallState={toolCallState}
/>
</div>
<div className="flex flex-row items-center gap-1.5">
{!!toolCallState.output && (
<ToolTruncateHistoryIcon historyIndex={historyIndex} />
)}
{!!args.length ? (
<ArgsToggleIcon
isShowing={argsExpanded}
setIsShowing={setArgsExpanded}
/>
) : null}
<div className="flex flex-col justify-center px-4">
<div className="mb-2 flex flex-col">
<div className="flex flex-row items-center justify-between gap-1.5">
<div className="flex min-w-0 flex-row items-center gap-2">
<div className="mt-[1px] h-4 w-4 flex-shrink-0 font-semibold">
{icon}
</div>
{tool?.faviconUrl && (
<img src={tool.faviconUrl} className="h-4 w-4 rounded-sm" />
)}
<ToolCallStatusMessage tool={tool} toolCallState={toolCallState} />
</div>
<div className="flex flex-row items-center gap-1.5">
{!!toolCallState.output && (
<ToolTruncateHistoryIcon historyIndex={historyIndex} />
)}
{!!args.length ? (
<ArgsToggleIcon
isShowing={argsExpanded}
setIsShowing={setArgsExpanded}
/>
) : null}
</div>
{argsExpanded && !!args.length && (
<ArgsItems args={args} isShowing={argsExpanded} />
)}
</div>
<div>{children}</div>
{argsExpanded && !!args.length && (
<ArgsItems args={args} isShowing={argsExpanded} />
)}
</div>
</>
<div>{children}</div>
</div>
);
}

View file

@ -56,10 +56,12 @@ export function ToolCallDiv({
// But we'd need a nicer place to put the truncate button and the X icon when tool call fails
if (functionName === BuiltInToolNames.SearchAndReplaceInFile) {
return (
<FunctionSpecificToolCallDiv
toolCallState={toolCallState}
historyIndex={historyIndex}
/>
<div className="flex flex-col px-1">
<FunctionSpecificToolCallDiv
toolCallState={toolCallState}
historyIndex={historyIndex}
/>
</div>
);
}
@ -80,7 +82,7 @@ export function ToolCallDiv({
if (shouldShowGroupedUI) {
return (
<div className="border-border rounded-lg border p-3 pb-0">
<div className="border-border rounded-lg border px-4 py-3 pb-0">
<GroupedToolCallHeader
toolCallStates={toolCallStates}
activeCalls={activeCalls}
@ -103,7 +105,7 @@ export function ToolCallDiv({
}
return toolCallStates.map((toolCallState) => (
<div className="px-4 py-1" key={toolCallState.toolCallId}>
<div className="py-1" key={toolCallState.toolCallId}>
{renderToolCall(toolCallState)}
</div>
));