diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml new file mode 100644 index 000000000..13ebcf269 --- /dev/null +++ b/.github/workflows/similar-issues.yml @@ -0,0 +1,342 @@ +name: Similar Issue Search & Discussion Suggestion +on: + issues: + types: [opened] + pull_request: + types: [opened] + +jobs: + analyze: + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + + steps: + - name: Checkout deja-view + uses: actions/checkout@v4 + with: + repository: 'bdougie/deja-view' + # Option 1: Pin to specific commit (most secure) + 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' + + - 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 }} + CHROMA_TENANT: ${{ secrets.CHROMA_TENANT }} + CHROMA_DATABASE: ${{ secrets.CHROMA_DATABASE }} + 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: + CHROMA_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }} + CHROMA_TENANT: ${{ secrets.CHROMA_TENANT }} + CHROMA_DATABASE: ${{ secrets.CHROMA_DATABASE }} + 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 }}" + THRESHOLD="0.85" + TOP_K="5" + else + ISSUE_URL="https://github.com/${{ github.repository }}/issues/${{ github.event.issue.number }}" + 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, + repo=repo, + issue_number=issue_number, + 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<> $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' + env: + CHROMA_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }} + CHROMA_TENANT: ${{ secrets.CHROMA_TENANT }} + CHROMA_DATABASE: ${{ secrets.CHROMA_DATABASE }} + 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): + self.title = issue_title + self.body = issue_body + self.labels = issue_labels + self.state = 'open' + self.number = int(os.environ.get('ISSUE_NUMBER', 0)) + 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<> $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: + script: | + let comment = ''; + 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 }}`); + + if (isPR) { + // Filter only open issues for PRs + const openIssues = similarIssues.filter(issue => issue.state === 'open'); + + if (openIssues.length > 0) { + // Simple table format for PRs + comment += '## 📋 Related Open Issues\n\n'; + comment += 'These open issues appear to be related to this PR (≥85% similarity):\n\n'; + comment += '| # | Title | Similarity |\n'; + comment += '|---|-------|------------|\n'; + + openIssues.forEach(issue => { + const similarity = (issue.similarity * 100).toFixed(0); + const title = issue.title.length > 50 ? issue.title.substring(0, 47) + '...' : issue.title; + comment += `| [#${issue.number}](${issue.url}) | ${title} | ${similarity}% |\n`; + }); + + comment += '\n'; + comment += '_Consider closing related issues if this PR addresses them._\n'; + } else { + // Don't add any comment if no open issues found + return; + } + } else { + // Original format for issues + comment += '## 🔍 Similar Issues Found\n\n'; + comment += 'I found some existing issues that might be related:\n\n'; + + similarIssues.forEach((issue, index) => { + const similarity = (issue.similarity * 100).toFixed(1); + const state = issue.state === 'open' ? '🟢' : '🔴'; + + comment += `${index + 1}. ${state} [#${issue.number}: ${issue.title}](${issue.url}) (${similarity}% similar)\n`; + + if (issue.summary) { + comment += ` > ${issue.summary.substring(0, 150)}${issue.summary.length > 150 ? '...' : ''}\n`; + } + comment += '\n'; + }); + + comment += '\n'; + } + } + + // Add discussion suggestion if applicable + if (shouldBeDiscussion) { + const analysis = JSON.parse(`${{ steps.discussion_check.outputs.analysis }}`); + const confidence = '${{ steps.discussion_check.outputs.confidence }}'; + + if (hasSimilar) { + comment += '---\n\n'; + } + + comment += '## 💬 Discussion Suggestion\n\n'; + + const confidenceEmoji = { + 'high': '🟢', + 'medium': '🟡', + 'low': '🔴' + }; + + comment += `This issue might be better suited as a **GitHub Discussion** ${confidenceEmoji[confidence] || ''}\n\n`; + comment += `**Confidence**: ${confidence.charAt(0).toUpperCase() + confidence.slice(1)} (${(analysis.score * 100).toFixed(0)}%)\n\n`; + + if (analysis.reasons && analysis.reasons.length > 0) { + comment += '**Reasons**:\n'; + analysis.reasons.forEach(reason => { + comment += `- ${reason}\n`; + }); + comment += '\n'; + } + + comment += 'GitHub Discussions are great for:\n'; + comment += '- Questions and help requests\n'; + comment += '- Feature requests and ideas\n'; + comment += '- General feedback and brainstorming\n'; + comment += '- Community conversations\n\n'; + + 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'; + comment += '_This analysis was automatically generated by [deja-view](https://github.com/bdougie/deja-view)._'; + + if ('${{ github.event_name }}' === 'pull_request') { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + body: comment + }); + } else { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + body: comment + }); + } + } + + - 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 }}`); + const hasDuplicate = similarIssues.some(issue => issue.similarity > 0.9); + + if (hasDuplicate) { + labels.push('potential-duplicate'); + } + } + + // Check for discussion suggestion + if ('${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true') { + const confidence = '${{ steps.discussion_check.outputs.confidence }}'; + + if (confidence === 'high') { + labels.push('should-be-discussion'); + } else if (confidence === 'medium') { + labels.push('discussion'); + } + } + + // Add labels if any + if (labels.length > 0) { + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + labels: labels + }); + } diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 179e5fad4..9d977d071 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -17,6 +17,7 @@ import { ControlPlaneSessionInfo, } from "../control-plane/AuthTypes.js"; import { getControlPlaneEnv } from "../control-plane/env.js"; +import { PolicySingleton } from "../control-plane/PolicySingleton.js"; import { logger } from "../util/logger.js"; import { Telemetry } from "../util/posthog.js"; import { @@ -45,7 +46,7 @@ export class ConfigHandler { private organizations: OrgWithProfiles[] = []; currentProfile: ProfileLifecycleManager | null; - currentOrg: OrgWithProfiles; + currentOrg: OrgWithProfiles | null; totalConfigReloads: number = 0; public isInitialized: Promise; @@ -83,16 +84,9 @@ export class ConfigHandler { this.ide, ); - // Just to be safe, always force a default personal org with local profile manager - this.currentProfile = this.globalLocalProfileManager; - const personalOrg: OrgWithProfiles = { - currentProfile: this.globalLocalProfileManager, - profiles: [this.globalLocalProfileManager], - ...this.PERSONAL_ORG_DESC, - }; - - this.currentOrg = personalOrg; - this.organizations = [personalOrg]; + this.currentOrg = null; + this.currentProfile = null; + this.organizations = []; this.initter = new EventEmitter(); this.isInitialized = new Promise((resolve) => { @@ -132,10 +126,10 @@ export class ConfigHandler { const firstNonPersonal = orgs.find( (org) => org.id !== this.PERSONAL_ORG_DESC.id, ); - const fallback = firstNonPersonal ?? orgs[0]; - // note, ignoring case of zero orgs since should never happen + const fallback: OrgWithProfiles | null = + firstNonPersonal ?? orgs[0] ?? null; - let selectedOrg: OrgWithProfiles; + let selectedOrg: OrgWithProfiles | null; if (currentSelection) { const match = orgs.find((org) => org.id === currentSelection); if (match) { @@ -153,12 +147,12 @@ export class ConfigHandler { this.globalContext.update("lastSelectedOrgIdForWorkspace", { ...selectedOrgs, - [workspaceId]: selectedOrg.id, + [workspaceId]: selectedOrg?.id, }); this.organizations = orgs; this.currentOrg = selectedOrg; - this.currentProfile = selectedOrg.currentProfile; + this.currentProfile = selectedOrg?.currentProfile; await this.reloadConfig(reason, errors); } catch (e) { @@ -179,10 +173,27 @@ export class ConfigHandler { const isSignedIn = await this.controlPlaneClient.isSignedIn(); if (isSignedIn) { try { - const orgDescs = await this.controlPlaneClient.listOrganizations(); + // TODO use policy returned with org, not policy endpoint + const policyResponse = await this.controlPlaneClient.getPolicy(); + PolicySingleton.getInstance().policy = policyResponse; + const orgDescriptions = + await this.controlPlaneClient.listOrganizations(); + const orgsWithPolicy = orgDescriptions.map((d) => ({ + ...d, + policy: policyResponse?.policy, + })); + + if (policyResponse?.policy?.allowOtherOrgs === false) { + if (orgsWithPolicy.length === 0) { + return { orgs: [] }; + } else { + const firstOrg = await this.getNonPersonalHubOrg(orgsWithPolicy[0]); + return { orgs: [firstOrg] }; + } + } const orgs = await Promise.all([ this.getPersonalHubOrg(), - ...orgDescs.map((org) => this.getNonPersonalHubOrg(org)), + ...orgsWithPolicy.map((org) => this.getNonPersonalHubOrg(org)), ]); // TODO make try/catch more granular here, to catch specific org errors return { orgs }; @@ -426,7 +437,7 @@ export class ConfigHandler { // Org id: check id validity, save selection, switch and reload async setSelectedOrgId(orgId: string, profileId?: string) { - if (orgId === this.currentOrg.id) { + if (orgId === this.currentOrg?.id) { return; } const org = this.organizations.find((org) => org.id === orgId); @@ -454,6 +465,9 @@ export class ConfigHandler { // Profile id: check id validity, save selection, switch and reload async setSelectedProfileId(profileId: string) { + if (!this.currentOrg) { + throw new Error(`No org selected`); + } if ( this.currentProfile && profileId === this.currentProfile.profileDescription.id @@ -490,10 +504,7 @@ export class ConfigHandler { if (!this.currentProfile) { return { config: undefined, - errors: [ - { message: "Current profile not found", fatal: true }, - ...(injectErrors ?? []), - ], + errors: injectErrors, configLoadInterrupted: true, }; } @@ -562,7 +573,7 @@ export class ConfigHandler { if (!this.currentProfile) { return { config: undefined, - errors: [{ message: "Current profile not found", fatal: true }], + errors: undefined, configLoadInterrupted: true, }; } @@ -575,7 +586,7 @@ export class ConfigHandler { if (!this.currentProfile) { return { config: undefined, - errors: [{ message: "Current profile not found", fatal: true }], + errors: undefined, configLoadInterrupted: true, }; } @@ -598,11 +609,15 @@ export class ConfigHandler { if (!openProfileId) { return; } - const profile = this.currentOrg.profiles.find( + const profile = this.currentOrg?.profiles.find( (p) => p.profileDescription.id === openProfileId, ); + if (!profile) { + console.error(`Profile ${profileId} not found`); + return; + } - if (profile?.profileDescription.profileType === "local") { + if (profile.profileDescription.profileType === "local") { const configFile = element?.sourceFile ?? profile.profileDescription.uri; await this.ide.openFile(configFile); } else { diff --git a/core/config/ConfigHandler.vitest.ts b/core/config/ConfigHandler.vitest.ts index f58160044..1307ce6ab 100644 --- a/core/config/ConfigHandler.vitest.ts +++ b/core/config/ConfigHandler.vitest.ts @@ -10,7 +10,7 @@ import { defaultConfig } from "./default"; describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should show only local profile", () => { - const profiles = testConfigHandler.currentOrg.profiles; + const profiles = testConfigHandler.currentOrg?.profiles; expect(profiles?.length).toBe(1); expect(profiles?.[0].profileDescription.id).toBe("local"); diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index f61908e32..e16bb7986 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -2,6 +2,7 @@ import { ConfigResult, ConfigValidationError, FullSlug, + Policy, } from "@continuedev/config-yaml"; import { @@ -30,6 +31,7 @@ export interface OrganizationDescription { iconUrl: string; name: string; slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend + policy?: Policy; } export type OrgWithProfiles = OrganizationDescription & { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index ea6b0bf51..d6528454b 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -26,6 +26,7 @@ import RulesContextProvider from "../../context/providers/RulesContextProvider"; import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { getControlPlaneEnv } from "../../control-plane/env.js"; +import { PolicySingleton } from "../../control-plane/PolicySingleton"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; import { getConfigDependentToolDefinitions } from "../../tools"; @@ -325,8 +326,18 @@ export default async function doLoadConfig(options: { } }); - newConfig.allowAnonymousTelemetry = - newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled()); + if (newConfig.allowAnonymousTelemetry !== false) { + if ((await ide.isTelemetryEnabled()) === false) { + newConfig.allowAnonymousTelemetry = false; + } + } + + if ( + PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry === + false + ) { + newConfig.allowAnonymousTelemetry = false; + } // Setup telemetry only after (and if) we know it is enabled await Telemetry.setup( diff --git a/core/config/util.ts b/core/config/util.ts index a53027a76..08bf8949b 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -10,7 +10,6 @@ import { JSONModelDescription, PromptTemplate, } from "../"; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; @@ -80,12 +79,6 @@ export function addModel( maxStopWords: model.maxStopWords, defaultCompletionOptions: model.completionOptions, }; - if (model.systemMessage) { - desc.chatOptions = { - baseSystemMessage: - DEFAULT_CHAT_SYSTEM_MESSAGE + "\n\n" + model.systemMessage, - }; - } config.models.push(desc); return config; }, diff --git a/core/context/providers/_context-providers.vitest.ts b/core/context/providers/_context-providers.vitest.ts index f7096bf87..bde33cec1 100644 --- a/core/context/providers/_context-providers.vitest.ts +++ b/core/context/providers/_context-providers.vitest.ts @@ -36,6 +36,7 @@ async function getContextProviderExtras( llmLogger, Promise.resolve(undefined), ); + await configHandler.isInitialized; const { config } = await configHandler.loadConfig(); if (!config) { throw new Error("Config not found"); @@ -54,7 +55,7 @@ async function getContextProviderExtras( }; } -describe.skip("Should successfully run all context providers", () => { +describe("Should successfully run all context providers", () => { afterAll(() => { tearDownTestDir(); }); diff --git a/core/control-plane/PolicySingleton.ts b/core/control-plane/PolicySingleton.ts new file mode 100644 index 000000000..705e67b49 --- /dev/null +++ b/core/control-plane/PolicySingleton.ts @@ -0,0 +1,15 @@ +import { PolicyResponse } from "./client.js"; + +export class PolicySingleton { + private static instance: PolicySingleton; + public policy: PolicyResponse | null = null; + + private constructor() {} + + public static getInstance(): PolicySingleton { + if (!PolicySingleton.instance) { + PolicySingleton.instance = new PolicySingleton(); + } + return PolicySingleton.instance; + } +} diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index ad6112aa9..d5f99a274 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -4,6 +4,7 @@ import { ConfigResult, FQSN, FullSlug, + Policy, SecretResult, SecretType, } from "@continuedev/config-yaml"; @@ -15,6 +16,11 @@ import { IdeInfo, IdeSettings, ModelDescription } from "../index.js"; import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js"; import { getControlPlaneEnv } from "./env.js"; +export interface PolicyResponse { + orgSlug?: string; + policy?: Policy; +} + export interface ControlPlaneWorkspace { id: string; name: string; @@ -215,6 +221,21 @@ export class ControlPlaneClient { } } + public async getPolicy(): Promise { + if (!(await this.isSignedIn())) { + return null; + } + + try { + const resp = await this.request(`ide/policy`, { + method: "GET", + }); + return (await resp.json()) as PolicyResponse; + } catch (e) { + return null; + } + } + public async getFreeTrialStatus(): Promise { if (!(await this.isSignedIn())) { return null; diff --git a/core/core.ts b/core/core.ts index 905151f07..aa558736c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -184,7 +184,7 @@ export class Core { profileId: this.configHandler.currentProfile?.profileDescription.id || null, organizations: this.configHandler.getSerializedOrgs(), - selectedOrgId: this.configHandler.currentOrg.id, + selectedOrgId: this.configHandler.currentOrg?.id ?? null, }); // update additional submenu context providers registered via VSCode API @@ -465,7 +465,7 @@ export class Core { profileId: this.configHandler.currentProfile?.profileDescription.id ?? null, organizations: this.configHandler.getSerializedOrgs(), - selectedOrgId: this.configHandler.currentOrg.id, + selectedOrgId: this.configHandler.currentOrg?.id ?? null, }; }); diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 1417d8307..40648c702 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -63,13 +63,22 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = ) { return true; } + + // LGAI EXAONE models expose an OpenAI-compatible API with tool + // calling support when served via frameworks like vLLM + if (lower.includes("exaone")) { + return true; + } + if (lower.includes("gpt-oss")) { return true; } + // https://ai.google.dev/gemma/docs/capabilities/function-calling if (lower.startsWith("gemma")) { return true; } + // firworks-ai https://docs.fireworks.ai/guides/function-calling if (model.startsWith("accounts/fireworks/models/")) { switch (model.substring(26)) { @@ -179,6 +188,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "firefunction-v2", "mistral", "devstral", + "exaone", "gpt-oss", ].some((part) => modelName.toLowerCase().includes(part)) ) { @@ -269,6 +279,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "deepseek/deepseek-chat", "meta-llama/llama-4", "all-hands/openhands-lm-32b", + "lgai-exaone/exaone", ]; for (const prefix of supportedPrefixes) { if (model.toLowerCase().startsWith(prefix)) { @@ -339,6 +350,7 @@ export function modelSupportsNativeTools(modelDescription: ModelDescription) { if (modelDescription.capabilities?.tools !== undefined) { return modelDescription.capabilities.tools; } + const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; if (!providerSupport) { return false; diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index ade13b4c3..67f7d1cf0 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -37,6 +37,7 @@ import { replaceEscapedCharacters } from "../util/text.js"; import { MERCURY_CODE_TO_EDIT_OPEN, MERCURY_SYSTEM_PROMPT, + MODEL_1_SYSTEM_PROMPT, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "./constants.js"; @@ -83,6 +84,7 @@ export class NextEditProvider { private contextRetrievalService: ContextRetrievalService; private endpointType: "default" | "fineTuned"; private diffContext: string = ""; + private autocompleteContext: string = ""; private promptMetadata: PromptMetadata | null = null; private currentEditChainId: string | null = null; private previousRequest: AutocompleteInput | null = null; @@ -137,6 +139,10 @@ export class NextEditProvider { this.diffContext = diff; } + public addAutocompleteContext(ctx: string): void { + this.autocompleteContext = ctx; + } + private async _prepareLlm(): Promise { const llm = await this._injectedGetLlm(); @@ -553,10 +559,33 @@ export class NextEditProvider { currentFilePath: helper.filepath, }; } else if (modelName.includes("model-1")) { + // 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( + helper.fileLines.length - 1, + 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, + ); + + // Ensure editable region boundaries are within the window. + const adjustedEditableStart = Math.max(windowStart, actualEditableStart); + const adjustedEditableEnd = Math.min(windowEnd, actualEditableEnd); ctx = { - userEdits: historyDiff ?? this.diffContext, + contextSnippets: this.autocompleteContext, + currentFileContent: helper.fileContents, + windowStart, + windowEnd, + adjustedEditableStart, + adjustedEditableEnd, + editDiffHistory: this.diffContext, + currentFilePath: helper.filepath, languageShorthand: helper.lang.name, - userExcerpts: helper.fileContents, }; } else { ctx = {}; @@ -567,7 +596,9 @@ export class NextEditProvider { const systemPrompt: Prompt = { role: "system", - content: MERCURY_SYSTEM_PROMPT, + content: modelName.includes("mercury-coder-nextedit") + ? MERCURY_SYSTEM_PROMPT + : MODEL_1_SYSTEM_PROMPT, }; return [systemPrompt, promptMetadata.prompt]; diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 153563d11..21e249b96 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -6,6 +6,33 @@ export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5; 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. + +You have access to the following information to help you make informed suggestions: + +- Context: In the section marked "### Context", there are context items from potentially relevant files in the developer's codebase. Each context item consists of a <|context_file|> marker, the filepath, a <|snippet|> marker, and then some content from that file, in that order. Keep in mind that not all of the context information may be relevant to the task, so use your judgement to determine which parts to consider. +- User Edits: In the section marked "### User Edits:", there is a record of the most recent changes made to the code, helping you understand the evolution of the code and the developer's intentions. These changes are listed from most recent to least recent. It's possible that some of the edit diff history is entirely irrelevant to the developer's change. The changes are provided in a unified line-diff format, i.e. with pluses and minuses for additions and deletions to the code. +- User Excerpt: In the section marked "### User Excerpt:", there is a filepath to the developer's current file, and then an excerpt from that file. The <|editable_region_start|> and <|editable_region_end|> markers are within this excerpt. Your job is to rewrite only this editable region, not the whole excerpt. The excerpt provides additional context on the surroundings of the developer's edit. +- Cursor Position: Within the user excerpt's editable region, the <|user_cursor_is_here|> flag indicates where the developer's cursor is currently located, which can be crucial for understanding what part of the code they are focusing on. Do not produce this marker in your output; simply take it into account. + +Your task is to predict and complete the changes the developer would have made next in the editable region. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they're following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn't get distracted by ensuring your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes. + +# Steps + +1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location. +2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements. +3. **Suggest Edits**: If changes are required, ensure they align with the developer's patterns and improve code quality. +4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style. + +# Output Format + +- 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 = + "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. export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN = diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts index 465a7106f..38a76b051 100644 --- a/core/nextEdit/context/diffFormatting.ts +++ b/core/nextEdit/context/diffFormatting.ts @@ -95,3 +95,139 @@ const createTokenLineDiff = ( // TODO: Implement token line diff return ""; }; + +export interface DiffMetadata { + oldFilename?: string; // Filename in the original version + newFilename?: string; // Filename in the modified version + oldTimestamp?: string; // Timestamp of the original file + newTimestamp?: string; // Timestamp of the modified file + hunks?: Array<{ + // Information about each change hunk + oldStart: number; // Starting line in original file + oldCount: number; // Number of lines in original file + newStart: number; // Starting line in modified file + newCount: number; // Number of lines in modified file + header?: string; // Optional section header + lines: Array<{ + type: "context" | "addition" | "deletion"; + content: string; + oldLineNumber?: number; + newLineNumber?: number; + }>; + }>; + isBinary?: boolean; // Whether this is a binary file diff + isNew?: boolean; // Whether this is a new file + isDeleted?: boolean; // Whether this file was deleted + isRename?: boolean; // Whether this file was renamed +} + +export function extractMetadataFromUnifiedDiff( + unifiedDiff: string, +): DiffMetadata { + const metadata: DiffMetadata = {}; + const lines = unifiedDiff.split("\n"); + + // Parse the header lines (first two lines) + if (lines.length >= 2) { + // Parse original file info (--- line) + const oldFileMatch = lines[0].match(/^--- (a\/)?(.+?)(?:\t(.+))?$/); + if (oldFileMatch) { + metadata.oldFilename = oldFileMatch[2]; + metadata.oldTimestamp = oldFileMatch[3]; + + // Check if this is a new file + if (metadata.oldFilename === "/dev/null") { + metadata.isNew = true; + } + } + + // Parse modified file info (+++ line) + const newFileMatch = lines[1].match(/^\+\+\+ (b\/)?(.+?)(?:\t(.+))?$/); + if (newFileMatch) { + metadata.newFilename = newFileMatch[2]; + metadata.newTimestamp = newFileMatch[3]; + + // Check if this file was deleted + if (metadata.newFilename === "/dev/null") { + metadata.isDeleted = true; + } + } + + // Check if this is a rename (different old and new names) + if ( + metadata.oldFilename && + metadata.newFilename && + metadata.oldFilename !== "/dev/null" && + metadata.newFilename !== "/dev/null" && + metadata.oldFilename !== metadata.newFilename + ) { + metadata.isRename = true; + } + } + + // Parse hunk headers and content + metadata.hunks = []; + const hunkHeaderRegex = + /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s(.*))?$/; + + let currentHunk: NonNullable[0] | null = null; + let oldLineNumber = 0; + let newLineNumber = 0; + + for (let i = 2; i < lines.length; i++) { + const line = lines[i]; + const hunkMatch = line.match(hunkHeaderRegex); + + if (hunkMatch) { + currentHunk = { + oldStart: parseInt(hunkMatch[1], 10), // line number where changes start in original file + oldCount: hunkMatch[2] ? parseInt(hunkMatch[2], 10) : 1, // number of changed lines in original file, default to 1 if not specified + newStart: parseInt(hunkMatch[3], 10), // line number where changes start in modified file + newCount: hunkMatch[4] ? parseInt(hunkMatch[4], 10) : 1, // number of changed lines in modified file, default to 1 if not specified + header: hunkMatch[5], // the line starting with @@ + lines: [], // the actual line changes + }; + + oldLineNumber = currentHunk.oldStart; + newLineNumber = currentHunk.newStart; + + metadata.hunks.push(currentHunk); + } else if ( + currentHunk && + (line.startsWith(" ") || line.startsWith("+") || line.startsWith("-")) + ) { + // Process hunk content lines. + const lineType = line[0]; + const content = line.slice(1); + + if (lineType === " ") { + // Context line (unchanged). + currentHunk.lines.push({ + type: "context", + content, + oldLineNumber: oldLineNumber++, + newLineNumber: newLineNumber++, + }); + } else if (lineType === "+") { + currentHunk.lines.push({ + type: "addition", + content, + newLineNumber: newLineNumber++, + }); + } else if (lineType === "-") { + currentHunk.lines.push({ + type: "deletion", + content, + oldLineNumber: oldLineNumber++, + }); + } + } + + // Check for binary file marker + if (line.includes("Binary files") || line.includes("GIT binary patch")) { + metadata.isBinary = true; + } + } + + return metadata; +} diff --git a/core/nextEdit/context/diffFormatting.vitest.ts b/core/nextEdit/context/diffFormatting.vitest.ts new file mode 100644 index 000000000..b010f7837 --- /dev/null +++ b/core/nextEdit/context/diffFormatting.vitest.ts @@ -0,0 +1,462 @@ +import { describe, expect, it } from "vitest"; +import { + BeforeAfterDiff, + createBeforeAfterDiff, + createDiff, + CreateDiffArgs, + DiffFormatType, + DiffMetadata, + extractMetadataFromUnifiedDiff, +} from "./diffFormatting"; + +describe("diffFormatting", () => { + const sampleFilePath = "test/sample.js"; + const beforeContent = "const a = 1;\nconst b = 2;"; + const afterContent = "const a = 1;\nconst b = 3;\nconst c = 4;"; + + describe("createDiff", () => { + it("should create unified diff when specified", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("---"); + expect(result).toContain("+++"); + expect(result).toContain("@@"); + expect(result).toContain("-const b = 2;"); + expect(result).toContain("+const b = 3;"); + expect(result).toContain("+const c = 4;"); + }); + + it("should create token line diff when specified", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: sampleFilePath, + diffType: DiffFormatType.TokenLineDiff, + contextLines: 3, + }; + + const result = createDiff(args); + + // Currently returns empty string as TODO + expect(result).toBe(""); + }); + + it("should return empty string for unsupported diff types", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: sampleFilePath, + diffType: DiffFormatType.RawBeforeAfter, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toBe(""); + }); + + it("should handle empty content", () => { + const args: CreateDiffArgs = { + beforeContent: "", + afterContent: "new content", + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("+++"); + expect(result).toContain("+new content"); + }); + + it("should handle deletion", () => { + const args: CreateDiffArgs = { + beforeContent: "old content", + afterContent: "", + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("---"); + expect(result).toContain("-old content"); + }); + + it("should handle content without newlines", () => { + const args: CreateDiffArgs = { + beforeContent: "line1", + afterContent: "line2", + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("-line1"); + expect(result).toContain("+line2"); + }); + + it("should respect contextLines parameter", () => { + const multiLineContent = Array(10) + .fill("line") + .map((l, i) => `${l}${i}`) + .join("\n"); + const modifiedContent = multiLineContent.replace("line5", "modified5"); + + const args: CreateDiffArgs = { + beforeContent: multiLineContent, + afterContent: modifiedContent, + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 2, + }; + + const result = createDiff(args); + + expect(result).toContain("@@ -4,5 +4,5 @@"); + }); + }); + + describe("createBeforeAfterDiff", () => { + it("should return BeforeAfterDiff with normalized content", () => { + const result: BeforeAfterDiff = createBeforeAfterDiff( + beforeContent, + afterContent, + sampleFilePath, + ); + + expect(result).toEqual({ + filePath: sampleFilePath, + beforeContent: beforeContent + "\n", + afterContent: afterContent + "\n", + }); + }); + + it("should not add extra newline if content already ends with one", () => { + const contentWithNewline = "const a = 1;\n"; + const result: BeforeAfterDiff = createBeforeAfterDiff( + contentWithNewline, + contentWithNewline, + sampleFilePath, + ); + + expect(result.beforeContent).toBe(contentWithNewline); + expect(result.afterContent).toBe(contentWithNewline); + }); + + it("should handle empty content", () => { + const result: BeforeAfterDiff = createBeforeAfterDiff( + "", + "", + sampleFilePath, + ); + + expect(result).toEqual({ + filePath: sampleFilePath, + beforeContent: "\n", + afterContent: "\n", + }); + }); + + it("should handle mixed newline scenarios", () => { + const beforeWithNewline = "line1\n"; + const afterWithoutNewline = "line2"; + const result: BeforeAfterDiff = createBeforeAfterDiff( + beforeWithNewline, + afterWithoutNewline, + sampleFilePath, + ); + + expect(result.beforeContent).toBe("line1\n"); + expect(result.afterContent).toBe("line2\n"); + }); + }); + + describe("extractMetadataFromUnifiedDiff", () => { + it("should extract basic file information", () => { + const unifiedDiff = `--- a/old.js\ttimestamp1 ++++ b/new.js\ttimestamp2 +@@ -1,3 +1,3 @@ + line1 +-line2 ++modified2 + line3`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("old.js"); + expect(metadata.newFilename).toBe("new.js"); + expect(metadata.oldTimestamp).toBe("timestamp1"); + expect(metadata.newTimestamp).toBe("timestamp2"); + expect(metadata.isNew).toBeFalsy(); + expect(metadata.isDeleted).toBeFalsy(); + expect(metadata.isRename).toBeTruthy(); + }); + + it("should detect new files", () => { + const unifiedDiff = `--- /dev/null ++++ b/new.js +@@ -0,0 +1,2 @@ ++line1 ++line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("/dev/null"); + expect(metadata.newFilename).toBe("new.js"); + expect(metadata.isNew).toBeTruthy(); + expect(metadata.isDeleted).toBeFalsy(); + expect(metadata.isRename).toBeFalsy(); + }); + + it("should detect deleted files", () => { + const unifiedDiff = `--- a/old.js ++++ /dev/null +@@ -1,2 +0,0 @@ +-line1 +-line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("old.js"); + expect(metadata.newFilename).toBe("/dev/null"); + expect(metadata.isNew).toBeFalsy(); + expect(metadata.isDeleted).toBeTruthy(); + expect(metadata.isRename).toBeFalsy(); + }); + + it("should parse hunk information", () => { + const unifiedDiff = `--- a/file.js ++++ b/file.js +@@ -1,5 +1,6 @@ function header + line1 +-line2 ++modified2 ++newline + line3 +@@ -10,3 +11,3 @@ + line10 +-line11 ++modified11 + line12`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.hunks).toHaveLength(2); + expect(metadata.hunks![0]).toEqual({ + oldStart: 1, + oldCount: 5, + newStart: 1, + newCount: 6, + header: "function header", + lines: [ + { + content: "line1", + newLineNumber: 1, + oldLineNumber: 1, + type: "context", + }, + { + content: "line2", + oldLineNumber: 2, + type: "deletion", + }, + { + content: "modified2", + newLineNumber: 2, + type: "addition", + }, + { + content: "newline", + newLineNumber: 3, + type: "addition", + }, + { + content: "line3", + newLineNumber: 4, + oldLineNumber: 3, + type: "context", + }, + ], + }); + expect(metadata.hunks![1]).toEqual({ + oldStart: 10, + oldCount: 3, + newStart: 11, + newCount: 3, + header: undefined, + lines: [ + { + content: "line10", + newLineNumber: 11, + oldLineNumber: 10, + type: "context", + }, + { + content: "line11", + oldLineNumber: 11, + type: "deletion", + }, + { + content: "modified11", + newLineNumber: 12, + type: "addition", + }, + { + content: "line12", + newLineNumber: 13, + oldLineNumber: 12, + type: "context", + }, + ], + }); + }); + + it("should handle single line hunks", () => { + const unifiedDiff = `--- a/file.js ++++ b/file.js +@@ -1 +1 @@ +-old ++new`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.hunks).toHaveLength(1); + expect(metadata.hunks![0]).toEqual({ + oldStart: 1, + oldCount: 1, + newStart: 1, + newCount: 1, + header: undefined, + lines: [ + { + content: "old", + oldLineNumber: 1, + type: "deletion", + }, + { + content: "new", + newLineNumber: 1, + type: "addition", + }, + ], + }); + }); + + it("should detect binary files", () => { + const unifiedDiff = `--- a/image.png ++++ b/image.png +Binary files a/image.png and b/image.png differ`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.isBinary).toBeTruthy(); + }); + + it("should detect git binary patches", () => { + const unifiedDiff = `--- a/file.bin ++++ b/file.bin +GIT binary patch +delta 123 +...`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.isBinary).toBeTruthy(); + }); + + it("should handle files without a/ b/ prefixes", () => { + const unifiedDiff = `--- old.js ++++ new.js +@@ -1,2 +1,2 @@ +-line1 ++modified1 + line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("old.js"); + expect(metadata.newFilename).toBe("new.js"); + }); + + it("should handle empty diff", () => { + const metadata: DiffMetadata = extractMetadataFromUnifiedDiff(""); + + expect(metadata.oldFilename).toBeUndefined(); + expect(metadata.newFilename).toBeUndefined(); + expect(metadata.hunks).toEqual([]); + expect(metadata.isBinary).toBeFalsy(); + }); + + it("should handle malformed diff gracefully", () => { + const malformedDiff = `not a diff +random text`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(malformedDiff); + + expect(metadata.oldFilename).toBeUndefined(); + expect(metadata.newFilename).toBeUndefined(); + expect(metadata.hunks).toEqual([]); + }); + + it("should not consider same filenames as rename", () => { + const unifiedDiff = `--- a/file.js ++++ b/file.js +@@ -1,2 +1,2 @@ +-line1 ++modified1 + line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.isRename).toBeFalsy(); + }); + + it("should handle files with spaces in names", () => { + const unifiedDiff = `--- a/my file.js\t2023-01-01 00:00:00 ++++ b/my new file.js\t2023-01-01 00:01:00 +@@ -1,1 +1,1 @@ +-content ++new content`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("my file.js"); + expect(metadata.newFilename).toBe("my new file.js"); + expect(metadata.oldTimestamp).toBe("2023-01-01 00:00:00"); + expect(metadata.newTimestamp).toBe("2023-01-01 00:01:00"); + expect(metadata.isRename).toBeTruthy(); + }); + }); + + describe("DiffFormatType enum", () => { + it("should have correct enum values", () => { + expect(DiffFormatType.Unified).toBe("unified"); + expect(DiffFormatType.RawBeforeAfter).toBe("beforeAfter"); + expect(DiffFormatType.TokenLineDiff).toBe("linediff"); + }); + }); +}); diff --git a/core/nextEdit/context/processNextEditData.ts b/core/nextEdit/context/processNextEditData.ts index aaa89d33a..0cecfe33e 100644 --- a/core/nextEdit/context/processNextEditData.ts +++ b/core/nextEdit/context/processNextEditData.ts @@ -3,6 +3,7 @@ import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types"; import { GetLspDefinitionsFunction } from "../../autocomplete/types"; import { ConfigHandler } from "../../config/ConfigHandler"; import { DataLogger } from "../../data/log"; +import { NextEditProvider } from "../NextEditProvider"; import { RecentlyEditedRange } from "../types"; import { getAutocompleteContext } from "./autocompleteContextFetching"; import { createDiff, DiffFormatType } from "./diffFormatting"; @@ -75,6 +76,8 @@ export const processNextEditData = async ({ modelName, ); + NextEditProvider.getInstance().addAutocompleteContext(autocompleteContext); + // console.log( // createDiff(beforeContent, afterContent, filePath, DiffFormatType.Unified), // ); diff --git a/core/nextEdit/context/processSmallEdit.ts b/core/nextEdit/context/processSmallEdit.ts index 5824191b3..a98233cfe 100644 --- a/core/nextEdit/context/processSmallEdit.ts +++ b/core/nextEdit/context/processSmallEdit.ts @@ -20,7 +20,7 @@ export const processSmallEdit = async ( afterContent: beforeAfterdiff.afterContent, filePath: beforeAfterdiff.filePath, diffType: DiffFormatType.Unified, - contextLines: 3, // NOTE: This can change depending on experiments! + contextLines: 5, // NOTE: This can change depending on experiments! }), ); diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 29e958b18..326ac4d84 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -2,6 +2,7 @@ import Handlebars from "handlebars"; import { Position } from "../.."; import { SnippetPayload } from "../../autocomplete/snippets"; import { HelperVars } from "../../autocomplete/util/HelperVars"; +import { NEXT_EDIT_MODELS } from "../../llm/constants"; import { MERCURY_CURRENT_FILE_CONTENT_CLOSE, MERCURY_CURRENT_FILE_CONTENT_OPEN, @@ -11,6 +12,7 @@ import { 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 { MercuryTemplateVars, @@ -26,11 +28,15 @@ import { editHistoryBlock, recentlyViewedCodeSnippetsBlock, } from "./mercuryCoderNextEdit"; +import { + contextSnippetsBlock, + currentFileContentBlock as model1CurrentFileContentBlock, + editHistoryBlock as model1EditHistoryBlock, +} from "./model1"; import { insertCursorToken, insertEditableRegionTokensWithStaticRange, } from "./utils"; -import { NEXT_EDIT_MODELS } from "../../llm/constants"; type TemplateRenderer = (vars: TemplateVars) => string; @@ -39,8 +45,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { 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: - "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```", + 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:`, }, }; @@ -115,7 +120,7 @@ export async function renderPrompt( break; } case "model-1": { - userEdits = ctx.userEdits; + userEdits = ctx.editDiffHistory; editedCodeWithTokens = insertTokens( helper.fileContents.split("\n"), @@ -124,9 +129,18 @@ export async function renderPrompt( ); const model1Ctx: Model1TemplateVars = { - userEdits: ctx.userEdits, + contextSnippets: contextSnippetsBlock(ctx.contextSnippets), + currentFileContent: model1CurrentFileContentBlock( + ctx.currentFileContent, + ctx.windowStart, + ctx.windowEnd, + ctx.editableRegionStartLine, + ctx.editableRegionEndLine, + helper.pos, + ), + editDiffHistory: model1EditHistoryBlock(ctx.editDiffHistory), + currentFilePath: ctx.currentFilePath, languageShorthand: ctx.languageShorthand, - userExcerpts: ctx.userExcerpts, }; tv = model1Ctx; diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index 785dd79cc..23ae1d7cb 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -3,6 +3,7 @@ import { Position } from "../.."; import { SnippetPayload } from "../../autocomplete/snippets"; import { AutocompleteSnippetType } from "../../autocomplete/snippets/types"; import { HelperVars } from "../../autocomplete/util/HelperVars"; +import { NEXT_EDIT_MODELS } from "../../llm/constants"; import { MERCURY_CURRENT_FILE_CONTENT_CLOSE, MERCURY_CURRENT_FILE_CONTENT_OPEN, @@ -12,13 +13,13 @@ import { 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, renderDefaultUserPrompt, renderPrompt, } from "./NextEditPromptEngine"; -import { NEXT_EDIT_MODELS } from "../../llm/constants"; describe("NextEditPromptEngine", () => { describe("renderPrompt", () => { @@ -81,15 +82,33 @@ describe("NextEditPromptEngine", () => { }); it("should render model-1 prompt correctly", async () => { - const result = await renderPrompt(model1Helper, ctx); + // Create proper model-1 context structure matching NextEditProvider.ts + const model1Ctx = { + contextSnippets: + "+++++ /path/to/context.ts\nconst contextVar = 'test';", + currentFileContent: model1Helper.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 + currentFilePath: "/path/to/file.ts", + languageShorthand: "ts", + }; + + const result = await renderPrompt(model1Helper, model1Ctx); + 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("### 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(ctx.userEdits); + expect(result.userEdits).toBe(model1Ctx.editDiffHistory); expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN); }); diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/model1.ts new file mode 100644 index 000000000..821d46d3b --- /dev/null +++ b/core/nextEdit/templating/model1.ts @@ -0,0 +1,123 @@ +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((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"); +} diff --git a/core/nextEdit/templating/model1.vitest.ts b/core/nextEdit/templating/model1.vitest.ts new file mode 100644 index 000000000..b1020f040 --- /dev/null +++ b/core/nextEdit/templating/model1.vitest.ts @@ -0,0 +1,445 @@ +import { describe, expect, test } from "vitest"; +import { Position } from "../.."; +import { + contextSnippetsBlock, + currentFileContentBlock, + editHistoryBlock, +} from "./model1"; + +describe("contextSnippetsBlock", () => { + test("should format empty context snippets", () => { + const result = contextSnippetsBlock(""); + expect(result).toBe(""); + }); + + test("should format single context snippet with codestral style header", () => { + const input = `+++++ src/utils.ts +function helper() { + return "test"; +}`; + + const expected = `<|context_file|>: src/utils.ts +<|snippet|> +function helper() { + return "test"; +}`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should format multiple context snippets", () => { + const input = `+++++ src/file1.ts +const var1 = "value1"; + ++++++ src/file2.ts +const var2 = "value2"; +function test() {}`; + + const expected = `<|context_file|>: src/file1.ts +<|snippet|> +const var1 = "value1"; + +<|context_file|>: src/file2.ts +<|snippet|> +const var2 = "value2"; +function test() {}`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should handle context snippet without content", () => { + const input = "+++++ src/empty.ts"; + + const expected = `<|context_file|>: src/empty.ts`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should handle malformed headers gracefully", () => { + const input = `not a header ++++++ src/valid.ts +valid content`; + + const expected = `not a header +<|context_file|>: src/valid.ts +<|snippet|> +valid content`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should handle multiple consecutive headers", () => { + const input = `+++++ src/file1.ts ++++++ src/file2.ts +content after headers`; + + const expected = `<|context_file|>: src/file1.ts +<|context_file|>: src/file2.ts +<|snippet|> +content after headers`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); +}); + +describe("currentFileContentBlock", () => { + test("should insert cursor and editable region tokens correctly", () => { + const content = `line 0 +line 1 +line 2 +line 3 +line 4`; + const windowStart = 0; + const windowEnd = 4; + const cursorPosition: Position = { line: 2, character: 4 }; + const editableRegionStartLine = 1; + const editableRegionEndLine = 3; + + const result = currentFileContentBlock( + content, + windowStart, + windowEnd, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `line 0 +<|editable_region_start|> +line 1 +line<|user_cursor_is_here|> 2 +line 3 +<|editable_region_end|> +line 4`; + + expect(result).toBe(expected); + }); + + test("should handle cursor at beginning of line", () => { + const content = `line 0 +line 1 +line 2`; + const windowStart = 0; + const windowEnd = 2; + const cursorPosition: Position = { line: 1, character: 0 }; + const editableRegionStartLine = 0; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + windowStart, + windowEnd, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +<|user_cursor_is_here|>line 1 +line 2 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); + + test("should handle cursor at end of line", () => { + const content = `line 0 +line 1 +line 2`; + const windowStart = 0; + const windowEnd = 2; + const cursorPosition: Position = { line: 1, character: 6 }; // end of "line 1" + const editableRegionStartLine = 0; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + windowStart, + windowEnd, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +line 1<|user_cursor_is_here|> +line 2 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); + + test("should handle single line editable region", () => { + const content = `line 0 +line 1 +line 2`; + const windowStart = 0; + const windowEnd = 2; + const cursorPosition: Position = { line: 1, character: 2 }; + const editableRegionStartLine = 1; + const editableRegionEndLine = 1; + + const result = currentFileContentBlock( + content, + windowStart, + windowEnd, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `line 0 +<|editable_region_start|> +li<|user_cursor_is_here|>ne 1 +<|editable_region_end|> +line 2`; + + expect(result).toBe(expected); + }); + + test("should handle cursor outside bounds gracefully (this shouldn't happen)", () => { + const content = `line 0 +line 1`; + const windowStart = 0; + const windowEnd = 1; + const cursorPosition: Position = { line: 10, character: 0 }; // out of bounds + const editableRegionStartLine = 0; + const editableRegionEndLine = 1; + + const result = currentFileContentBlock( + content, + windowStart, + windowEnd, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +line 1 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); + + test("should handle editable region covering entire file", () => { + const content = `line 0 +line 1 +line 2`; + const windowStart = 0; + const windowEnd = 2; + const cursorPosition: Position = { line: 1, character: 0 }; + const editableRegionStartLine = 0; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + windowStart, + windowEnd, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +<|user_cursor_is_here|>line 1 +line 2 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); + + test("should handle windowing - content outside window not included", () => { + const content = `line 0 +line 1 +line 2 +line 3 +line 4`; + const windowStart = 1; + const windowEnd = 3; + const cursorPosition: Position = { line: 2, character: 2 }; + const editableRegionStartLine = 2; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + windowStart, + windowEnd, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `line 1 +<|editable_region_start|> +li<|user_cursor_is_here|>ne 2 +<|editable_region_end|> +line 3`; + + expect(result).toBe(expected); + }); +}); + +describe("editHistoryBlock", () => { + test("should format empty edit history", () => { + const result = editHistoryBlock(""); + expect(result).toBe(""); + }); + + test("should format single diff history entry", () => { + const diff = `Index: test.js +=================================================================== +--- a/test.js 2023-01-01 10:00:00.000000000 +0000 ++++ b/test.js 2023-01-01 10:01:00.000000000 +0000 +@@ -1,3 +1,3 @@ + function test() { +- console.log("old"); ++ console.log("new"); + }`; + + const result = editHistoryBlock(diff); + const expected = `User edited file "test.js" + +\`\`\`diff +@@ -1,3 +1,3 @@ + function test() { +- console.log("old"); ++ console.log("new"); + } +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should format multiple diff history entries in unified format", () => { + // Multiple diffs should be concatenated into a single string + const unifiedDiff = `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(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); + }); + + // Fix remaining tests to pass strings instead of arrays + test("should handle diff with complex filename paths", () => { + const diff = `Index: src/components/Button/Button.tsx +=================================================================== +--- a/src/components/Button/Button.tsx 2023-01-01 10:00:00.000000000 +0000 ++++ b/src/components/Button/Button.tsx 2023-01-01 10:01:00.000000000 +0000 +@@ -1,2 +1,2 @@ +-export const Button = () => ; ++export const Button = () => ;`; + + const result = editHistoryBlock(diff); + const expected = `User edited file "src/components/Button/Button.tsx" + +\`\`\`diff +@@ -1,2 +1,2 @@ +-export const Button = () => ; ++export const Button = () => ; +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should handle diff with new file creation", () => { + const diff = `Index: newfile.js +=================================================================== +--- /dev/null 2023-01-01 10:00:00.000000000 +0000 ++++ b/newfile.js 2023-01-01 10:01:00.000000000 +0000 +@@ -0,0 +1,3 @@ ++function newFunction() { ++ return "hello world"; ++}`; + + const result = editHistoryBlock(diff); + const expected = `User edited file "newfile.js" + +\`\`\`diff +@@ -0,0 +1,3 @@ ++function newFunction() { ++ return "hello world"; ++} +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should handle diff with file deletion", () => { + const diff = `Index: deletedfile.js +=================================================================== +--- a/deletedfile.js 2023-01-01 10:00:00.000000000 +0000 ++++ /dev/null 2023-01-01 10:01:00.000000000 +0000 +@@ -1,3 +0,0 @@ +-function deletedFunction() { +- return "goodbye"; +-}`; + + const result = editHistoryBlock(diff); + const expected = `User edited file "deletedfile.js" + +\`\`\`diff +@@ -1,3 +0,0 @@ +-function deletedFunction() { +- return "goodbye"; +-} +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should handle minimal diff format", () => { + const diff = `Index: simple.txt +=================================================================== +@@ -1 +1 @@ +-old text ++new text`; + + const result = editHistoryBlock(diff); + const expected = `User edited file "simple.txt" + +\`\`\`diff +@@ -1 +1 @@ +-old text ++new text +\`\`\``; + + expect(result).toBe(expected); + }); +}); diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 49a4c0862..4c50e0291 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -91,9 +91,11 @@ export interface NextEditTemplate { export interface TemplateVars {} export interface Model1TemplateVars extends TemplateVars { - userEdits: string; + contextSnippets: string; + currentFileContent: string; + editDiffHistory: string; // could be a singe large unified diff + currentFilePath: string; languageShorthand: string; - userExcerpts: string; } export interface MercuryTemplateVars extends TemplateVars { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 85bca7242..258feaaa9 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -90,7 +90,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { result: ConfigResult; profileId: string | null; organizations: SerializedOrgWithProfiles[]; - selectedOrgId: string; + selectedOrgId: string | null; }, ]; "config/deleteModel": [{ title: string }, void]; diff --git a/core/tools/implementations/runTerminalCommand.test.ts b/core/tools/implementations/runTerminalCommand.test.ts index d688e4991..e744ea4f1 100644 --- a/core/tools/implementations/runTerminalCommand.test.ts +++ b/core/tools/implementations/runTerminalCommand.test.ts @@ -352,4 +352,123 @@ describe("runTerminalCommandImpl", () => { expect(result[0].content).toBe("Command is running in the background..."); expect(result[0].status).toBe("Command is running in the background..."); }); + + it("should handle missing workspace directory gracefully", async () => { + // Mock IDE to return empty workspace directories + const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); + + // Create IDE mock with empty workspace + const mockIde = { + getIdeInfo: jest + .fn() + .mockReturnValue(Promise.resolve({ remoteName: "local" })), + getWorkspaceDirs: mockEmptyWorkspace, + runCommand: jest.fn(), + getIdeSettings: jest.fn(), + getDiff: jest.fn(), + getClipboardContent: jest.fn(), + isTelemetryEnabled: jest.fn(), + readFile: jest.fn(), + writeFile: jest.fn(), + renameFile: jest.fn(), + deleteFile: jest.fn(), + globFiles: jest.fn(), + ls: jest.fn(), + }; + + const extras = { + ide: mockIde as unknown as IDE, + llm: {} as any, + fetch: {} as any, + tool: {} as any, + toolCallId: "test-tool-call", + } as ToolExtras; + + const command = `node -e "console.log('no workspace test')"`; + const args = { command, waitForCompletion: true }; + + const result = await runTerminalCommandImpl(args, extras); + + // Should still work - falling back to HOME or cwd + expect(result).toHaveLength(1); + expect(result[0].name).toBe("Terminal"); + expect(result[0].description).toBe("Terminal command output"); + expect(result[0].content).toContain("no workspace test"); + expect(result[0].status).toBe("Command completed"); + + // Verify workspace dirs was called but returned empty + expect(mockEmptyWorkspace).toHaveBeenCalled(); + }); + + it("should handle case where cwd fallbacks all fail", async () => { + // Mock IDE to return empty workspace directories + const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); + + // Save original environment variables and process.cwd + const originalHome = process.env.HOME; + const originalUserProfile = process.env.USERPROFILE; + const originalCwd = process.cwd; + + try { + // Mock all fallbacks to fail + delete process.env.HOME; + delete process.env.USERPROFILE; + process.cwd = jest.fn().mockImplementation(() => { + throw new Error("Current directory unavailable"); + }) as jest.MockedFunction<() => string>; + + // Create IDE mock with empty workspace + const mockIde = { + getIdeInfo: jest + .fn() + .mockReturnValue(Promise.resolve({ remoteName: "local" })), + getWorkspaceDirs: mockEmptyWorkspace, + runCommand: jest.fn(), + getIdeSettings: jest.fn(), + getDiff: jest.fn(), + getClipboardContent: jest.fn(), + isTelemetryEnabled: jest.fn(), + readFile: jest.fn(), + writeFile: jest.fn(), + renameFile: jest.fn(), + deleteFile: jest.fn(), + globFiles: jest.fn(), + ls: jest.fn(), + }; + + const extras = { + ide: mockIde as unknown as IDE, + llm: {} as any, + fetch: {} as any, + tool: {} as any, + toolCallId: "test-tool-call", + } as ToolExtras; + + const command = `node -e "console.log('fallback test')"`; + const args = { command, waitForCompletion: true }; + + // This should now handle the case gracefully by falling back to temp directory + const result = await runTerminalCommandImpl(args, extras); + + // Should work using the temp directory as fallback + expect(result).toHaveLength(1); + expect(result[0].name).toBe("Terminal"); + expect(result[0].content).toContain("fallback test"); + expect(result[0].status).toBe("Command completed"); + + console.log( + "Successfully handled cwd fallback to temp directory:", + result[0].status, + ); + } finally { + // Always restore original values + if (originalHome !== undefined) { + process.env.HOME = originalHome; + } + if (originalUserProfile !== undefined) { + process.env.USERPROFILE = originalUserProfile; + } + process.cwd = originalCwd; + } + }); }); diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index c48ba2ade..b106396af 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -1,5 +1,6 @@ import iconv from "iconv-lite"; import childProcess from "node:child_process"; +import os from "node:os"; import util from "node:util"; // Automatically decode the buffer according to the platform to avoid garbled Chinese function getDecodedOutput(data: Buffer): string { @@ -75,89 +76,132 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { if (ENABLED_FOR_REMOTES.includes(ideInfo.remoteName)) { // For streaming output if (extras.onPartialOutput) { - return new Promise((resolve, reject) => { - try { - const getWorkspaceDirsPromise = extras.ide.getWorkspaceDirs(); - getWorkspaceDirsPromise - .then((workspaceDirs) => { - const cwd = fileURLToPath(workspaceDirs[0]); - let terminalOutput = ""; + try { + const workspaceDirs = await extras.ide.getWorkspaceDirs(); - if (!waitForCompletion) { - const status = "Command is running in the background..."; - if (extras.onPartialOutput) { - extras.onPartialOutput({ - toolCallId, - contextItems: [ - { - name: "Terminal", - description: "Terminal command output", - content: "", - status: status, - }, - ], - }); - } - } + // Handle case where no workspace is available + let cwd: string; + if (workspaceDirs.length > 0) { + cwd = fileURLToPath(workspaceDirs[0]); + } else { + // Default to user's home directory with fallbacks + try { + cwd = process.env.HOME || process.env.USERPROFILE || process.cwd(); + } catch (error) { + // Final fallback if even process.cwd() fails - use system temp directory + cwd = os.tmpdir(); + } + } - // Use spawn with color environment - const { shell, args } = getShellCommand(command); - const childProc = childProcess.spawn(shell, args, { - cwd, - env: getColorEnv(), // Add enhanced environment for colors + return new Promise((resolve, reject) => { + let terminalOutput = ""; + + if (!waitForCompletion) { + const status = "Command is running in the background..."; + if (extras.onPartialOutput) { + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: "", + status: status, + }, + ], }); + } + } - childProc.stdout?.on("data", (data) => { - // Skip if this process has been backgrounded - if (isProcessBackgrounded(toolCallId)) return; + // Use spawn with color environment + const { shell, args } = getShellCommand(command); + const childProc = childProcess.spawn(shell, args, { + cwd, + env: getColorEnv(), // Add enhanced environment for colors + }); - const newOutput = getDecodedOutput(data); - terminalOutput += newOutput; + childProc.stdout?.on("data", (data) => { + // Skip if this process has been backgrounded + if (isProcessBackgrounded(toolCallId)) return; - // Send partial output to UI - if (extras.onPartialOutput) { - const status = waitForCompletion - ? "" - : "Command is running in the background..."; - extras.onPartialOutput({ - toolCallId, - contextItems: [ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - status: status, - }, - ], - }); - } + const newOutput = getDecodedOutput(data); + terminalOutput += newOutput; + + // Send partial output to UI + if (extras.onPartialOutput) { + const status = waitForCompletion + ? "" + : "Command is running in the background..."; + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ], }); + } + }); - childProc.stderr?.on("data", (data) => { - // Skip if this process has been backgrounded - if (isProcessBackgrounded(toolCallId)) return; + childProc.stderr?.on("data", (data) => { + // Skip if this process has been backgrounded + if (isProcessBackgrounded(toolCallId)) return; - const newOutput = getDecodedOutput(data); - terminalOutput += newOutput; + const newOutput = getDecodedOutput(data); + terminalOutput += newOutput; - // Send partial output to UI, status is not required - if (extras.onPartialOutput) { - extras.onPartialOutput({ - toolCallId, - contextItems: [ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - }, - ], - }); - } + // Send partial output to UI, status is not required + if (extras.onPartialOutput) { + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + }, + ], }); + } + }); - // If we don't need to wait for completion, resolve immediately - if (!waitForCompletion) { - const status = "Command is running in the background..."; + // If we don't need to wait for completion, resolve immediately + if (!waitForCompletion) { + const status = "Command is running in the background..."; + resolve([ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ]); + } + + childProc.on("close", (code) => { + // If this process has been backgrounded, clean it up from the map and return + if (isProcessBackgrounded(toolCallId)) { + removeBackgroundedProcess(toolCallId); + return; + } + + if (waitForCompletion) { + // Normal completion, resolve now + if (code === 0) { + const status = "Command completed"; + resolve([ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ]); + } else { + const status = `Command failed with exit code ${code}`; resolve([ { name: "Terminal", @@ -167,80 +211,58 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { }, ]); } + } else { + // Already resolved, just update the UI with final output + if (extras.onPartialOutput) { + const status = + code === 0 || !code + ? "\nBackground command completed" + : `\nBackground command failed with exit code ${code}`; + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ], + }); + } + } + }); - childProc.on("close", (code) => { - // If this process has been backgrounded, clean it up from the map and return - if (isProcessBackgrounded(toolCallId)) { - removeBackgroundedProcess(toolCallId); - return; - } + childProc.on("error", (error) => { + // If this process has been backgrounded, clean it up from the map and return + if (isProcessBackgrounded(toolCallId)) { + removeBackgroundedProcess(toolCallId); + return; + } - if (waitForCompletion) { - // Normal completion, resolve now - if (code === 0) { - const status = "Command completed"; - resolve([ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - status: status, - }, - ]); - } else { - const status = `Command failed with exit code ${code}`; - resolve([ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - status: status, - }, - ]); - } - } else { - // Already resolved, just update the UI with final output - if (extras.onPartialOutput) { - const status = - code === 0 || !code - ? "\nBackground command completed" - : `\nBackground command failed with exit code ${code}`; - extras.onPartialOutput({ - toolCallId, - contextItems: [ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - status: status, - }, - ], - }); - } - } - }); - - childProc.on("error", (error) => { - // If this process has been backgrounded, clean it up from the map and return - if (isProcessBackgrounded(toolCallId)) { - removeBackgroundedProcess(toolCallId); - return; - } - - reject(error); - }); - }) - .catch((error) => { - reject(error); - }); - } catch (error: any) { - reject(error); - } - }); + reject(error); + }); + }); + } catch (error: any) { + throw error; + } } else { // Fallback to non-streaming for older clients const workspaceDirs = await extras.ide.getWorkspaceDirs(); - const cwd = fileURLToPath(workspaceDirs[0]); + + // Handle case where no workspace is available + let cwd: string; + if (workspaceDirs.length > 0) { + cwd = fileURLToPath(workspaceDirs[0]); + } else { + // Default to user's home directory with fallbacks + try { + cwd = process.env.HOME || process.env.USERPROFILE || process.cwd(); + } catch (error) { + // Final fallback if even process.cwd() fails - use system temp directory + cwd = os.tmpdir(); + } + } if (waitForCompletion) { // Standard execution, waiting for completion diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 147c3979a..fbcdbca66 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -20,6 +20,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { useImports: true, transform: true, showWhateverWeHaveAtXMs: 300, + // Experimental options: true = enabled, false = disabled, number = enabled w priority experimental_includeClipboard: true, experimental_includeRecentlyVisitedRanges: true, experimental_includeRecentlyEditedRanges: true, diff --git a/docs/customize/deep-dives/autocomplete.mdx b/docs/customize/deep-dives/autocomplete.mdx index d1ea3635e..818261ac5 100644 --- a/docs/customize/deep-dives/autocomplete.mdx +++ b/docs/customize/deep-dives/autocomplete.mdx @@ -84,7 +84,7 @@ Then, add the model to your configuration: Once the model has been downloaded, you should begin to see completions in VS Code. -NOTE: Typically, thinking-type models are not recommended as they generate more slowly and are not suitable for scenarios that require speed. +NOTE: Typically, thinking-type models are not recommended as they generate more slowly and are not suitable for scenarios that require speed. However, if you use any thinking-switchable models, you can configure these models for autocomplete functions by turning off the thinking mode. @@ -92,7 +92,7 @@ For example: - ```yaml title="config.yaml" +```yaml title="config.yaml" models: - name: Qwen3 without Thinking for Autocomplete provider: ollama @@ -122,9 +122,32 @@ The following settings can be configured for autocompletion in the IDE extension - `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto` - `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt" -### `config.json` Configuration +### Autocomplete Configuration -The `config.json` configuration format (deprecated) offers further configuration options through `tabAutocompleteOptions`. See the [JSON Reference](/reference) for more details. +#### YAML Configuration + +The `config.yaml` format offers model-level configuration using the `autocompleteOptions` field. See the [YAML Reference](/reference#models) for more details. + +```yaml +models: + - name: Codestral + provider: mistral + model: codestral-latest + roles: + - autocomplete + autocompleteOptions: + disable: false + maxPromptTokens: 1024 + debounceDelay: 250 + modelTimeout: 150 + maxSuffixPercentage: 0.2 + prefixPercentage: 0.3 + onlyMyCode: true +``` + +#### JSON Configuration (Deprecated) + +The `config.json` configuration format offers configuration options through `tabAutocompleteOptions`. See the [JSON Reference](/reference/json-reference#tabautocomplete-options) for more details. ## FAQs diff --git a/docs/reference.mdx b/docs/reference.mdx index 1a827dc60..c96bd7d96 100644 --- a/docs/reference.mdx +++ b/docs/reference.mdx @@ -175,6 +175,7 @@ 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 @@ -228,6 +229,21 @@ The `models` section defines the language models used in your configuration. Mod - `key`: Path to the client certificate key file. - `passphrase`: Optional passphrase for the client certificate key file. +- `autocompleteOptions`: If the model includes role `autocomplete`, these settings apply for tab autocompletion: + + - `disable`: If `true`, disables autocomplete for this model. + - `maxPromptTokens`: Maximum number of tokens for the autocomplete prompt. + - `debounceDelay`: Delay before triggering autocomplete in milliseconds. + - `modelTimeout`: Model timeout for autocomplete requests in milliseconds. + - `maxSuffixPercentage`: Maximum percentage of prompt allocated for suffix. + - `prefixPercentage`: Percentage of input allocated for prefix. + - `template`: Custom template for autocomplete using Mustache syntax. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables. + - `onlyMyCode`: Only includes code within the repository for context. + - `useCache`: If `true`, enables caching for completions. + - `useImports`: If `true`, includes imports in context. + - `useRecentlyEdited`: If `true`, includes recently edited files in context. + - `useRecentlyOpened`: If `true`, includes recently opened files in context. + **Example:** ```yaml title="config.yaml" @@ -247,6 +263,10 @@ models: model: codestral-latest roles: - autocomplete + autocompleteOptions: + debounceDelay: 250 + maxPromptTokens: 1024 + onlyMyCode: true - name: My Model - OpenAI-Compatible provider: openai apiBase: http://my-endpoint/v1 @@ -456,6 +476,10 @@ models: model: starcoder roles: - autocomplete + autocompleteOptions: + debounceDelay: 350 + maxPromptTokens: 1024 + onlyMyCode: true defaultCompletionOptions: temperature: 0.3 stop: @@ -531,4 +555,8 @@ models: useLegacyCompletionsEndpoint: false roles: - autocomplete + autocompleteOptions: + debounceDelay: 350 + maxPromptTokens: 1024 + onlyMyCode: true ``` diff --git a/docs/reference/json-reference.mdx b/docs/reference/json-reference.mdx index 319b91e38..54fa4d64a 100644 --- a/docs/reference/json-reference.mdx +++ b/docs/reference/json-reference.mdx @@ -107,6 +107,12 @@ config.json Specifies options for tab autocompletion behavior. + + **Note**: Many of these parameters can also be configured per-model using the + `autocompleteOptions` field in `config.yaml`. See the [YAML + Reference](/reference#models) for more details. + + **Properties:** - `disable`: If `true`, disables tab autocomplete (default: `false`). diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 175993fa2..6ca982585 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,6 +1,6 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginRepositoryUrl=https://github.com/continuedev/continue -pluginVersion=1.0.34 +pluginVersion=1.0.36 pluginSinceBuild=223 platformType=IC platformVersion=2022.3.3 diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt index adcc86f7f..71e73369f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt @@ -1,29 +1,27 @@ package com.github.continuedev.continueintellijextension.listeners import ToolTipComponent -import com.github.continuedev.continueintellijextension.editor.EditorUtils import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.utils.Debouncer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.editor.event.SelectionEvent import com.intellij.openapi.editor.event.SelectionListener -import com.intellij.openapi.project.DumbAware -import com.intellij.openapi.util.TextRange -import kotlinx.coroutines.CoroutineScope -import com.intellij.openapi.editor.Document -import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor +import com.intellij.openapi.project.DumbAware +import com.intellij.openapi.util.TextRange +import kotlinx.coroutines.CoroutineScope class ContinuePluginSelectionListener( coroutineScope: CoroutineScope, ) : SelectionListener, DumbAware { - private val debouncer = Debouncer(100, coroutineScope) + private val debouncer = Debouncer(200, coroutineScope) private var toolTipComponents: ArrayList = ArrayList() private var lastActiveEditor: Editor? = null @@ -228,5 +226,3 @@ class ContinuePluginSelectionListener( editor.contentComponent.repaint() } } - - diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 9d15d1bb6..1282f2cd4 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.75", + "version": "1.1.76", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/gui/src/components/config/FatalErrorNotice.tsx b/gui/src/components/config/FatalErrorNotice.tsx index 8c0a346c2..3d528e810 100644 --- a/gui/src/components/config/FatalErrorNotice.tsx +++ b/gui/src/components/config/FatalErrorNotice.tsx @@ -32,10 +32,10 @@ export const FatalErrorIndicator = () => { return null; } - const displayName = - selectedProfile?.title ?? - `${selectedProfile?.fullSlug?.ownerSlug}/${selectedProfile?.fullSlug?.packageSlug}` ?? - "assistant"; + const displayName = selectedProfile + ? (selectedProfile.title ?? + `${selectedProfile.fullSlug?.ownerSlug}/${selectedProfile.fullSlug?.packageSlug}`) + : "agent"; return ( diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index f9638b37f..8db383dd3 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -32,6 +32,7 @@ import FileIcon from "../../FileIcon"; import SafeImg from "../../SafeImg"; import AddDocsDialog from "../../dialogs/AddDocsDialog"; import HeaderButtonWithToolTip from "../../gui/HeaderButtonWithToolTip"; +import { Button } from "../../ui"; import { NAMED_ICONS } from "../icons"; import type { ComboBoxItem, ComboBoxItemType } from "../types"; @@ -117,6 +118,7 @@ const QueryInput = styled.textarea` background-color: #fff1; border: 1px solid ${lightGray}; border-radius: ${defaultBorderRadius}; + overflow: hidden; padding: 0.2rem 0.4rem; width: 240px; @@ -243,7 +245,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { .run(); // Trigger warning message - ideMessenger.ide.showToast( + void ideMessenger.ide.showToast( "warning", fileSize > 0 ? "File exceeds model's context length" @@ -368,8 +370,9 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { if (item) { if (item.type === "file" && item.query) { - isItemTooBig(item.type, item.query).then(([fileExceeds, fileSize]) => - handleItemTooBig(fileExceeds, fileSize, item), + void isItemTooBig(item.type, item.query).then( + ([fileExceeds, fileSize]) => + handleItemTooBig(fileExceeds, fileSize, item), ); } else { props.command({ ...item, itemType: item.type }); @@ -456,34 +459,53 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { return ( {querySubmenuItem ? ( - { - e.stopPropagation(); - }} - rows={1} - ref={queryInputRef} - placeholder={querySubmenuItem.description} - onKeyDown={(e) => { - if (!queryInputRef.current) { - return; - } - if (e.key === "Enter") { - if (e.shiftKey) { - queryInputRef.current.innerText += "\n"; - } else { - props.command({ - ...querySubmenuItem, - itemType: querySubmenuItem.type, - query: queryInputRef.current.value, - label: `${querySubmenuItem.label}: ${queryInputRef.current.value}`, - }); + + { + e.stopPropagation(); + }} + rows={1} + ref={queryInputRef} + placeholder={querySubmenuItem.description} + onKeyDown={(e) => { + if (!queryInputRef.current) { + return; } - } else if (e.key === "Escape") { - setQuerySubmenuItem(undefined); - setSubMenuTitle(undefined); + if (e.key === "Enter") { + if (e.shiftKey) { + queryInputRef.current.innerText += "\n"; + } else { + props.command({ + ...querySubmenuItem, + itemType: querySubmenuItem.type, + query: queryInputRef.current.value, + label: `${querySubmenuItem.label}: ${queryInputRef.current.value}`, + }); + } + } else if (e.key === "Escape") { + setQuerySubmenuItem(undefined); + setSubMenuTitle(undefined); + } + }} + /> + + ) : ( <> {subMenuTitle && {subMenuTitle}} diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index b5c4bbae5..be50ef6f5 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -330,6 +330,32 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["nebius"], isOpenSource: true, }, + exaone32B: { + title: "EXAONE 4.0.1-32B", + description: + "LG AI Research's 32B model with integrated reasoning and agentic tool use capabilities.", + refUrl: "https://huggingface.co/LGAI-EXAONE/EXAONE-4.0.1-32B", + params: { + title: "EXAONE-4.0.1-32B", + model: "LGAI-EXAONE/EXAONE-4.0.1-32B", + contextLength: 131072, + }, + providerOptions: ["openai"], + isOpenSource: true, + }, + exaone12B: { + title: "EXAONE 4.0-1.2B", + description: + "Compact EXAONE 4.0 model suitable for on-device use while retaining tool calling support.", + refUrl: "https://huggingface.co/LGAI-EXAONE/EXAONE-4.0-1.2B", + params: { + title: "EXAONE-4.0-1.2B", + model: "LGAI-EXAONE/EXAONE-4.0-1.2B", + contextLength: 65536, + }, + providerOptions: ["openai"], + isOpenSource: true, + }, moonshotChat: { title: "Moonshot Chat", description: "Moonshot AI provides high-performance large language models", @@ -653,7 +679,6 @@ export const models: { [key: string]: ModelPackage } = { model: "granite-code", contextLength: 20_000, title: "Granite Code", - systemMessage: `You are Granite Chat, an AI language model developed by IBM. You are a cautious assistant. You carefully follow instructions. You are helpful and harmless and you follow ethical guidelines and promote positive behavior. You always respond to greetings (for example, hi, hello, g'day, morning, afternoon, evening, night, what's up, nice to meet you, sup, etc) with "Hello! I am Granite Chat, created by IBM. How can I help you today?". Please do not say anything else and do not start a conversation.`, }, providerOptions: ["ollama", "lmstudio", "llama.cpp", "replicate"], icon: "ibm.png", @@ -1128,8 +1153,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-4o", contextLength: 128_000, title: "GPT-4o", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["openai", "askSage"], icon: "openai.png", @@ -1143,8 +1166,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-4o-mini", contextLength: 128_000, title: "GPT-4o mini", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["openai", "askSage"], icon: "openai.png", @@ -1398,8 +1419,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt4-gov", contextLength: 128_000, title: "GPT-4 gov", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed }, providerOptions: ["askSage"], icon: "openai.png", @@ -1413,8 +1432,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-4o-gov", contextLength: 128_000, title: "GPT-4o-gov", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed }, providerOptions: ["askSage"], icon: "openai.png", @@ -1427,8 +1444,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-gov", contextLength: 8096, title: "GPT-3.5-Turbo gov", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed }, providerOptions: ["askSage"], icon: "openai.png", @@ -1442,8 +1457,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-4o-mini-gov", contextLength: 128_000, title: "GPT-4o-mini gov", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed }, providerOptions: ["askSage"], icon: "openai.png", @@ -1483,8 +1496,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-o1", contextLength: 128_000, title: "GPT-o1", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["askSage"], icon: "openai.png", @@ -1498,8 +1509,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-o1-mini", contextLength: 128_000, title: "GPT-o1-mini", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["askSage"], icon: "openai.png", @@ -1513,8 +1522,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-o3-mini", contextLength: 200_000, title: "GPT-o3-mini", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["askSage"], icon: "openai.png", @@ -1528,8 +1535,6 @@ export const models: { [key: string]: ModelPackage } = { model: "aws-bedrock-claude-35-sonnet-gov", contextLength: 200_000, title: "Claude 3.5 Sonnet gov", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["askSage"], icon: "anthropic.png", diff --git a/gui/src/pages/config/IndexingSettingsSection.tsx b/gui/src/pages/config/IndexingSettingsSection.tsx index 4e4c670c0..6df4faed0 100644 --- a/gui/src/pages/config/IndexingSettingsSection.tsx +++ b/gui/src/pages/config/IndexingSettingsSection.tsx @@ -15,7 +15,7 @@ export function IndexingSettingsSection() {

Indexing is disabled

- Open settings and toggle Disable Indexing to re-enable + Open settings and toggle Enable Indexing to re-enable

) : ( diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index 576a6d1c6..28ab1947a 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -20,6 +20,7 @@ import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { updateConfig } from "../../redux/slices/configSlice"; +import { selectCurrentOrg } from "../../redux/slices/profilesSlice"; import { setLocalStorage } from "../../util/localStorage"; import { ContinueFeaturesMenu } from "./ContinueFeaturesMenu"; @@ -28,6 +29,8 @@ export function UserSettingsForm() { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const config = useAppSelector((state) => state.config.config); + const currentOrg = useAppSelector(selectCurrentOrg); + const [showExperimental, setShowExperimental] = useState(false); const { session } = useAuth(); @@ -133,6 +136,9 @@ export function UserSettingsForm() { "@continue.dev", ); + const disableTelemetryToggle = + currentOrg?.policy?.allowAnonymousTelemetry === false; + return (
{/* {selectedProfile && isLocalProfile(selectedProfile) ? ( @@ -225,6 +231,7 @@ export function UserSettingsForm() { handleUpdate({ allowAnonymousTelemetry: !allowAnonymousTelemetry, diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 11c1ca20c..a22bb00bb 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -151,6 +151,16 @@ export const tabAutocompleteOptionsSchema = z.object({ useRecentlyEdited: z.boolean(), disableInFiles: z.array(z.string()).optional(), useImports: z.boolean().optional(), + // Experimental options: true = enabled, false = disabled, number = enabled w priority + experimental_includeClipboard: z.union([z.boolean(), z.number()]).optional(), + experimental_includeRecentlyVisitedRanges: z + .union([z.boolean(), z.number()]) + .optional(), + experimental_includeRecentlyEditedRanges: z + .union([z.boolean(), z.number()]) + .optional(), + experimental_includeDiff: z.union([z.boolean(), z.number()]).optional(), + experimental_enableStaticContextualization: z.boolean().optional(), }); export type TabAutocompleteOptions = z.infer< typeof tabAutocompleteOptionsSchema diff --git a/packages/config-yaml/src/browser.ts b/packages/config-yaml/src/browser.ts index b8c5cca1b..9edef65aa 100644 --- a/packages/config-yaml/src/browser.ts +++ b/packages/config-yaml/src/browser.ts @@ -15,4 +15,5 @@ export * from "./modelName.js"; export * from "./schemas/data/index.js"; export * from "./schemas/index.js"; export * from "./schemas/models.js"; +export * from "./schemas/policy.js"; export * from "./validation.js"; diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 0693675a2..d5af3bfaa 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -120,6 +120,16 @@ export const autocompleteOptionsSchema = z.object({ prefixPercentage: z.number().optional(), template: z.string().optional(), onlyMyCode: z.boolean().optional(), + useCache: z.boolean().optional(), + useImports: z.boolean().optional(), + useRecentlyEdited: z.boolean().optional(), + useRecentlyOpened: z.boolean().optional(), + // Experimental options: true = enabled, false = disabled, number = enabled w priority + experimental_includeClipboard: z.boolean().optional(), + experimental_includeRecentlyVisitedRanges: z.boolean().optional(), + experimental_includeRecentlyEditedRanges: z.boolean().optional(), + experimental_includeDiff: z.boolean().optional(), + experimental_enableStaticContextualization: z.boolean().optional(), }); /** Prompt templates use Handlebars syntax */ diff --git a/packages/config-yaml/src/schemas/policy.ts b/packages/config-yaml/src/schemas/policy.ts new file mode 100644 index 000000000..c9b3d3a0b --- /dev/null +++ b/packages/config-yaml/src/schemas/policy.ts @@ -0,0 +1,9 @@ +import * as z from "zod"; + +export const policySchema = z.object({ + allowAnonymousTelemetry: z.boolean().optional(), + allowOtherOrgs: z.boolean().optional(), + // allowLocalConfigFile: z.boolean().optional(), +}); + +export type Policy = z.infer;