Merge branch 'main' into nate/quick-edit-f4d8
This commit is contained in:
commit
d389bb791e
96 changed files with 1946 additions and 1104 deletions
|
|
@ -6,6 +6,7 @@
|
|||
},
|
||||
"plugins": ["@typescript-eslint", "import"],
|
||||
"rules": {
|
||||
"@typescript-eslint/naming-convention": "off",
|
||||
"@typescript-eslint/semi": "warn",
|
||||
"curly": "warn",
|
||||
"eqeqeq": "warn",
|
||||
|
|
|
|||
23
.github/ISSUE_TEMPLATE/docs_issue_report.yml
vendored
23
.github/ISSUE_TEMPLATE/docs_issue_report.yml
vendored
|
|
@ -58,26 +58,3 @@ body:
|
|||
label: Expected Content
|
||||
description: If applicable, provide the content you believe should be added or updated.
|
||||
placeholder: "Suggested details or changes for the documentation..."
|
||||
|
||||
- type: textarea
|
||||
id: additional-info
|
||||
attributes:
|
||||
label: Additional Information
|
||||
description: Add any other relevant information that may help us understand and resolve your issue.
|
||||
placeholder: "Additional context, screenshots, or related links..."
|
||||
|
||||
- type: input
|
||||
id: related-issue
|
||||
attributes:
|
||||
label: Related Issue
|
||||
description: If this issue is related to an existing GitHub issue, provide the issue number.
|
||||
placeholder: "#123"
|
||||
|
||||
- type: checkboxes
|
||||
id: terms
|
||||
attributes:
|
||||
label: Code of Conduct
|
||||
description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/continuedev/continue/blob/main/CODE_OF_CONDUCT.md)
|
||||
options:
|
||||
- label: I agree to follow this project's Code of Conduct
|
||||
required: true
|
||||
|
|
@ -188,7 +188,7 @@ After you've written your context provider, make sure to complete the following:
|
|||
|
||||
### Adding an LLM Provider
|
||||
|
||||
Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, Novita AI, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps:
|
||||
Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps:
|
||||
|
||||
1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example.
|
||||
|
||||
|
|
@ -209,7 +209,7 @@ While any model that works with a supported provider can be used with Continue,
|
|||
1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file
|
||||
2. Add the model within its provider's array to [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed)
|
||||
- [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this.
|
||||
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), [Novita AI](./core/llm/llms/Novita.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Novita AI](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), [Replicate](https://replicate.com/collections/streaming-language-models).
|
||||
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
|
||||
- [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates.
|
||||
|
||||
### Adding Pre-indexed Documentation
|
||||
|
|
|
|||
|
|
@ -59,8 +59,8 @@ export async function testAutocompleteFiltering(
|
|||
line,
|
||||
character,
|
||||
},
|
||||
recentlyEditedFiles: [],
|
||||
recentlyEditedRanges: [],
|
||||
recentlyVisitedRanges: [],
|
||||
};
|
||||
|
||||
// Generate a completion
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { findUriInDirs } from "../../util/uri";
|
|||
import { ContextRetrievalService } from "../context/ContextRetrievalService";
|
||||
import { GetLspDefinitionsFunction } from "../types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
import {
|
||||
AutocompleteClipboardSnippet,
|
||||
AutocompleteCodeSnippet,
|
||||
|
|
@ -15,6 +16,7 @@ export interface SnippetPayload {
|
|||
importDefinitionSnippets: AutocompleteCodeSnippet[];
|
||||
ideSnippets: AutocompleteCodeSnippet[];
|
||||
recentlyEditedRangeSnippets: AutocompleteCodeSnippet[];
|
||||
recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[];
|
||||
diffSnippets: AutocompleteDiffSnippet[];
|
||||
clipboardSnippets: AutocompleteClipboardSnippet[];
|
||||
}
|
||||
|
|
@ -135,5 +137,6 @@ export const getAllSnippets = async ({
|
|||
recentlyEditedRangeSnippets,
|
||||
diffSnippets,
|
||||
clipboardSnippets,
|
||||
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -111,13 +111,13 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
|
|||
return snippet.content;
|
||||
}
|
||||
|
||||
return `+++++ ${relativePaths[i]}\n${snippet.content}`;
|
||||
return `+++++ ${relativePaths[i].uri} \n${snippet.content}`;
|
||||
})
|
||||
.join("\n\n");
|
||||
|
||||
return [
|
||||
`${otherFiles}\n\n+++++ ${
|
||||
relativePaths[relativePaths.length - 1]
|
||||
relativePaths[relativePaths.length - 1].uri
|
||||
}\n${prefix}`,
|
||||
suffix,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
AutocompleteSnippet,
|
||||
} from "../snippets/types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
import { isValidSnippet } from "./validation";
|
||||
|
||||
const getRemainingTokenCount = (helper: HelperVars): number => {
|
||||
|
|
@ -44,6 +45,7 @@ export const getSnippets = (
|
|||
const snippets = [
|
||||
...payload.diffSnippets,
|
||||
...payload.clipboardSnippets,
|
||||
...payload.recentlyVisitedRangesSnippets,
|
||||
...shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
RangeInFileWithContents,
|
||||
TabAutocompleteOptions,
|
||||
} from "../..";
|
||||
import { AutocompleteCodeSnippet } from "../snippets/types";
|
||||
|
||||
export type RecentlyEditedRange = RangeInFile & {
|
||||
timestamp: number;
|
||||
|
|
@ -17,7 +18,7 @@ export interface AutocompleteInput {
|
|||
completionId: string;
|
||||
filepath: string;
|
||||
pos: Position;
|
||||
recentlyEditedFiles: RangeInFileWithContents[];
|
||||
recentlyVisitedRanges: AutocompleteCodeSnippet[];
|
||||
recentlyEditedRanges: RecentlyEditedRange[];
|
||||
// Used for notebook files
|
||||
manuallyPassFileContents?: string;
|
||||
|
|
|
|||
|
|
@ -46,6 +46,8 @@ import CustomLLMClass from "../llm/llms/CustomLLM";
|
|||
import FreeTrial from "../llm/llms/FreeTrial";
|
||||
import { LLMReranker } from "../llm/llms/llm";
|
||||
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
|
||||
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
|
||||
import { allTools } from "../tools";
|
||||
import { copyOf } from "../util";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
|
|
@ -61,8 +63,6 @@ import {
|
|||
getEsbuildBinaryPath,
|
||||
} from "../util/paths";
|
||||
|
||||
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
|
||||
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
|
||||
import {
|
||||
defaultContextProvidersJetBrains,
|
||||
defaultContextProvidersVsCode,
|
||||
|
|
@ -70,6 +70,7 @@ import {
|
|||
defaultSlashCommandsVscode,
|
||||
} from "./default";
|
||||
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
|
||||
import { isSupportedLanceDbCpuTarget } from "./util";
|
||||
import { ConfigValidationError, validateConfig } from "./validation.js";
|
||||
|
||||
export interface ConfigResult<T> {
|
||||
|
|
@ -112,6 +113,7 @@ function loadSerializedConfig(
|
|||
ideSettings: IdeSettings,
|
||||
ideType: IdeType,
|
||||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
ide: IDE,
|
||||
): ConfigResult<SerializedContinueConfig> {
|
||||
const configPath = getConfigJsonPath(ideType);
|
||||
let config: SerializedContinueConfig = overrideConfigJson!;
|
||||
|
|
@ -174,6 +176,10 @@ function loadSerializedConfig(
|
|||
? [...defaultSlashCommandsVscode]
|
||||
: [...defaultSlashCommandsJetBrains];
|
||||
|
||||
if (!isSupportedLanceDbCpuTarget(ide)) {
|
||||
config.disableIndexing = true;
|
||||
}
|
||||
|
||||
return { config, errors, configLoadInterrupted: false };
|
||||
}
|
||||
|
||||
|
|
@ -767,6 +773,7 @@ async function loadFullConfigNode(
|
|||
ideSettings,
|
||||
ideType,
|
||||
overrideConfigJson,
|
||||
ide,
|
||||
);
|
||||
|
||||
if (!serialized || configLoadInterrupted) {
|
||||
|
|
|
|||
|
|
@ -717,7 +717,6 @@ declare global {
|
|||
|
||||
type ContextProviderName =
|
||||
| "diff"
|
||||
| "github"
|
||||
| "terminal"
|
||||
| "debugger"
|
||||
| "open"
|
||||
|
|
|
|||
|
|
@ -1,10 +1,15 @@
|
|||
import { execSync } from "child_process";
|
||||
import os from "os";
|
||||
|
||||
import {
|
||||
ContextProviderWithParams,
|
||||
ContinueConfig,
|
||||
IDE,
|
||||
ILLM,
|
||||
ModelDescription,
|
||||
ModelRoles,
|
||||
} from "../";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { editConfigJson } from "../util/paths";
|
||||
|
||||
function stringify(obj: any, indentation?: number): string {
|
||||
|
|
@ -96,3 +101,84 @@ export function getModelByRole<T extends keyof ModelRoles>(
|
|||
|
||||
return matchingModel;
|
||||
}
|
||||
|
||||
/**
|
||||
* This check is to determine if the user is on an unsupported CPU
|
||||
* target for our Lance DB binaries.
|
||||
*
|
||||
* See here for details: https://github.com/continuedev/continue/issues/940
|
||||
*/
|
||||
export function isSupportedLanceDbCpuTarget(ide: IDE) {
|
||||
const CPU_FEATURES_TO_CHECK = ["avx2", "fma"] as const;
|
||||
|
||||
const globalContext = new GlobalContext();
|
||||
const globalContextVal = globalContext.get("isSupportedLanceDbCpuTarget");
|
||||
|
||||
// If we've already checked the CPU target, return the cached value
|
||||
if (globalContextVal !== undefined) {
|
||||
return globalContextVal;
|
||||
}
|
||||
|
||||
const arch = os.arch();
|
||||
const platform = os.platform();
|
||||
|
||||
// This check only applies to x64
|
||||
//https://github.com/lancedb/lance/issues/2195#issuecomment-2057841311
|
||||
if (arch !== "x64") {
|
||||
globalContext.update("isSupportedLanceDbCpuTarget", true);
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const cpuFlags = (() => {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return execSync("sysctl -n machdep.cpu.features")
|
||||
.toString()
|
||||
.toLowerCase();
|
||||
case "linux":
|
||||
return execSync("cat /proc/cpuinfo").toString().toLowerCase();
|
||||
case "win32":
|
||||
return execSync("wmic cpu get caption /format:list")
|
||||
.toString()
|
||||
.toLowerCase();
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
})();
|
||||
|
||||
const isSupportedLanceDbCpuTarget = cpuFlags
|
||||
? CPU_FEATURES_TO_CHECK.every((feature) => cpuFlags.includes(feature))
|
||||
: true;
|
||||
|
||||
// If it's not a supported CPU target, and it's the first time we are checking,
|
||||
// show a toast to inform the user that we are going to disable indexing.
|
||||
if (!isSupportedLanceDbCpuTarget) {
|
||||
// We offload our async toast to `showUnsupportedCpuToast` to prevent making
|
||||
// our config loading async upstream of `isSupportedLanceDbCpuTarget`
|
||||
void showUnsupportedCpuToast(ide);
|
||||
}
|
||||
|
||||
globalContext.update(
|
||||
"isSupportedLanceDbCpuTarget",
|
||||
isSupportedLanceDbCpuTarget,
|
||||
);
|
||||
|
||||
return isSupportedLanceDbCpuTarget;
|
||||
} catch (error) {
|
||||
// If we can't determine CPU features, default to true
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
async function showUnsupportedCpuToast(ide: IDE) {
|
||||
const shouldOpenLink = await ide.showToast(
|
||||
"warning",
|
||||
"Codebase indexing is disabled due to CPU incompatibility",
|
||||
"Learn more",
|
||||
);
|
||||
|
||||
if (shouldOpenLink) {
|
||||
void ide.openUrl("https://github.com/continuedev/continue/pull/3551");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ class DebugLocalsProvider extends BaseContextProvider {
|
|||
static description: ContextProviderDescription = {
|
||||
title: "debugger",
|
||||
displayTitle: "Debugger",
|
||||
description: "Reference the contents of the local variables in the debugger",
|
||||
description: "Local variables",
|
||||
type: "submenu",
|
||||
renderInlineAs: "",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -17,7 +17,9 @@ class DiffContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const diff = await extras.ide.getDiff(this.options.includeUnstaged ?? true);
|
||||
const diff = await extras.ide.getDiff(
|
||||
this.options?.includeUnstaged ?? true,
|
||||
);
|
||||
return [
|
||||
{
|
||||
description: "The current git diff",
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ class DiscordContextProvider extends BaseContextProvider {
|
|||
static description: ContextProviderDescription = {
|
||||
title: "discord",
|
||||
displayTitle: "Discord",
|
||||
description: "Reference Discord messages from a channel",
|
||||
description: "Select a channel",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -80,6 +80,8 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const useReranking = this.options?.useReranking ?? true;
|
||||
|
||||
// Get docs service
|
||||
const docsService = DocsService.getSingleton();
|
||||
if (!docsService) {
|
||||
|
|
@ -101,8 +103,8 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
// We found chunks, so check if there's a favicon for the docs page
|
||||
const favicon = await docsService.getFavicon(query);
|
||||
|
||||
// Rerank if there's a rerankder
|
||||
if (extras.reranker) {
|
||||
// Rerank if there's a reranker
|
||||
if (useReranking && extras.reranker) {
|
||||
chunks = await this._rerankChunks(
|
||||
chunks,
|
||||
extras.reranker,
|
||||
|
|
|
|||
|
|
@ -38,7 +38,10 @@ class RepoMapContextProvider extends BaseContextProvider {
|
|||
content: await generateRepoMap(extras.llm, extras.ide, {
|
||||
dirUris: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query],
|
||||
outputRelativeUriPaths: true,
|
||||
includeSignatures: false,
|
||||
// Doesn't ALWAYS depend on indexing, so not setting dependsOnIndexing = true, just checking for it
|
||||
includeSignatures: extras.config.disableIndexing
|
||||
? false
|
||||
: (this.options?.includeSignatures ?? false),
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { BaseContextProvider } from "../";
|
||||
import { ContextProviderName } from "../../";
|
||||
import ClipboardContextProvider from "./ClipboardContextProvider";
|
||||
|
||||
import ClipboardContextProvider from "./ClipboardContextProvider";
|
||||
import CodeContextProvider from "./CodeContextProvider";
|
||||
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
|
||||
import CurrentFileContextProvider from "./CurrentFileContextProvider";
|
||||
|
|
|
|||
29
core/core.ts
29
core/core.ts
|
|
@ -2,10 +2,12 @@ import path from "path";
|
|||
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import ignore from "ignore";
|
||||
import * as URI from "uri-js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { CompletionProvider } from "./autocomplete/CompletionProvider";
|
||||
import { ConfigHandler } from "./config/ConfigHandler";
|
||||
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
|
||||
import {
|
||||
setupBestConfig,
|
||||
setupLocalConfig,
|
||||
|
|
@ -26,6 +28,7 @@ import Ollama from "./llm/llms/Ollama";
|
|||
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
|
||||
import { callTool } from "./tools/callTool";
|
||||
import { ChatDescriber } from "./util/chatDescriber";
|
||||
import { clipboardCache } from "./util/clipboardCache";
|
||||
import { logDevData } from "./util/devdata";
|
||||
import { DevDataSqliteDb } from "./util/devdataSqlite";
|
||||
import { GlobalContext } from "./util/GlobalContext";
|
||||
|
|
@ -35,18 +38,15 @@ import {
|
|||
getConfigJsonPath,
|
||||
setupInitialDotContinueDirectory,
|
||||
} from "./util/paths";
|
||||
import { localPathToUri } from "./util/pathToUri";
|
||||
import { Telemetry } from "./util/posthog";
|
||||
import { getSymbolsForManyFiles } from "./util/treeSitter";
|
||||
import { TTS } from "./util/tts";
|
||||
|
||||
import { type ContextItemId, type IDE, type IndexingProgressUpdate } from ".";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
|
||||
import * as URI from "uri-js";
|
||||
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
import { localPathToUri } from "./util/pathToUri";
|
||||
import { clipboardCache } from "./util/clipboardCache";
|
||||
|
||||
export class Core {
|
||||
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
|
||||
|
|
@ -299,7 +299,6 @@ export class Core {
|
|||
});
|
||||
|
||||
on("context/loadSubmenuItems", async (msg) => {
|
||||
console.log("Load SUMBENU ITEMS", msg);
|
||||
const config = await this.config();
|
||||
if (!config) {
|
||||
return [];
|
||||
|
|
@ -384,9 +383,12 @@ export class Core {
|
|||
});
|
||||
|
||||
on("clipboardCache/add", (msg) => {
|
||||
console.log("ADD TO CLIPBOARD", msg);
|
||||
clipboardCache.add(uuidv4(), msg.data.content);
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
const added = clipboardCache.add(uuidv4(), msg.data.content);
|
||||
if (added) {
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: ["clipboard"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
async function* llmStreamChat(
|
||||
|
|
@ -665,7 +667,6 @@ export class Core {
|
|||
abortedMessageIds.delete(msg.messageId);
|
||||
break;
|
||||
}
|
||||
console.log(diffLine);
|
||||
yield { content: diffLine };
|
||||
}
|
||||
|
||||
|
|
@ -948,7 +949,9 @@ export class Core {
|
|||
}
|
||||
}
|
||||
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: "dependsOnIndexing",
|
||||
});
|
||||
this.indexingCancellationController = undefined;
|
||||
}
|
||||
|
||||
|
|
@ -979,7 +982,9 @@ export class Core {
|
|||
}
|
||||
}
|
||||
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: "dependsOnIndexing",
|
||||
});
|
||||
}
|
||||
|
||||
// private
|
||||
|
|
|
|||
17
core/index.d.ts
vendored
17
core/index.d.ts
vendored
|
|
@ -216,6 +216,10 @@ export interface ContextSubmenuItem {
|
|||
metadata?: any;
|
||||
}
|
||||
|
||||
export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem {
|
||||
providerTitle: string;
|
||||
}
|
||||
|
||||
export interface SiteIndexingConfig {
|
||||
title: string;
|
||||
startUrl: string;
|
||||
|
|
@ -630,7 +634,7 @@ export interface IDE {
|
|||
|
||||
openUrl(url: string): Promise<void>;
|
||||
|
||||
runCommand(command: string): Promise<void>;
|
||||
runCommand(command: string, options?: TerminalOptions): Promise<void>;
|
||||
|
||||
saveFile(fileUri: string): Promise<void>;
|
||||
|
||||
|
|
@ -724,7 +728,6 @@ export type StepName =
|
|||
|
||||
export type ContextProviderName =
|
||||
| "diff"
|
||||
| "github"
|
||||
| "terminal"
|
||||
| "debugger"
|
||||
| "open"
|
||||
|
|
@ -751,6 +754,8 @@ export type ContextProviderName =
|
|||
| "issue"
|
||||
| "repo-map"
|
||||
| "url"
|
||||
| "web"
|
||||
| "discord"
|
||||
| "clipboard"
|
||||
| string;
|
||||
|
||||
|
|
@ -1066,7 +1071,6 @@ export interface ExperimentalConfig {
|
|||
* This is needed to crawl a large number of documentation sites that are dynamically rendered.
|
||||
*/
|
||||
useChromiumForDocsCrawling?: boolean;
|
||||
useTools?: boolean;
|
||||
modelContextProtocolServers?: MCPOptions[];
|
||||
}
|
||||
|
||||
|
|
@ -1230,4 +1234,9 @@ export type PackageDocsResult = {
|
|||
} & (
|
||||
| { error: string; details?: never }
|
||||
| { details: PackageDetailsSuccess; error?: never }
|
||||
);
|
||||
);
|
||||
|
||||
export interface TerminalOptions {
|
||||
reuseTerminal?: boolean,
|
||||
terminalName?: string,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -580,9 +580,9 @@ export default class DocsService {
|
|||
|
||||
void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
|
||||
|
||||
if (this.messenger) {
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
}
|
||||
this.messenger?.send("refreshSubmenuItems", {
|
||||
providers: ["docs"],
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Error indexing docs", e);
|
||||
this.handleStatusUpdate({
|
||||
|
|
@ -1055,6 +1055,8 @@ export default class DocsService {
|
|||
this.abort(startUrl);
|
||||
await this.deleteIndexes(startUrl);
|
||||
this.deleteFromConfig(startUrl);
|
||||
this.messenger?.send("refreshSubmenuItems", undefined);
|
||||
this.messenger?.send("refreshSubmenuItems", {
|
||||
providers: ["docs"],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ import {
|
|||
xWinCoderEditPrompt,
|
||||
zephyrEditPrompt,
|
||||
} from "./templates/edit.js";
|
||||
import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js";
|
||||
|
||||
const PROVIDER_HANDLES_TEMPLATING: string[] = [
|
||||
"lmstudio",
|
||||
|
|
@ -87,11 +88,11 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
|
|||
];
|
||||
|
||||
function modelSupportsTools(modelName: string, provider: string) {
|
||||
return (
|
||||
provider === "anthropic" &&
|
||||
modelName.includes("claude") &&
|
||||
(modelName.includes("3-5") || modelName.includes("3.5"))
|
||||
);
|
||||
const providerSupport = PROVIDER_TOOL_SUPPORT[provider];
|
||||
if (!providerSupport) {
|
||||
return false;
|
||||
}
|
||||
return providerSupport(modelName) ?? false;
|
||||
}
|
||||
|
||||
function modelSupportsImages(
|
||||
|
|
|
|||
|
|
@ -71,20 +71,17 @@ function constructSystemPrompt(
|
|||
provider: string,
|
||||
useTools: boolean,
|
||||
): string | null {
|
||||
if (
|
||||
useTools &&
|
||||
CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))
|
||||
) {
|
||||
return SYSTEM_MESSAGE + "\n\n" + TOOL_USE_RULES;
|
||||
} else if (
|
||||
CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))
|
||||
) {
|
||||
return SYSTEM_MESSAGE;
|
||||
} else if (useTools && modelSupportsTools(model, provider)) {
|
||||
return TOOL_USE_RULES;
|
||||
let systemMessage = "";
|
||||
if (CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))) {
|
||||
systemMessage = SYSTEM_MESSAGE;
|
||||
}
|
||||
|
||||
return null;
|
||||
if (useTools && modelSupportsTools(model, provider)) {
|
||||
if (systemMessage) {
|
||||
systemMessage += "\n\n";
|
||||
}
|
||||
systemMessage += TOOL_USE_RULES;
|
||||
}
|
||||
return systemMessage || null;
|
||||
}
|
||||
|
||||
const CANCELED_TOOL_CALL_MESSAGE =
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ import {
|
|||
toCompleteBody,
|
||||
toFimBody,
|
||||
} from "./openaiTypeConverters.js";
|
||||
import { isOllamaInstalled } from "../util/ollamaHelper.js";
|
||||
|
||||
export abstract class BaseLLM implements ILLM {
|
||||
static providerName: string;
|
||||
|
|
@ -414,9 +415,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
e.code === "ECONNREFUSED" &&
|
||||
e.message.includes("http://127.0.0.1:11434")
|
||||
) {
|
||||
throw new Error(
|
||||
"Failed to connect to local Ollama instance, please ensure Ollama is both installed and running. You can download Ollama from https://ollama.ai.",
|
||||
);
|
||||
const message = (await isOllamaInstalled()) ?
|
||||
"Unable to connect to local Ollama instance. Ollama may not be running." :
|
||||
"Unable to connect to local Ollama instance. Ollama may not be installed or may not running."
|
||||
;
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
throw new Error(e.message);
|
||||
|
|
|
|||
|
|
@ -1,12 +1,24 @@
|
|||
import { JSONSchema7Object, JSONSchema7Type } from "json-schema";
|
||||
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
|
||||
type OllamaChatMessage = ChatMessage & { images?: string[] };
|
||||
type OllamaChatMessage = {
|
||||
role: "tool" | "user" | "assistant" | "system";
|
||||
content: string;
|
||||
images?: string[] | null;
|
||||
tool_calls?: {
|
||||
function: {
|
||||
name: string;
|
||||
arguments: Record<string, JSONSchema7Type>;
|
||||
};
|
||||
}[];
|
||||
};
|
||||
|
||||
// See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter
|
||||
interface ModelFileParams {
|
||||
interface OllamaModelFileParams {
|
||||
mirostat?: number;
|
||||
mirostat_eta?: number;
|
||||
mirostat_tau?: number;
|
||||
|
|
@ -21,23 +33,35 @@ interface ModelFileParams {
|
|||
top_k?: number;
|
||||
top_p?: number;
|
||||
min_p?: number;
|
||||
// deprecated?
|
||||
|
||||
// deprecated or not directly supported here:
|
||||
num_thread?: number;
|
||||
use_mmap?: boolean;
|
||||
num_gqa?: number;
|
||||
num_gpu?: number;
|
||||
num_keep?: number;
|
||||
typical_p?: number;
|
||||
presence_penalty?: number;
|
||||
frequency_penalty?: number;
|
||||
penalize_newline?: boolean;
|
||||
numa?: boolean;
|
||||
num_batch?: number;
|
||||
main_gpu?: number;
|
||||
low_vram?: boolean;
|
||||
vocab_only?: boolean;
|
||||
use_mlock?: boolean;
|
||||
}
|
||||
|
||||
// See https://github.com/ollama/ollama/blob/main/docs/api.md
|
||||
interface BaseOptions {
|
||||
interface OllamaBaseOptions {
|
||||
model: string; // the model name
|
||||
options?: ModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature
|
||||
options?: OllamaModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature
|
||||
format?: "json"; // the format to return a response in. Currently, the only accepted value is json
|
||||
stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects
|
||||
keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m)
|
||||
}
|
||||
|
||||
interface GenerateOptions extends BaseOptions {
|
||||
interface OllamaRawOptions extends OllamaBaseOptions {
|
||||
prompt: string; // the prompt to generate a response for
|
||||
suffix?: string; // the text after the model response
|
||||
images?: string[]; // a list of base64-encoded images (for multimodal models such as llava)
|
||||
|
|
@ -47,12 +71,58 @@ interface GenerateOptions extends BaseOptions {
|
|||
raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API
|
||||
}
|
||||
|
||||
interface ChatOptions extends BaseOptions {
|
||||
interface OllamaChatOptions extends OllamaBaseOptions {
|
||||
messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory
|
||||
tools?: OllamaTool[]; // the tools of the chat, this can be used to keep a tool memory
|
||||
// Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false
|
||||
// And correspondingly, tool calls in OllamaChatMessage
|
||||
}
|
||||
|
||||
type OllamaBaseResponse = {
|
||||
model: string;
|
||||
created_at: string;
|
||||
} & (
|
||||
| {
|
||||
done: false;
|
||||
}
|
||||
| {
|
||||
done: true;
|
||||
done_reason: string;
|
||||
total_duration: number; // Time spent generating the response in nanoseconds
|
||||
load_duration: number; // Time spent loading the model in nanoseconds
|
||||
prompt_eval_count: number; // Number of tokens in the prompt
|
||||
prompt_eval_duration: number; // Time spent evaluating the prompt in nanoseconds
|
||||
eval_count: number; // Number of tokens in the response
|
||||
eval_duration: number; // Time spent generating the response in nanoseconds
|
||||
context: number[]; // An encoding of the conversation used in this response; can be sent in the next request to keep conversational memory
|
||||
}
|
||||
);
|
||||
|
||||
type OllamaErrorResponse = {
|
||||
error: string;
|
||||
};
|
||||
|
||||
type OllamaRawResponse =
|
||||
| OllamaErrorResponse
|
||||
| (OllamaBaseResponse & {
|
||||
response: string; // the generated response
|
||||
});
|
||||
|
||||
type OllamaChatResponse =
|
||||
| OllamaErrorResponse
|
||||
| (OllamaBaseResponse & {
|
||||
message: OllamaChatMessage;
|
||||
});
|
||||
|
||||
interface OllamaTool {
|
||||
type: "function";
|
||||
function: {
|
||||
name: string;
|
||||
description?: string;
|
||||
parameters?: JSONSchema7Object;
|
||||
};
|
||||
}
|
||||
|
||||
class Ollama extends BaseLLM {
|
||||
static providerName = "ollama";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
|
|
@ -130,56 +200,59 @@ class Ollama extends BaseLLM {
|
|||
});
|
||||
}
|
||||
|
||||
// Map of "continue model name" to Ollama actual model name
|
||||
private modelMap: Record<string, string> = {
|
||||
"mistral-7b": "mistral:7b",
|
||||
"mixtral-8x7b": "mixtral:8x7b",
|
||||
"llama2-7b": "llama2:7b",
|
||||
"llama2-13b": "llama2:13b",
|
||||
"codellama-7b": "codellama:7b",
|
||||
"codellama-13b": "codellama:13b",
|
||||
"codellama-34b": "codellama:34b",
|
||||
"codellama-70b": "codellama:70b",
|
||||
"llama3-8b": "llama3:8b",
|
||||
"llama3-70b": "llama3:70b",
|
||||
"llama3.1-8b": "llama3.1:8b",
|
||||
"llama3.1-70b": "llama3.1:70b",
|
||||
"llama3.1-405b": "llama3.1:405b",
|
||||
"llama3.2-1b": "llama3.2:1b",
|
||||
"llama3.2-3b": "llama3.2:3b",
|
||||
"llama3.2-11b": "llama3.2:11b",
|
||||
"llama3.2-90b": "llama3.2:90b",
|
||||
"phi-2": "phi:2.7b",
|
||||
"phind-codellama-34b": "phind-codellama:34b-v2",
|
||||
"qwen2.5-coder-0.5b": "qwen2.5-coder:0.5b",
|
||||
"qwen2.5-coder-1.5b": "qwen2.5-coder:1.5b",
|
||||
"qwen2.5-coder-3b": "qwen2.5-coder:3b",
|
||||
"qwen2.5-coder-7b": "qwen2.5-coder:7b",
|
||||
"qwen2.5-coder-14b": "qwen2.5-coder:14b",
|
||||
"qwen2.5-coder-32b": "qwen2.5-coder:32b",
|
||||
"wizardcoder-7b": "wizardcoder:7b-python",
|
||||
"wizardcoder-13b": "wizardcoder:13b-python",
|
||||
"wizardcoder-34b": "wizardcoder:34b-python",
|
||||
"zephyr-7b": "zephyr:7b",
|
||||
"codeup-13b": "codeup:13b",
|
||||
"deepseek-1b": "deepseek-coder:1.3b",
|
||||
"deepseek-7b": "deepseek-coder:6.7b",
|
||||
"deepseek-33b": "deepseek-coder:33b",
|
||||
"neural-chat-7b": "neural-chat:7b-v3.3",
|
||||
"starcoder-1b": "starcoder:1b",
|
||||
"starcoder-3b": "starcoder:3b",
|
||||
"starcoder2-3b": "starcoder2:3b",
|
||||
"stable-code-3b": "stable-code:3b",
|
||||
"granite-code-3b": "granite-code:3b",
|
||||
"granite-code-8b": "granite-code:8b",
|
||||
"granite-code-20b": "granite-code:20b",
|
||||
"granite-code-34b": "granite-code:34b",
|
||||
};
|
||||
|
||||
private _getModel() {
|
||||
return (
|
||||
{
|
||||
"mistral-7b": "mistral:7b",
|
||||
"mixtral-8x7b": "mixtral:8x7b",
|
||||
"llama2-7b": "llama2:7b",
|
||||
"llama2-13b": "llama2:13b",
|
||||
"codellama-7b": "codellama:7b",
|
||||
"codellama-13b": "codellama:13b",
|
||||
"codellama-34b": "codellama:34b",
|
||||
"codellama-70b": "codellama:70b",
|
||||
"llama3-8b": "llama3:8b",
|
||||
"llama3-70b": "llama3:70b",
|
||||
"llama3.1-8b": "llama3.1:8b",
|
||||
"llama3.1-70b": "llama3.1:70b",
|
||||
"llama3.1-405b": "llama3.1:405b",
|
||||
"llama3.2-1b": "llama3.2:1b",
|
||||
"llama3.2-3b": "llama3.2:3b",
|
||||
"llama3.2-11b": "llama3.2:11b",
|
||||
"llama3.2-90b": "llama3.2:90b",
|
||||
"phi-2": "phi:2.7b",
|
||||
"phind-codellama-34b": "phind-codellama:34b-v2",
|
||||
"qwen2.5-coder-0.5b": "qwen2.5-coder:0.5b",
|
||||
"qwen2.5-coder-1.5b": "qwen2.5-coder:1.5b",
|
||||
"qwen2.5-coder-3b": "qwen2.5-coder:3b",
|
||||
"qwen2.5-coder-7b": "qwen2.5-coder:7b",
|
||||
"qwen2.5-coder-14b": "qwen2.5-coder:14b",
|
||||
"qwen2.5-coder-32b": "qwen2.5-coder:32b",
|
||||
"wizardcoder-7b": "wizardcoder:7b-python",
|
||||
"wizardcoder-13b": "wizardcoder:13b-python",
|
||||
"wizardcoder-34b": "wizardcoder:34b-python",
|
||||
"zephyr-7b": "zephyr:7b",
|
||||
"codeup-13b": "codeup:13b",
|
||||
"deepseek-1b": "deepseek-coder:1.3b",
|
||||
"deepseek-7b": "deepseek-coder:6.7b",
|
||||
"deepseek-33b": "deepseek-coder:33b",
|
||||
"neural-chat-7b": "neural-chat:7b-v3.3",
|
||||
"starcoder-1b": "starcoder:1b",
|
||||
"starcoder-3b": "starcoder:3b",
|
||||
"starcoder2-3b": "starcoder2:3b",
|
||||
"stable-code-3b": "stable-code:3b",
|
||||
"granite-code-3b": "granite-code:3b",
|
||||
"granite-code-8b": "granite-code:8b",
|
||||
"granite-code-20b": "granite-code:20b",
|
||||
"granite-code-34b": "granite-code:34b",
|
||||
}[this.model] ?? this.model
|
||||
);
|
||||
return this.modelMap[this.model] ?? this.model;
|
||||
}
|
||||
|
||||
private _getModelFileParams(options: CompletionOptions): ModelFileParams {
|
||||
private _getModelFileParams(
|
||||
options: CompletionOptions,
|
||||
): OllamaModelFileParams {
|
||||
return {
|
||||
temperature: options.temperature,
|
||||
top_p: options.topP,
|
||||
|
|
@ -194,50 +267,38 @@ class Ollama extends BaseLLM {
|
|||
};
|
||||
}
|
||||
|
||||
private _convertMessage(message: ChatMessage) {
|
||||
if (message.role === "tool") {
|
||||
return null;
|
||||
}
|
||||
private _convertToOllamaMessage(message: ChatMessage): OllamaChatMessage {
|
||||
const ollamaMessage: OllamaChatMessage = {
|
||||
role: message.role,
|
||||
content: "",
|
||||
};
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
return message;
|
||||
}
|
||||
const images: string[] = [];
|
||||
message.content.forEach((part) => {
|
||||
if (part.type === "imageUrl" && part.imageUrl) {
|
||||
const image = part.imageUrl?.url.split(",").at(-1);
|
||||
if (image) {
|
||||
images.push(image);
|
||||
ollamaMessage.content = message.content;
|
||||
} else {
|
||||
ollamaMessage.content = renderChatMessage(message);
|
||||
const images: string[] = [];
|
||||
message.content.forEach((part) => {
|
||||
if (part.type === "imageUrl" && part.imageUrl) {
|
||||
const image = part.imageUrl?.url.split(",").at(-1);
|
||||
if (image) {
|
||||
images.push(image);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (images.length > 0) {
|
||||
ollamaMessage.images = images;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
role: message.role,
|
||||
content: renderChatMessage(message),
|
||||
images,
|
||||
};
|
||||
}
|
||||
|
||||
private _getChatOptions(
|
||||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
): ChatOptions {
|
||||
return {
|
||||
model: this._getModel(),
|
||||
messages: messages.map(this._convertMessage).filter(Boolean) as any,
|
||||
options: this._getModelFileParams(options),
|
||||
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
|
||||
stream: options.stream,
|
||||
// format: options.format, // Not currently in base completion options
|
||||
};
|
||||
return ollamaMessage;
|
||||
}
|
||||
|
||||
private _getGenerateOptions(
|
||||
options: CompletionOptions,
|
||||
prompt: string,
|
||||
suffix?: string,
|
||||
): GenerateOptions {
|
||||
): OllamaRawOptions {
|
||||
return {
|
||||
model: this._getModel(),
|
||||
prompt,
|
||||
|
|
@ -286,12 +347,11 @@ class Ollama extends BaseLLM {
|
|||
const chunk = chunks[i];
|
||||
if (chunk.trim() !== "") {
|
||||
try {
|
||||
const j = JSON.parse(chunk);
|
||||
if ("response" in j) {
|
||||
yield j.response;
|
||||
} else if ("error" in j) {
|
||||
const j = JSON.parse(chunk) as OllamaRawResponse;
|
||||
if ("error" in j) {
|
||||
throw new Error(j.error);
|
||||
}
|
||||
yield j.response;
|
||||
} catch (e) {
|
||||
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
|
||||
}
|
||||
|
|
@ -305,39 +365,91 @@ class Ollama extends BaseLLM {
|
|||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const chatOptions: OllamaChatOptions = {
|
||||
model: this._getModel(),
|
||||
messages: messages.map(this._convertToOllamaMessage),
|
||||
options: this._getModelFileParams(options),
|
||||
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
|
||||
stream: options.stream,
|
||||
// format: options.format, // Not currently in base completion options
|
||||
};
|
||||
if (options.tools?.length) {
|
||||
chatOptions.tools = options.tools.map((tool) => ({
|
||||
type: "function",
|
||||
function: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
parameters: tool.function.parameters,
|
||||
},
|
||||
}));
|
||||
chatOptions.stream = false; // Cannot set stream = true for tools calls
|
||||
}
|
||||
|
||||
const response = await this.fetch(this.getEndpoint("api/chat"), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify(this._getChatOptions(options, messages)),
|
||||
body: JSON.stringify(chatOptions),
|
||||
signal,
|
||||
});
|
||||
|
||||
let buffer = "";
|
||||
for await (const value of streamResponse(response)) {
|
||||
// Append the received chunk to the buffer
|
||||
buffer += value;
|
||||
// Split the buffer into individual JSON chunks
|
||||
const chunks = buffer.split("\n");
|
||||
buffer = chunks.pop() ?? "";
|
||||
function convertChatMessage(res: OllamaChatResponse): ChatMessage {
|
||||
if ("error" in res) {
|
||||
throw new Error(res.error);
|
||||
}
|
||||
if (res.message.role === "tool") {
|
||||
throw new Error(
|
||||
"Unexpected message received from ollama with role = tool",
|
||||
);
|
||||
}
|
||||
if (res.message.role === "assistant") {
|
||||
const chatMessage: ChatMessage = {
|
||||
role: "assistant",
|
||||
content: res.message.content,
|
||||
};
|
||||
if (res.message.tool_calls) {
|
||||
// Continue handles the response as a tool call delta but
|
||||
// But ollama returns the full object in one response with no streaming
|
||||
chatMessage.toolCalls = res.message.tool_calls.map((tc) => ({
|
||||
type: "function",
|
||||
function: {
|
||||
name: tc.function.name,
|
||||
arguments: JSON.stringify(tc.function.arguments),
|
||||
},
|
||||
}));
|
||||
}
|
||||
return chatMessage;
|
||||
} else {
|
||||
return {
|
||||
role: res.message.role,
|
||||
content: res.message.content,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
const chunk = chunks[i];
|
||||
if (chunk.trim() !== "") {
|
||||
try {
|
||||
const j = JSON.parse(chunk);
|
||||
if (j.message?.content) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: j.message.content,
|
||||
};
|
||||
} else if (j.error) {
|
||||
throw new Error(j.error);
|
||||
if (chatOptions.stream === false) {
|
||||
const json = (await response.json()) as OllamaChatResponse;
|
||||
yield convertChatMessage(json);
|
||||
} else {
|
||||
let buffer = "";
|
||||
for await (const value of streamResponse(response)) {
|
||||
// Append the received chunk to the buffer
|
||||
buffer += value;
|
||||
// Split the buffer into individual JSON chunks
|
||||
const chunks = buffer.split("\n");
|
||||
buffer = chunks.pop() ?? "";
|
||||
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
const chunk = chunks[i];
|
||||
if (chunk.trim() !== "") {
|
||||
try {
|
||||
const j = JSON.parse(chunk) as OllamaChatResponse;
|
||||
const chatMessage = convertChatMessage(j);
|
||||
} catch (e) {
|
||||
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
46
core/llm/toolSupport.ts
Normal file
46
core/llm/toolSupport.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
export const PROVIDER_TOOL_SUPPORT: Record<
|
||||
string,
|
||||
(model: string) => boolean | undefined
|
||||
> = {
|
||||
anthropic: (model) => {
|
||||
if (
|
||||
["claude-3-5", "claude-3.5"].some((part) =>
|
||||
model.toLowerCase().startsWith(part),
|
||||
)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
// https://ollama.com/search?c=tools
|
||||
ollama: (model) => {
|
||||
if (
|
||||
["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
|
||||
(part) => model.toLowerCase().includes(part),
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
[
|
||||
"llama3.3",
|
||||
"qwq",
|
||||
"llama3.2",
|
||||
"llama3.1",
|
||||
"qwen2",
|
||||
"mixtral",
|
||||
"command-r",
|
||||
"smollm2",
|
||||
"hermes3",
|
||||
"athene-v2",
|
||||
"nemotron",
|
||||
"llama3-groq",
|
||||
"granite3",
|
||||
"aya-expanse",
|
||||
"firefunction-v2",
|
||||
"mistral",
|
||||
].some((part) => model.toLowerCase().startsWith(part))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
};
|
||||
7
core/package-lock.json
generated
7
core/package-lock.json
generated
|
|
@ -83,6 +83,7 @@
|
|||
"@types/jest": "^29.5.12",
|
||||
"@types/jquery": "^3.5.29",
|
||||
"@types/jsdom": "^21.1.6",
|
||||
"@types/json-schema": "^7.0.15",
|
||||
"@types/mozilla-readability": "^0.2.1",
|
||||
"@types/mustache": "^4.2.5",
|
||||
"@types/node-fetch": "^2.6.11",
|
||||
|
|
@ -5311,6 +5312,12 @@
|
|||
"parse5": "^7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/json-schema": {
|
||||
"version": "7.0.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
||||
"integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/json5": {
|
||||
"version": "0.0.29",
|
||||
"resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz",
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@
|
|||
"@types/jest": "^29.5.12",
|
||||
"@types/jquery": "^3.5.29",
|
||||
"@types/jsdom": "^21.1.6",
|
||||
"@types/json-schema": "^7.0.15",
|
||||
"@types/mozilla-readability": "^0.2.1",
|
||||
"@types/mustache": "^4.2.5",
|
||||
"@types/node-fetch": "^2.6.11",
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import type {
|
|||
Range,
|
||||
RangeInFile,
|
||||
Thread,
|
||||
TerminalOptions
|
||||
} from "../";
|
||||
|
||||
export interface GetGhTokenArgs {
|
||||
|
|
@ -28,7 +29,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
showVirtualFile: [{ name: string; content: string }, void];
|
||||
openFile: [{ path: string }, void];
|
||||
openUrl: [string, void];
|
||||
runCommand: [{ command: string }, void];
|
||||
runCommand: [{ command: string, options?: TerminalOptions }, void];
|
||||
getSearchResults: [{ query: string }, string];
|
||||
subprocess: [{ command: string; cwd?: string }, [string, string]];
|
||||
saveFile: [{ filepath: string }, void];
|
||||
|
|
|
|||
|
|
@ -62,10 +62,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
||||
setInactive: [undefined, void];
|
||||
submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap
|
||||
updateSubmenuItems: [
|
||||
{ provider: string; submenuItems: ContextSubmenuItem[] },
|
||||
void,
|
||||
];
|
||||
newSessionWithPrompt: [{ prompt: string }, void];
|
||||
userInput: [{ input: string }, void];
|
||||
focusContinueInput: [undefined, void];
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import type {
|
|||
Problem,
|
||||
Range,
|
||||
RangeInFile,
|
||||
TerminalOptions,
|
||||
Thread,
|
||||
} from "../..";
|
||||
|
||||
|
|
@ -151,8 +152,8 @@ export class MessageIde implements IDE {
|
|||
await this.request("openUrl", url);
|
||||
}
|
||||
|
||||
async runCommand(command: string): Promise<void> {
|
||||
await this.request("runCommand", { command });
|
||||
async runCommand(command: string, options?: TerminalOptions): Promise<void> {
|
||||
await this.request("runCommand", { command, options });
|
||||
}
|
||||
|
||||
async saveFile(fileUri: string): Promise<void> {
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import { ConfigValidationError } from "../config/validation.js";
|
|||
import type {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContextItemWithId,
|
||||
ContextProviderName,
|
||||
ContextSubmenuItem,
|
||||
IndexingProgressUpdate,
|
||||
IndexingStatus,
|
||||
PackageDocsResult,
|
||||
|
|
@ -21,7 +23,12 @@ export type ToWebviewFromIdeOrCoreProtocol = {
|
|||
getDefaultModelTitle: [undefined, string];
|
||||
indexProgress: [IndexingProgressUpdate, void]; // Codebase
|
||||
"indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc.
|
||||
refreshSubmenuItems: [undefined, void];
|
||||
refreshSubmenuItems: [
|
||||
{
|
||||
providers: "all" | "dependsOnIndexing" | ContextProviderName[];
|
||||
},
|
||||
void,
|
||||
];
|
||||
isContinueInputFocused: [undefined, boolean];
|
||||
addContextItem: [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ export type GlobalContextType = {
|
|||
hasDismissedConfigTsNoticeJetBrains: boolean;
|
||||
hasAlreadyCreatedAPromptFile: boolean;
|
||||
showConfigUpdateToast: boolean;
|
||||
isSupportedLanceDbCpuTarget: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -8,10 +8,28 @@ class ClipboardCache {
|
|||
this.order = [];
|
||||
}
|
||||
|
||||
add(id: string, content: string): void {
|
||||
/*
|
||||
Returns true if added, false if not.
|
||||
*/
|
||||
add(id: string, content: string): boolean {
|
||||
if (!content) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the content already exists in the cache
|
||||
for (const [existingId, existingContent] of this.cache.entries()) {
|
||||
if (existingContent === content) {
|
||||
// Remove the existing entry with the same content
|
||||
this.cache.delete(existingId);
|
||||
const index = this.order.indexOf(existingId);
|
||||
if (index > -1) {
|
||||
this.order.splice(index, 1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the oldest entry if the cache exceeds the maximum size
|
||||
if (this.order.length >= this.maxSize) {
|
||||
const oldest = this.order.pop();
|
||||
if (oldest) {
|
||||
|
|
@ -19,14 +37,13 @@ class ClipboardCache {
|
|||
}
|
||||
}
|
||||
|
||||
// Add the new entry to the cache and update the order
|
||||
this.cache.set(id, content);
|
||||
this.order.unshift(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
getNItems(count: number): {
|
||||
id: string;
|
||||
content: string;
|
||||
}[] {
|
||||
getNItems(count: number): { id: string; content: string }[] {
|
||||
return this.order.slice(0, count).map((id) => ({
|
||||
id,
|
||||
content: this.cache.get(id) || "",
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import {
|
|||
Problem,
|
||||
Range,
|
||||
RangeInFile,
|
||||
TerminalOptions,
|
||||
Thread,
|
||||
ToastType,
|
||||
} from "../index.js";
|
||||
|
|
@ -190,7 +191,7 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve();
|
||||
}
|
||||
|
||||
runCommand(command: string): Promise<void> {
|
||||
runCommand(command: string, options?: TerminalOptions): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
|
|
|
|||
41
core/util/ollamaHelper.ts
Normal file
41
core/util/ollamaHelper.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import path from "node:path";
|
||||
import { IDE } from "..";
|
||||
import { exec } from "node:child_process";
|
||||
|
||||
export async function isOllamaInstalled(): Promise<boolean> {
|
||||
return new Promise((resolve, _reject) => {
|
||||
const command = process.platform === "win32" ? "where.exe ollama" : "which ollama";
|
||||
exec(command, (error, _stdout, _stderr) => {
|
||||
resolve(!error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function startLocalOllama(ide: IDE): Promise<void> {
|
||||
let startCommand: string | undefined;
|
||||
|
||||
switch (process.platform) {
|
||||
case "darwin"://MacOS
|
||||
startCommand = "open -a Ollama.app\n";
|
||||
break;
|
||||
|
||||
case "win32"://Windows
|
||||
startCommand = `& "ollama app.exe"\n`;
|
||||
break;
|
||||
|
||||
default: //Linux...
|
||||
const start_script_path = path.resolve(__dirname, './start_ollama.sh');
|
||||
if (await ide.fileExists(`file:/${start_script_path}`)) {
|
||||
startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`;
|
||||
console.log(`Ollama Linux startup script at : ${start_script_path}`);
|
||||
} else {
|
||||
ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`)
|
||||
}
|
||||
}
|
||||
if (startCommand) {
|
||||
return ide.runCommand(startCommand, {
|
||||
reuseTerminal: true,
|
||||
terminalName: "Start Ollama"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -2,15 +2,17 @@ import os from "node:os";
|
|||
|
||||
import { TeamAnalytics } from "../control-plane/TeamAnalytics.js";
|
||||
import { IdeInfo } from "../index.js";
|
||||
|
||||
import type { PostHog as PostHogType } from "posthog-node";
|
||||
|
||||
export enum PosthogFeatureFlag {
|
||||
AutocompleteTimeout = "autocomplete-timeout",
|
||||
RecentlyVisitedRangesNumSurroundingLines = "recently-visited-ranges-num-surrounding-lines",
|
||||
}
|
||||
|
||||
export const EXPERIMENTS: {
|
||||
[key in PosthogFeatureFlag]: {
|
||||
[key: string]: { value: number };
|
||||
[key: string]: { value: any };
|
||||
};
|
||||
} = {
|
||||
[PosthogFeatureFlag.AutocompleteTimeout]: {
|
||||
|
|
@ -19,6 +21,13 @@ export const EXPERIMENTS: {
|
|||
"350": { value: 350 },
|
||||
"450": { value: 450 },
|
||||
},
|
||||
[PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines]: {
|
||||
control: { value: null },
|
||||
"5": { value: 5 },
|
||||
"10": { value: 10 },
|
||||
"15": { value: 15 },
|
||||
"20": { value: 20 },
|
||||
},
|
||||
};
|
||||
|
||||
export class Telemetry {
|
||||
|
|
|
|||
84
core/util/start_ollama.sh
Executable file
84
core/util/start_ollama.sh
Executable file
|
|
@ -0,0 +1,84 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Timeout for waiting for Ollama to start (in seconds)
|
||||
readonly TIMEOUT=60
|
||||
readonly OLLAMA_API_URL="http://localhost:11434/api/version"
|
||||
|
||||
# Check if a command exists
|
||||
command_exists() {
|
||||
command -v "$1" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
# Check if Ollama is already running
|
||||
ollama_is_running() {
|
||||
VERSION=$(curl -s --fail --max-time 1 "$OLLAMA_API_URL" | grep '"version"' | awk -F: '{ print $2 }' | sed -e 's/.*"\([^"]*\)".*/\1/')
|
||||
test -n "$VERSION"
|
||||
}
|
||||
|
||||
# Determine if running in a container environment
|
||||
in_container() {
|
||||
[[ -f /.dockerenv || -f /run/.containerenv ]]
|
||||
}
|
||||
|
||||
# Start Ollama service or background process
|
||||
start_ollama() {
|
||||
local start_method="${1:-background}"
|
||||
echo "Starting Ollama ($start_method)..."
|
||||
|
||||
if [[ "$start_method" == "service" ]]; then
|
||||
if in_container; then
|
||||
service ollama start || return $?
|
||||
else
|
||||
sudo systemctl start ollama || return $?
|
||||
fi
|
||||
else
|
||||
nohup ollama serve >/dev/null 2>&1 &
|
||||
fi
|
||||
|
||||
# Wait for Ollama to start. TIMEOUT * 4, since we sleep 1/4 sec on each iteration
|
||||
for _ in $(seq 1 $((TIMEOUT * 4))); do
|
||||
if ollama_is_running; then
|
||||
echo -e "\nOllama started successfully."
|
||||
return 0
|
||||
fi
|
||||
(( _ % 2 == 0 )) && printf "."
|
||||
sleep 0.25
|
||||
done
|
||||
|
||||
echo -e "\nTimeout: Failed to start Ollama."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Main script execution
|
||||
main() {
|
||||
# Early exit if Ollama is already running
|
||||
if ollama_is_running; then
|
||||
echo "Ollama is already running."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Try starting via service if possible
|
||||
if in_container; then
|
||||
if service --status-all 2>&1 | grep -qw 'ollama'; then
|
||||
start_ollama service || return $?
|
||||
return 0
|
||||
fi
|
||||
elif command_exists systemctl; then
|
||||
if systemctl list-unit-files ollama.service >/dev/null 2>&1; then
|
||||
start_ollama service || return $?
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
# Fallback to background process
|
||||
if command_exists ollama; then
|
||||
start_ollama || return 1
|
||||
else
|
||||
echo "Error: Ollama is not installed or not in the PATH." >&2
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Run the main function and exit with its status
|
||||
main
|
||||
exit $?
|
||||
|
|
@ -15,7 +15,7 @@ The highlighted code you’ve selected by pressing <kbd>cmd/ctrl</kbd> + <kbd>L<
|
|||
|
||||
## Active file
|
||||
|
||||
You can include the currently open file as context by pressing <kbd>cmd</kbd> + <kbd>opt</kbd> + <kbd>enter</kbd> (Mac) or <kbd>alt</kbd> + <kbd>enter</kbd> (Windows) when you send your request at Chat window(Prompt can't be empty).
|
||||
You can include the currently open file as context by pressing <kbd>opt</kbd> + <kbd>enter</kbd> (Mac) or <kbd>alt</kbd> + <kbd>enter</kbd> (Windows) when you send your request at Chat window(Prompt can't be empty).
|
||||
|
||||
## Specific file
|
||||
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customiz
|
|||
|
||||
### Llama 3.1 405B from Meta
|
||||
|
||||
If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Novita AI](../customize/model-providers/more/novita.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)).
|
||||
If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)).
|
||||
|
||||
<Tabs groupId="providers">
|
||||
<TabItem value="Together">
|
||||
|
|
@ -48,18 +48,6 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your
|
|||
]
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="Novita">
|
||||
```json title="config.json"
|
||||
"models": [
|
||||
{
|
||||
"title": "Llama 3.1 405B",
|
||||
"provider": "novita",
|
||||
"model": "meta-llama/llama-3.1-405b-instruct",
|
||||
"apiKey": "[NOVITA_API_KEY]"
|
||||
}
|
||||
]
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="Groq">
|
||||
```json title="config.json"
|
||||
"models": [
|
||||
|
|
@ -94,18 +82,6 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your
|
|||
]
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="Nebius">
|
||||
```json title="config.json"
|
||||
"models": [
|
||||
{
|
||||
"title": "Llama 3.1 405B",
|
||||
"provider": "nebius",
|
||||
"model": "llama3.1-405b",
|
||||
"apiKey": "[NEBIUS_API_KEY]"
|
||||
}
|
||||
]
|
||||
```
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### GPT-4o from OpenAI
|
||||
|
|
|
|||
|
|
@ -123,11 +123,16 @@ Reference the contents of all of your open files. Set `onlyPinned` to `true` to
|
|||
|
||||
Reference relevant pages from across the web, automatically determined from your input.
|
||||
|
||||
Optionally, set "n" to limit the number of results returned (default 6).
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "web"
|
||||
"name": "web",
|
||||
"params": {
|
||||
"n": 5
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -193,6 +198,20 @@ Reference the markdown converted contents of a given URL.
|
|||
}
|
||||
```
|
||||
|
||||
### `@Clipboard`
|
||||
|
||||
Reference recent clipboard items
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "clipboard"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `@Tree`
|
||||
|
||||
Reference the structure of your current workspace.
|
||||
|
|
@ -207,26 +226,103 @@ Reference the structure of your current workspace.
|
|||
}
|
||||
```
|
||||
|
||||
### `@Google`
|
||||
### `@Problems`
|
||||
|
||||
Reference the results of a Google search.
|
||||
Get Problems from the current file.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "google",
|
||||
"name": "problems"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `@Debugger`
|
||||
|
||||
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "debugger",
|
||||
"params": {
|
||||
"serperApiKey": "<your serper.dev api key>"
|
||||
"stackDepth": 3
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python.
|
||||
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
|
||||
|
||||
Note: You can get an API key for free at [serper.dev](https://serper.dev).
|
||||
### `@Repository Map`
|
||||
|
||||
Reference the outline of your codebase.
|
||||
|
||||
`includeSignatures` params can be used to include signatures for all files in the repo. Use with caution as will increase context size significantly. `includeSignatures` will not work if indexing is disabled.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "repo-map",
|
||||
"params": {
|
||||
"includeSignatures": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
|
||||
|
||||
In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from.
|
||||
|
||||
This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html).
|
||||
|
||||
### `@Operating System`
|
||||
|
||||
Reference the architecture and platform of your current operating system.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "os"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Model Context Protocol
|
||||
|
||||
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"experimental": {
|
||||
"modelContextProtocolServers": [
|
||||
{
|
||||
"transport": {
|
||||
"type": "stdio",
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
|
||||
|
||||
### Prompt Files
|
||||
|
||||
See [Prompt Files](/customize/deep-dives/prompt-files). Prompt files are not added directly to the config file; prompt files are parsed and injected into the config automatically, to be used like other context providers.
|
||||
|
||||
### `@Issue`
|
||||
|
||||
|
|
@ -253,6 +349,110 @@ Reference the conversation in a GitHub issue.
|
|||
|
||||
Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited.
|
||||
|
||||
### `@Database`
|
||||
|
||||
Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "database",
|
||||
"params": {
|
||||
"connections": [
|
||||
{
|
||||
"name": "examplePostgres",
|
||||
"connection_type": "postgres",
|
||||
"connection": {
|
||||
"user": "username",
|
||||
"host": "localhost",
|
||||
"database": "exampleDB",
|
||||
"password": "yourPassword",
|
||||
"port": 5432
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "exampleMssql",
|
||||
"connection_type": "mssql",
|
||||
"connection": {
|
||||
"user": "username",
|
||||
"server": "localhost",
|
||||
"database": "exampleDB",
|
||||
"password": "yourPassword"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "exampleSqlite",
|
||||
"connection_type": "sqlite",
|
||||
"connection": {
|
||||
"filename": "/path/to/your/sqlite/database.db"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type.
|
||||
|
||||
Available connection types:
|
||||
|
||||
- `postgres`
|
||||
- `mysql`
|
||||
- `sqlite`
|
||||
|
||||
### `@Postgres`
|
||||
|
||||
Reference the schema of a table, and some sample rows
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "postgres",
|
||||
"params": {
|
||||
"host": "localhost",
|
||||
"port": 5436,
|
||||
"user": "myuser",
|
||||
"password": "catsarecool",
|
||||
"database": "animals",
|
||||
"schema": "public",
|
||||
"sampleRows": 3
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`.
|
||||
|
||||
By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas.
|
||||
|
||||
[Here is a short demo.](https://github.com/continuedev/continue/pull/859)
|
||||
|
||||
### `@Google`
|
||||
|
||||
Reference the results of a Google search.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "google",
|
||||
"params": {
|
||||
"serperApiKey": "<your serper.dev api key>"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python.
|
||||
|
||||
Note: You can get an API key for free at [serper.dev](https://serper.dev).
|
||||
|
||||
### `@Gitlab Merge Request`
|
||||
|
||||
Reference an open MR for this branch on GitLab.
|
||||
|
|
@ -373,164 +573,6 @@ Reference the messages in a Discord channel.
|
|||
|
||||
Make sure to include your own [Bot Token](https://discord.com/developers/applications), and join it to your related server . If you want more granular control over which channels are searched, you can specify a list of channel IDs to search in. If you don't want to specify any channels, just include the guild id(Server ID) and all channels will be included. The provider only reads text channels.
|
||||
|
||||
### `@Postgres`
|
||||
|
||||
Reference the schema of a table, and some sample rows
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "postgres",
|
||||
"params": {
|
||||
"host": "localhost",
|
||||
"port": 5436,
|
||||
"user": "myuser",
|
||||
"password": "catsarecool",
|
||||
"database": "animals",
|
||||
"schema": "public",
|
||||
"sampleRows": 3
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`.
|
||||
|
||||
By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas.
|
||||
|
||||
[Here is a short demo.](https://github.com/continuedev/continue/pull/859)
|
||||
|
||||
### `@Database`
|
||||
|
||||
Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "database",
|
||||
"params": {
|
||||
"connections": [
|
||||
{
|
||||
"name": "examplePostgres",
|
||||
"connection_type": "postgres",
|
||||
"connection": {
|
||||
"user": "username",
|
||||
"host": "localhost",
|
||||
"database": "exampleDB",
|
||||
"password": "yourPassword",
|
||||
"port": 5432
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "exampleMssql",
|
||||
"connection_type": "mssql",
|
||||
"connection": {
|
||||
"user": "username",
|
||||
"server": "localhost",
|
||||
"database": "exampleDB",
|
||||
"password": "yourPassword"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "exampleSqlite",
|
||||
"connection_type": "sqlite",
|
||||
"connection": {
|
||||
"filename": "/path/to/your/sqlite/database.db"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type.
|
||||
|
||||
Available connection types:
|
||||
|
||||
- `postgres`
|
||||
- `mysql`
|
||||
- `sqlite`
|
||||
|
||||
### `@Debugger`
|
||||
|
||||
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "debugger",
|
||||
"params": {
|
||||
"stackDepth": 3
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
|
||||
|
||||
### `@Repository Map`
|
||||
|
||||
Reference the outline of your codebase.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "repo-map"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
|
||||
|
||||
In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from.
|
||||
|
||||
This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html).
|
||||
|
||||
### `@Operating System`
|
||||
|
||||
Reference the architecture and platform of your current operating system.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "os"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Model Context Protocol
|
||||
|
||||
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"experimental": {
|
||||
"modelContextProtocolServers": [
|
||||
{
|
||||
"transport": {
|
||||
"type": "stdio",
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
|
||||
|
||||
### `@HTTP`
|
||||
|
||||
The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
|
||||
|
|
@ -550,7 +592,7 @@ The HttpContextProvider makes a POST request to the url passed in the configurat
|
|||
|
||||
The receiving URL should expect to receive the following parameters:
|
||||
|
||||
```json title="POST parameters"
|
||||
```js title="POST parameters"
|
||||
{
|
||||
query: string,
|
||||
fullInput: string
|
||||
|
|
@ -576,15 +618,19 @@ The response 200 OK should be a JSON object with the following structure:
|
|||
}
|
||||
```
|
||||
|
||||
### `@Clipboard`
|
||||
### `@Greptile`
|
||||
|
||||
Reference recent clipboard items
|
||||
Query a [Greptile](https://www.greptile.com/) index of the current repo/branch.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "clipboard"
|
||||
"name": "greptile",
|
||||
"params": {
|
||||
"GreptileToken": "...",
|
||||
"GithubToken": "..."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,12 @@ description: Tool use and customization
|
|||
keywords: [tool, use, function calling, claude, automatic]
|
||||
---
|
||||
|
||||
Tools allow Continue to take action in your IDE and beyond (when you give permission). Currently, they are only supported with [Anthropic](./model-providers/top-level/anthropic.md). To use tools, click on the icon in the input toolbar like below.
|
||||
Tools allow Continue to take action in your IDE and beyond (when you give permission). Currently, they are only supported for the following providers:
|
||||
|
||||
- [Anthropic](./model-providers/top-level/anthropic.md) - see recommended models [here](https://docs.anthropic.com/en/docs/build-with-claude/tool-use#choosing-a-model).
|
||||
- [Ollama](./model-providers/top-level/ollama.md) - see recommended models [here](https://ollama.com/search?c=tools).
|
||||
|
||||
To use tools, click on the icon in the input toolbar like below.
|
||||
|
||||

|
||||
|
||||
|
|
|
|||
|
|
@ -71,28 +71,6 @@ Together AI provides fast and reliable inference of open-source models. You'll b
|
|||
}
|
||||
```
|
||||
|
||||
|
||||
## Novita AI
|
||||
|
||||
[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) offers an affordable, reliable, and simple inference platform with scalable [LLM API](https://novita.ai/docs/model-api/reference/introduction.html), empowering developers to build AI applications. Try the [Novita AI Llama 3 API Demo](https://novita.ai/model-api/product/llm-api/playground/meta-llama-llama-3.1-70b-instruct?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) today!
|
||||
|
||||
1. Create an account [here](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)
|
||||
2. Copy your API key that appears on the welcome screen
|
||||
3. Update your Continue config file like this:
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Llama 3.1 405b",
|
||||
"provider": "novita",
|
||||
"model": "meta-llama/llama-3.1-405b-instruct",
|
||||
"apiKey": "<API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Replicate
|
||||
|
||||
Replicate makes it easy to host and run open-source AI with an API.
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ import TabItem from "@theme/TabItem";
|
|||
|
||||
### 来自 Meta 的 Llama 3.1 405B
|
||||
|
||||
如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md) 、[Novita AI](../customize/model-providers/more/novita.md)或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。
|
||||
如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md)或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。
|
||||
|
||||
<Tabs groupId="providers">
|
||||
<TabItem value="Together">
|
||||
|
|
|
|||
|
|
@ -71,27 +71,6 @@ Together AI 提供开源模型的快速和可信任的推理。你可以以良
|
|||
}
|
||||
```
|
||||
|
||||
## Novita AI
|
||||
|
||||
[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) 提供了一个经济实惠、可靠且简单的推理平台。你可以以良好的速度运行 405b 模型。
|
||||
|
||||
1. 创建账号 [在这里](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)
|
||||
2. 复制[Key Management](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)中的你的 API key
|
||||
3. 更新你的 Continue 配置文件,像这样:
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Llama 3.1 405b",
|
||||
"provider": "novita",
|
||||
"model": "meta-llama/llama-3.1-405b-instruct",
|
||||
"apiKey": "<API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Replicate
|
||||
|
||||
Replicate 让使用 API 托管和运行开源 AI 变得简单。
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
</map>
|
||||
</option>
|
||||
<option name="executionName" />
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="externalSystemIdString" value="GRADLE" />
|
||||
<option name="scriptParameters" value="" />
|
||||
<option name="taskDescriptions">
|
||||
|
|
|
|||
|
|
@ -1,16 +1,17 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Start Core Dev Server (CE)" type="ShConfigurationType">
|
||||
<option name="SCRIPT_TEXT" value="export CONTINUE_DEVELOPMENT=true && export CONTINUE_GLOBAL_DIR=$PROJECT_DIR$/extensions/.continue-debug && node out/index.js" />
|
||||
<option name="SCRIPT_TEXT" value="export CONTINUE_DEVELOPMENT=true && export CONTINUE_GLOBAL_DIR=$PROJECT_DIR$/../.continue-debug && node out/index.js" />
|
||||
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||
<option name="SCRIPT_PATH" value="" />
|
||||
<option name="SCRIPT_OPTIONS" value="" />
|
||||
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/binary" />
|
||||
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/../../binary" />
|
||||
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||
<option name="INTERPRETER_PATH" value="" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
<option name="EXECUTE_IN_TERMINAL" value="false" />
|
||||
<option name="EXECUTE_SCRIPT_FILE" value="false" />
|
||||
<envs />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
|
|
@ -5,7 +5,7 @@
|
|||
<option name="SCRIPT_PATH" value="" />
|
||||
<option name="SCRIPT_OPTIONS" value="" />
|
||||
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/gui" />
|
||||
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/../../gui" />
|
||||
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||
<option name="INTERPRETER_PATH" value="/bin/zsh" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ and is generated by [Changie](https://github.com/miniscruff/changie).
|
|||
|
||||
|
||||
Pre-release Changes
|
||||
### Fixed
|
||||
### Fixed
|
||||
* Off-screen rendering to solve white flash on load and lack of changing cursor type
|
||||
* OSR-related fixes for non-Mac users
|
||||
* Fixes for inline edit in JetBrains
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import com.github.continuedev.continueintellijextension.listeners.ContinuePlugin
|
|||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.services.SettingsListener
|
||||
import com.intellij.openapi.Disposable
|
||||
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
|
||||
import com.intellij.openapi.actionSystem.KeyboardShortcut
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.application.ApplicationNamesInfo
|
||||
|
|
@ -162,7 +162,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
override fun after(events: List<VFileEvent>) {
|
||||
// Collect all relevant URIs for deletions
|
||||
val deletedURIs = events.filterIsInstance<VFileDeleteEvent>()
|
||||
.map { event -> event.file.url }
|
||||
.mapNotNull { event -> event.file.toUriOrNull() }
|
||||
|
||||
// Send "files/deleted" message if there are any deletions
|
||||
if (deletedURIs.isNotEmpty()) {
|
||||
|
|
@ -172,7 +172,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
|
||||
// Collect all relevant URIs for content changes
|
||||
val changedURIs = events.filterIsInstance<VFileContentChangeEvent>()
|
||||
.map { event -> event.file.url }
|
||||
.mapNotNull { event -> event.file.toUriOrNull() }
|
||||
|
||||
// Send "files/changed" message if there are any content changes
|
||||
if (changedURIs.isNotEmpty()) {
|
||||
|
|
@ -220,7 +220,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
// Reload the WebView
|
||||
continuePluginService?.let { pluginService ->
|
||||
val allModulePaths = ModuleManager.getInstance(project).modules
|
||||
.flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.map { it.url } }
|
||||
.flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } }
|
||||
|
||||
val topLevelModulePaths = allModulePaths
|
||||
.filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } }
|
||||
|
|
|
|||
|
|
@ -22,4 +22,4 @@ class AcceptAutocompleteAction : EditorAction(object : EditorActionHandler() {
|
|||
&& autocompleteService.pendingCompletion?.text != null
|
||||
return enabled
|
||||
}
|
||||
}) {}
|
||||
})
|
||||
|
|
@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.autocomplete
|
|||
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.intellij.injected.editor.VirtualFileWindow
|
||||
import com.intellij.openapi.application.*
|
||||
|
|
@ -10,8 +11,10 @@ import com.intellij.openapi.components.ServiceManager
|
|||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.InlayProperties
|
||||
import com.intellij.openapi.editor.impl.EditorImpl
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.TextRange
|
||||
import com.intellij.openapi.wm.WindowManager
|
||||
import com.intellij.psi.PsiDocumentManager
|
||||
import com.intellij.psi.PsiElement
|
||||
|
|
@ -32,9 +35,24 @@ fun PsiElement.isInjectedText(): Boolean {
|
|||
return false
|
||||
}
|
||||
|
||||
fun Editor.addInlayElement(
|
||||
lines: List<String>,
|
||||
offset: Int,
|
||||
properties: InlayProperties
|
||||
) {
|
||||
if (this is EditorImpl) {
|
||||
if (lines[0].isNotEmpty()) {
|
||||
inlayModel.addInlineElement(offset, properties, ContinueInlayRenderer(listOf(lines[0])))
|
||||
}
|
||||
if (lines.size > 1) {
|
||||
inlayModel.addBlockElement(offset, properties, ContinueInlayRenderer(lines.drop(1)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class AutocompleteService(private val project: Project) {
|
||||
var pendingCompletion: PendingCompletion? = null;
|
||||
var pendingCompletion: PendingCompletion? = null
|
||||
private val autocompleteLookupListener = project.service<AutocompleteLookupListener>()
|
||||
private var widget: AutocompleteSpinnerWidget? = null
|
||||
|
||||
|
|
@ -66,23 +84,23 @@ class AutocompleteService(private val project: Project) {
|
|||
|
||||
// Request a completion from the core
|
||||
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
|
||||
|
||||
val uri = virtualFile?.toUriOrNull() ?: return
|
||||
|
||||
val line = editor.caretModel.primaryCaret.logicalPosition.line
|
||||
val column = editor.caretModel.primaryCaret.logicalPosition.column
|
||||
val input = mapOf(
|
||||
"completionId" to completionId,
|
||||
"filepath" to virtualFile?.url,
|
||||
"filepath" to uri,
|
||||
"pos" to mapOf(
|
||||
"line" to editor.caretModel.primaryCaret.logicalPosition.line,
|
||||
"line" to line,
|
||||
"character" to column
|
||||
),
|
||||
"recentlyEditedFiles" to emptyList<String>(),
|
||||
"recentlyEditedRanges" to emptyList<String>(),
|
||||
"clipboardText" to ""
|
||||
"clipboardText" to "",
|
||||
"recentlyEditedRanges" to emptyList<Any>(),
|
||||
"recentlyVisitedRanges" to emptyList<Any>(),
|
||||
)
|
||||
|
||||
val lineStart = editor.document.getLineStartOffset(editor.caretModel.primaryCaret.logicalPosition.line)
|
||||
val lineEnd = editor.document.getLineEndOffset(editor.caretModel.primaryCaret.logicalPosition.line)
|
||||
val lineLength = lineEnd - lineStart
|
||||
|
||||
project.service<ContinuePluginService>().coreMessenger?.request(
|
||||
"autocomplete/complete",
|
||||
input,
|
||||
|
|
@ -95,24 +113,28 @@ class AutocompleteService(private val project: Project) {
|
|||
val completion = completions[0].toString()
|
||||
val finalTextToInsert = deduplicateCompletion(editor, offset, completion)
|
||||
|
||||
if (shouldRenderCompletion(finalTextToInsert, column, lineLength, editor)) {
|
||||
if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) {
|
||||
renderCompletion(editor, offset, finalTextToInsert)
|
||||
pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert)
|
||||
// Hide auto-popup
|
||||
// AutoPopupController.getInstance(project).cancelAllRequests()
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
private fun shouldRenderCompletion(completion: String, column: Int, lineLength: Int, editor: Editor): Boolean {
|
||||
if (completion.isEmpty()) {
|
||||
private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean {
|
||||
if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (completion.lines().size == 1) {
|
||||
return true
|
||||
}
|
||||
|
||||
val endOffset = editor.document.getLineEndOffset(line)
|
||||
|
||||
// Do not render if completion is multi-line and caret is in middle of line
|
||||
return !(completion.lines().size > 1 && column < lineLength)
|
||||
return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank()
|
||||
}
|
||||
|
||||
private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String {
|
||||
|
|
@ -126,9 +148,9 @@ class AutocompleteService(private val project: Project) {
|
|||
|
||||
val N = 10
|
||||
var textAfterCursor = if (caretOffset + N <= document.textLength) {
|
||||
document.getText(com.intellij.openapi.util.TextRange(caretOffset, caretOffset + N))
|
||||
document.getText(TextRange(caretOffset, caretOffset + N))
|
||||
} else {
|
||||
document.getText(com.intellij.openapi.util.TextRange(caretOffset, document.textLength))
|
||||
document.getText(TextRange(caretOffset, document.textLength))
|
||||
}
|
||||
|
||||
// Avoid truncating the completion text when the text after the cursor is blank
|
||||
|
|
@ -171,19 +193,9 @@ class AutocompleteService(private val project: Project) {
|
|||
properties.relatesToPrecedingText(true)
|
||||
properties.disableSoftWrapping(true)
|
||||
|
||||
if (completion.lines().size > 1) {
|
||||
editor.inlayModel.addBlockElement(
|
||||
offset,
|
||||
properties,
|
||||
ContinueMultilineCustomElementRenderer(editor, completion)
|
||||
)
|
||||
} else {
|
||||
editor.inlayModel.addInlineElement(
|
||||
offset,
|
||||
properties,
|
||||
ContinueCustomElementRenderer(editor, completion)
|
||||
)
|
||||
}
|
||||
val lines = completion.lines()
|
||||
pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n"))
|
||||
editor.addInlayElement(lines, offset, properties)
|
||||
|
||||
// val attributes = TextAttributes().apply {
|
||||
// backgroundColor = JBColor.GREEN
|
||||
|
|
@ -211,7 +223,7 @@ class AutocompleteService(private val project: Project) {
|
|||
({})
|
||||
)
|
||||
invokeLater {
|
||||
clearCompletions(editor)
|
||||
clearCompletions(editor, completion)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -274,23 +286,14 @@ class AutocompleteService(private val project: Project) {
|
|||
project.service<ContinuePluginService>().coreMessenger?.request("autocomplete/cancel", null, null, ({}))
|
||||
}
|
||||
|
||||
fun clearCompletions(editor: Editor) {
|
||||
fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) {
|
||||
if (isInjectedFile(editor)) return
|
||||
|
||||
if (pendingCompletion != null) {
|
||||
cancelCompletion(pendingCompletion!!)
|
||||
pendingCompletion = null
|
||||
}
|
||||
editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach {
|
||||
if (it.renderer is ContinueCustomElementRenderer) {
|
||||
it.dispose()
|
||||
}
|
||||
}
|
||||
editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach {
|
||||
if (it.renderer is ContinueMultilineCustomElementRenderer) {
|
||||
it.dispose()
|
||||
}
|
||||
if (completion != null) {
|
||||
cancelCompletion(completion)
|
||||
if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null
|
||||
}
|
||||
disposeInlayRenderer(editor)
|
||||
}
|
||||
|
||||
private fun isInjectedFile(editor: Editor): Boolean {
|
||||
|
|
@ -306,13 +309,17 @@ class AutocompleteService(private val project: Project) {
|
|||
fun hideCompletions(editor: Editor) {
|
||||
if (isInjectedFile(editor)) return
|
||||
|
||||
disposeInlayRenderer(editor)
|
||||
}
|
||||
|
||||
private fun disposeInlayRenderer(editor: Editor) {
|
||||
editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach {
|
||||
if (it.renderer is ContinueCustomElementRenderer) {
|
||||
if (it.renderer is ContinueInlayRenderer) {
|
||||
it.dispose()
|
||||
}
|
||||
}
|
||||
editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach {
|
||||
if (it.renderer is ContinueMultilineCustomElementRenderer) {
|
||||
if (it.renderer is ContinueInlayRenderer) {
|
||||
it.dispose()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,45 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.EditorCustomElementRenderer
|
||||
import com.intellij.openapi.editor.Inlay
|
||||
import com.intellij.openapi.editor.colors.EditorFontType
|
||||
import com.intellij.openapi.editor.impl.EditorImpl
|
||||
import com.intellij.openapi.editor.impl.FontInfo
|
||||
import com.intellij.openapi.editor.markup.TextAttributes
|
||||
import com.intellij.ui.JBColor
|
||||
import com.intellij.util.ui.UIUtil
|
||||
import java.awt.Font
|
||||
import java.awt.Graphics
|
||||
import java.awt.Rectangle
|
||||
import kotlin.math.ceil
|
||||
|
||||
class ContinueCustomElementRenderer(
|
||||
val editor: Editor,
|
||||
val text: String,
|
||||
) : EditorCustomElementRenderer {
|
||||
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
|
||||
val width = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(this.text)
|
||||
return width
|
||||
}
|
||||
|
||||
private fun font(editor: Editor): Font {
|
||||
val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN)
|
||||
return UIUtil.getFontWithFallbackIfNeeded(editorFont, text).deriveFont(editor.colorsScheme.editorFontSize)
|
||||
}
|
||||
|
||||
private fun offsetY(editor: Editor): Int {
|
||||
val metrics =
|
||||
FontInfo.getFontMetrics(font(editor), FontInfo.getFontRenderContext(editor.contentComponent))
|
||||
val fontHeight =
|
||||
font(editor).createGlyphVector(metrics.fontRenderContext, text).visualBounds.height
|
||||
val height = (editor.lineHeight + fontHeight) / 2
|
||||
return ceil(height).toInt()
|
||||
}
|
||||
|
||||
override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) {
|
||||
g.color = JBColor.GRAY
|
||||
g.font = font(inlay.editor)
|
||||
g.drawString(this.text, targetRegion.x, targetRegion.y + inlay.editor.ascent)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.EditorCustomElementRenderer
|
||||
import com.intellij.openapi.editor.Inlay
|
||||
import com.intellij.openapi.editor.colors.EditorFontType
|
||||
import com.intellij.openapi.editor.impl.EditorImpl
|
||||
import com.intellij.openapi.editor.markup.TextAttributes
|
||||
import com.intellij.ui.JBColor
|
||||
import com.intellij.util.ui.UIUtil
|
||||
import java.awt.Font
|
||||
import java.awt.Graphics
|
||||
import java.awt.Rectangle
|
||||
|
||||
/**
|
||||
* The `ContinueInlayRenderer` class is responsible for rendering custom inlay elements within an editor.
|
||||
* It implements the [EditorCustomElementRenderer] interface to provide custom rendering logic for inlays.
|
||||
*
|
||||
* This renderer is designed to display a list of text lines (`lines`) within the editor, calculating the
|
||||
* necessary width and height based on the content and rendering each line with appropriate font and color.
|
||||
*
|
||||
* @author lk
|
||||
*/
|
||||
class ContinueInlayRenderer(val lines: List<String>) : EditorCustomElementRenderer {
|
||||
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
|
||||
var maxLen = 0;
|
||||
for (line in lines) {
|
||||
val len = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(line)
|
||||
if (len > maxLen) {
|
||||
maxLen = len
|
||||
}
|
||||
}
|
||||
return maxLen
|
||||
}
|
||||
|
||||
override fun calcHeightInPixels(inlay: Inlay<*>): Int {
|
||||
return (inlay.editor as EditorImpl).lineHeight * lines.size
|
||||
}
|
||||
|
||||
private fun font(editor: Editor): Font {
|
||||
val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN)
|
||||
return UIUtil.getFontWithFallbackIfNeeded(editorFont, lines.joinToString("\n"))
|
||||
.deriveFont(editor.colorsScheme.editorFontSize)
|
||||
}
|
||||
|
||||
override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) {
|
||||
val editor = inlay.editor
|
||||
g.color = JBColor.GRAY
|
||||
g.font = font(editor)
|
||||
var additionalYOffset = 0
|
||||
val ascent = editor.ascent
|
||||
val lineHeight = editor.lineHeight
|
||||
for (line in lines) {
|
||||
g.drawString(line, targetRegion.x, targetRegion.y + ascent + additionalYOffset)
|
||||
additionalYOffset += lineHeight
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,81 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.autocomplete
|
||||
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.EditorCustomElementRenderer
|
||||
import com.intellij.openapi.editor.Inlay
|
||||
import com.intellij.openapi.editor.colors.EditorFontType
|
||||
import com.intellij.openapi.editor.impl.EditorImpl
|
||||
import com.intellij.openapi.editor.impl.FontInfo
|
||||
import com.intellij.openapi.editor.markup.TextAttributes
|
||||
import com.intellij.ui.JBColor
|
||||
import com.intellij.util.ui.UIUtil
|
||||
import java.awt.Font
|
||||
import java.awt.Graphics
|
||||
import java.awt.Rectangle
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.max
|
||||
|
||||
class ContinueMultilineCustomElementRenderer(
|
||||
val editor: Editor,
|
||||
val text: String,
|
||||
) : EditorCustomElementRenderer {
|
||||
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
|
||||
val lines = text.lines()
|
||||
var maxLen = 0;
|
||||
for (line in lines) {
|
||||
val len = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(line)
|
||||
if (len > maxLen) {
|
||||
maxLen = len
|
||||
}
|
||||
}
|
||||
return maxLen
|
||||
}
|
||||
|
||||
override fun calcHeightInPixels(inlay: Inlay<*>): Int {
|
||||
return (inlay.editor as EditorImpl).lineHeight * text.lines().size
|
||||
}
|
||||
|
||||
protected val font: Font
|
||||
get() {
|
||||
val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN)
|
||||
return UIUtil.getFontWithFallbackIfNeeded(editorFont, text).deriveFont(editor.colorsScheme.editorFontSize)
|
||||
}
|
||||
|
||||
private fun offsetY(): Int {
|
||||
val metrics =
|
||||
FontInfo.getFontMetrics(font, FontInfo.getFontRenderContext(editor.contentComponent))
|
||||
val fontHeight =
|
||||
font.createGlyphVector(metrics.fontRenderContext, text).visualBounds.height
|
||||
val height = (editor.lineHeight + fontHeight) / 2
|
||||
return ceil(height).toInt()
|
||||
}
|
||||
|
||||
private fun offsetX(): Int {
|
||||
val currentLine = editor.caretModel.primaryCaret.logicalPosition.line
|
||||
val currentColumn = editor.caretModel.primaryCaret.logicalPosition.column
|
||||
val metrics =
|
||||
FontInfo.getFontMetrics(font, FontInfo.getFontRenderContext(editor.contentComponent))
|
||||
val fontWidth =
|
||||
font.createGlyphVector(metrics.fontRenderContext, text).visualBounds.width
|
||||
val widthBeforeCaret = (editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(
|
||||
text.substring(0, minOf(currentColumn, text.length))
|
||||
)
|
||||
return max(0, widthBeforeCaret - (editor as EditorImpl).scrollingModel.horizontalScrollOffset)
|
||||
}
|
||||
|
||||
override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) {
|
||||
g.color = JBColor.GRAY
|
||||
g.font = font
|
||||
var additionalYOffset = -editor.lineHeight;
|
||||
var isFirstLine = true
|
||||
for (line in text.lines()) {
|
||||
g.drawString(
|
||||
line,
|
||||
if (isFirstLine) targetRegion.x + offsetX() else targetRegion.x,
|
||||
targetRegion.y + inlay.editor.ascent + additionalYOffset
|
||||
)
|
||||
additionalYOffset += editor.lineHeight
|
||||
isFirstLine = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -549,12 +549,14 @@ class IdeProtocolClient(
|
|||
val startChar = startOffset - document.getLineStartOffset(startLine)
|
||||
val endChar = endOffset - document.getLineStartOffset(endLine)
|
||||
|
||||
return@runReadAction RangeInFileWithContents(
|
||||
virtualFile.url, Range(
|
||||
Position(startLine, startChar),
|
||||
Position(endLine, endChar)
|
||||
), selectedText
|
||||
)
|
||||
return@runReadAction virtualFile.toUriOrNull()?.let {
|
||||
RangeInFileWithContents(
|
||||
it, Range(
|
||||
Position(startLine, startChar),
|
||||
Position(endLine, endChar)
|
||||
), selectedText
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
|
|||
import com.github.continuedev.continueintellijextension.utils.OS
|
||||
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
|
||||
import com.github.continuedev.continueintellijextension.utils.getOS
|
||||
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
|
||||
import com.intellij.codeInsight.daemon.impl.HighlightInfo
|
||||
import com.intellij.execution.configurations.GeneralCommandLine
|
||||
import com.intellij.execution.util.ExecUtil
|
||||
|
|
@ -180,7 +181,7 @@ class IntelliJIDE(
|
|||
for (workspaceDir in workspaceDirs) {
|
||||
val dir = VirtualFileManager.getInstance().findFileByUrl(workspaceDir)
|
||||
if (dir != null) {
|
||||
val contents = dir.children.map { it.url }
|
||||
val contents = dir.children.mapNotNull { it.toUriOrNull() }
|
||||
|
||||
// Find any .continuerc.json files
|
||||
for (file in contents) {
|
||||
|
|
@ -261,7 +262,7 @@ class IntelliJIDE(
|
|||
content
|
||||
} else {
|
||||
val file = File(URI(filepath))
|
||||
if (!file.exists()) return ""
|
||||
if (!file.exists() || file.isDirectory) return ""
|
||||
withContext(Dispatchers.IO) {
|
||||
FileInputStream(file).use { fis ->
|
||||
val sizeToRead = minOf(100000, file.length()).toInt()
|
||||
|
|
@ -269,6 +270,8 @@ class IntelliJIDE(
|
|||
val bytesRead = fis.read(buffer, 0, sizeToRead)
|
||||
if (bytesRead <= 0) return@use ""
|
||||
String(buffer, 0, bytesRead, Charset.forName("UTF-8"))
|
||||
// `\r` takes up unnecessary tokens
|
||||
.lineSequence().joinToString("\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -307,16 +310,16 @@ class IntelliJIDE(
|
|||
|
||||
override suspend fun getOpenFiles(): List<String> {
|
||||
val fileEditorManager = FileEditorManager.getInstance(project)
|
||||
return fileEditorManager.openFiles.map { it.url }.toList()
|
||||
return fileEditorManager.openFiles.mapNotNull { it.toUriOrNull() }.toList()
|
||||
}
|
||||
|
||||
override suspend fun getCurrentFile(): Map<String, Any>? {
|
||||
val fileEditorManager = FileEditorManager.getInstance(project)
|
||||
val editor = fileEditorManager.selectedTextEditor
|
||||
val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) }
|
||||
return virtualFile?.let {
|
||||
return virtualFile?.toUriOrNull()?.let {
|
||||
mapOf(
|
||||
"path" to it.url,
|
||||
"path" to it,
|
||||
"contents" to editor.document.text,
|
||||
"isUntitled" to false
|
||||
)
|
||||
|
|
@ -382,7 +385,7 @@ class IntelliJIDE(
|
|||
|
||||
problems.add(
|
||||
Problem(
|
||||
filepath = psiFile.virtualFile?.url ?: "",
|
||||
filepath = psiFile.virtualFile?.toUriOrNull() ?: "",
|
||||
range = Range(
|
||||
start = Position(
|
||||
line = startLineNumber,
|
||||
|
|
@ -561,6 +564,6 @@ class IntelliJIDE(
|
|||
return dirs
|
||||
}
|
||||
|
||||
return listOfNotNull(project.guessProjectDir()?.url).toTypedArray()
|
||||
return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray()
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
package com.github.continuedev.continueintellijextension.utils
|
||||
|
||||
import com.intellij.openapi.vfs.VirtualFile
|
||||
import java.net.NetworkInterface
|
||||
import java.util.*
|
||||
import java.awt.event.KeyEvent.*
|
||||
|
|
@ -77,4 +78,6 @@ fun getMachineUniqueID(): String {
|
|||
|
||||
fun uuid(): String {
|
||||
return UUID.randomUUID().toString()
|
||||
}
|
||||
}
|
||||
|
||||
fun VirtualFile.toUriOrNull(): String? = fileSystem.getNioPath(this)?.toUri()?.toString()?.removeSuffix("/")
|
||||
|
|
@ -5,6 +5,6 @@
|
|||
},
|
||||
"extends": ["../../.eslintrc.shared.json"],
|
||||
"rules": {
|
||||
"@typescript-eslint/naming-convention": "warn"
|
||||
"@typescript-eslint/naming-convention": "off"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1906,6 +1906,9 @@
|
|||
"repo-map",
|
||||
"greptile",
|
||||
"web",
|
||||
"gitlab-mr",
|
||||
"discord",
|
||||
"jira",
|
||||
"clipboard"
|
||||
],
|
||||
"markdownEnumDescriptions": [
|
||||
|
|
@ -2057,8 +2060,7 @@
|
|||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["params"]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
|
|
@ -2083,6 +2085,73 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["repo-map"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"includeSignatures": {
|
||||
"type": "boolean",
|
||||
"description": "Include message signatures from repo-map",
|
||||
"default": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["debugger"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"stackDepth": {
|
||||
"title": "Stack Depth",
|
||||
"description": "Stack trace depth to include in context",
|
||||
"default": 3,
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["diff"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"includeUnstaged": {
|
||||
"type": "boolean",
|
||||
"description": "Include diff from unstaged files",
|
||||
"default": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
|
@ -2317,7 +2386,7 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["codebase", "folder"]
|
||||
"enum": ["codebase", "folder", "docs"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -2401,10 +2470,11 @@
|
|||
"default": 3,
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["host", "port", "user", "password", "database"]
|
||||
}
|
||||
},
|
||||
"required": ["host", "port", "user", "password", "database"]
|
||||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
|
|
@ -2431,10 +2501,11 @@
|
|||
"default": "",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["GreptileToken", "GithubToken"]
|
||||
}
|
||||
},
|
||||
"required": ["GreptileToken", "GithubToken"]
|
||||
"required": ["params"]
|
||||
}
|
||||
}
|
||||
],
|
||||
|
|
@ -3166,11 +3237,6 @@
|
|||
"description": "Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.",
|
||||
"default": false
|
||||
},
|
||||
"useTools": {
|
||||
"type": "boolean",
|
||||
"description": "Allow tool use. Currently only supported with Claude 3.5 Sonnet",
|
||||
"default": true
|
||||
},
|
||||
"modelContextProtocolServers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,6 @@
|
|||
import { expect } from "chai";
|
||||
import {
|
||||
Key,
|
||||
WebElement,
|
||||
waitForAttributeValue,
|
||||
} from "vscode-extension-tester";
|
||||
import { Key } from "vscode-extension-tester";
|
||||
|
||||
import { DEFAULT_TIMEOUT } from "./constants";
|
||||
|
||||
export class TestUtils {
|
||||
|
|
|
|||
40
extensions/vscode/e2e/actions/Edit.actions.ts
Normal file
40
extensions/vscode/e2e/actions/Edit.actions.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { TextEditor, WebView } from "vscode-extension-tester";
|
||||
|
||||
import { EditSelectors } from "../selectors/Edit.selectors";
|
||||
import { TestUtils } from "../TestUtils";
|
||||
|
||||
export class EditActions {
|
||||
static async invokeEditShortcut(editor: TextEditor) {
|
||||
editor
|
||||
.getDriver()
|
||||
.actions()
|
||||
.keyDown(TestUtils.osControlKey)
|
||||
.sendKeys("i")
|
||||
.keyUp(TestUtils.osControlKey)
|
||||
.perform();
|
||||
}
|
||||
|
||||
static async acceptEditInGUI(view: WebView): Promise<void> {
|
||||
await TestUtils.waitForSuccess(async () =>
|
||||
(await EditSelectors.getEditAcceptButton(view)).click(),
|
||||
);
|
||||
await view.switchBack();
|
||||
}
|
||||
|
||||
static async rejectEditInGUI(view: WebView): Promise<void> {
|
||||
await TestUtils.waitForSuccess(async () =>
|
||||
(await EditSelectors.getEditRejectButton(view)).click(),
|
||||
);
|
||||
await view.switchBack();
|
||||
}
|
||||
|
||||
static async acceptEditWithCodeLens(editor: TextEditor): Promise<void> {
|
||||
const acceptCodeLens = await editor.getCodeLens("Accept");
|
||||
await acceptCodeLens?.click();
|
||||
}
|
||||
|
||||
static async rejectEditWithCodeLens(editor: TextEditor): Promise<void> {
|
||||
const rejectCodeLens = await editor.getCodeLens("Reject");
|
||||
await rejectCodeLens?.click();
|
||||
}
|
||||
}
|
||||
|
|
@ -6,9 +6,10 @@ import {
|
|||
WebView,
|
||||
Workbench,
|
||||
} from "vscode-extension-tester";
|
||||
|
||||
import { DEFAULT_TIMEOUT } from "../constants";
|
||||
import { GUISelectors } from "../selectors/GUI.selectors";
|
||||
import { TestUtils } from "../TestUtils";
|
||||
import { DEFAULT_TIMEOUT } from "../constants";
|
||||
|
||||
export class GUIActions {
|
||||
public static moveContinueToSidebar = async (driver: WebDriver) => {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,29 @@
|
|||
import { VSBrowser, WebView } from "vscode-extension-tester";
|
||||
import {
|
||||
EditorView,
|
||||
InputBox,
|
||||
TextEditor,
|
||||
VSBrowser,
|
||||
Workbench,
|
||||
} from "vscode-extension-tester";
|
||||
|
||||
import { DEFAULT_TIMEOUT } from "../constants";
|
||||
|
||||
export class GlobalActions {
|
||||
public static async openTestWorkspace() {
|
||||
return VSBrowser.instance.openResources("e2e/test-continue");
|
||||
}
|
||||
|
||||
public static async createAndOpenNewTextFile(): Promise<{
|
||||
editor: TextEditor;
|
||||
}> {
|
||||
await new Workbench().executeCommand("Create: New File...");
|
||||
await (
|
||||
await InputBox.create(DEFAULT_TIMEOUT.MD)
|
||||
).selectQuickPick("Text File");
|
||||
const editor = (await new EditorView().openEditor(
|
||||
"Untitled-1",
|
||||
)) as TextEditor;
|
||||
|
||||
return { editor };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,4 @@
|
|||
import { TextEditor, WebDriver, WebView } from "vscode-extension-tester";
|
||||
|
||||
import { TestUtils } from "../TestUtils";
|
||||
import { TextEditor } from "vscode-extension-tester";
|
||||
|
||||
export class KeyboardShortcutsActions {
|
||||
/**
|
||||
|
|
|
|||
13
extensions/vscode/e2e/selectors/Edit.selectors.ts
Normal file
13
extensions/vscode/e2e/selectors/Edit.selectors.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { WebView } from "vscode-extension-tester";
|
||||
|
||||
import { SelectorUtils } from "./SelectorUtils";
|
||||
|
||||
export class EditSelectors {
|
||||
public static getEditAcceptButton(view: WebView) {
|
||||
return SelectorUtils.getElementByDataTestId(view, "edit-accept-button");
|
||||
}
|
||||
|
||||
public static getEditRejectButton(view: WebView) {
|
||||
return SelectorUtils.getElementByDataTestId(view, "edit-reject-button");
|
||||
}
|
||||
}
|
||||
|
|
@ -16,11 +16,7 @@ describe("Autocomplete", () => {
|
|||
this.timeout(DEFAULT_TIMEOUT.XL);
|
||||
|
||||
await GlobalActions.openTestWorkspace();
|
||||
await new Workbench().executeCommand("Create: New File...");
|
||||
await (
|
||||
await InputBox.create(DEFAULT_TIMEOUT.MD)
|
||||
).selectQuickPick("Text File");
|
||||
editor = (await new EditorView().openEditor("Untitled-1")) as TextEditor;
|
||||
({ editor } = await GlobalActions.createAndOpenNewTextFile());
|
||||
});
|
||||
|
||||
afterEach(async function () {
|
||||
|
|
|
|||
125
extensions/vscode/e2e/tests/Edit.test.ts
Normal file
125
extensions/vscode/e2e/tests/Edit.test.ts
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
import {
|
||||
EditorView,
|
||||
WebView,
|
||||
WebDriver,
|
||||
Key,
|
||||
VSBrowser,
|
||||
InputBox,
|
||||
TextEditor,
|
||||
Workbench,
|
||||
} from "vscode-extension-tester";
|
||||
|
||||
import { EditActions } from "../actions/Edit.actions";
|
||||
import { GlobalActions } from "../actions/Global.actions";
|
||||
import { GUIActions } from "../actions/GUI.actions";
|
||||
import { DEFAULT_TIMEOUT } from "../constants";
|
||||
import { EditSelectors } from "../selectors/Edit.selectors";
|
||||
import { GUISelectors } from "../selectors/GUI.selectors";
|
||||
import { TestUtils } from "../TestUtils";
|
||||
|
||||
describe("Edit Test", () => {
|
||||
let view: WebView;
|
||||
let editor: TextEditor;
|
||||
let originalEditorText = "Hello world!";
|
||||
let { userMessage, llmResponse } = TestUtils.generateTestMessagePair();
|
||||
|
||||
before(async function () {
|
||||
this.timeout(DEFAULT_TIMEOUT.XL);
|
||||
await GUIActions.moveContinueToSidebar(VSBrowser.instance.driver);
|
||||
await GlobalActions.openTestWorkspace();
|
||||
({ editor } = await GlobalActions.createAndOpenNewTextFile());
|
||||
});
|
||||
|
||||
beforeEach(async function () {
|
||||
this.timeout(DEFAULT_TIMEOUT.XL);
|
||||
|
||||
await GUIActions.toggleGui();
|
||||
|
||||
await editor.typeTextAt(1, 1, originalEditorText);
|
||||
await editor.selectText(originalEditorText);
|
||||
|
||||
await EditActions.invokeEditShortcut(editor);
|
||||
|
||||
({ view } = await GUIActions.switchToReactIframe());
|
||||
|
||||
await GUIActions.sendMessage({
|
||||
view,
|
||||
message: userMessage,
|
||||
inputFieldIndex: 0,
|
||||
});
|
||||
|
||||
await view.switchBack();
|
||||
|
||||
await TestUtils.waitForSuccess(async () => {
|
||||
const editorText = await editor.getText();
|
||||
return editorText.includes(llmResponse);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async function () {
|
||||
this.timeout(DEFAULT_TIMEOUT.XL);
|
||||
await editor.clearText();
|
||||
});
|
||||
|
||||
it("Accepts an Edit in the GUI", async () => {
|
||||
({ view } = await GUIActions.switchToReactIframe());
|
||||
|
||||
await EditActions.acceptEditInGUI(view);
|
||||
|
||||
await view.switchBack();
|
||||
|
||||
const editorText = await editor.getText();
|
||||
|
||||
await TestUtils.waitForSuccess(
|
||||
async () =>
|
||||
!editorText.includes(originalEditorText) &&
|
||||
editorText.includes(llmResponse),
|
||||
DEFAULT_TIMEOUT.SM,
|
||||
);
|
||||
}).timeout(DEFAULT_TIMEOUT.XL);
|
||||
|
||||
it("Rejects an Edit in the GUI", async () => {
|
||||
({ view } = await GUIActions.switchToReactIframe());
|
||||
|
||||
await EditActions.rejectEditInGUI(view);
|
||||
|
||||
await view.switchBack();
|
||||
|
||||
const editorText = await editor.getText();
|
||||
|
||||
await TestUtils.waitForSuccess(
|
||||
async () =>
|
||||
editorText.includes(originalEditorText) &&
|
||||
!editorText.includes(llmResponse),
|
||||
DEFAULT_TIMEOUT.SM,
|
||||
);
|
||||
}).timeout(DEFAULT_TIMEOUT.XL);
|
||||
|
||||
it("Accepts an Edit using CodeLens buttons", async () => {
|
||||
const acceptCodeLens = await editor.getCodeLens("Accept");
|
||||
await acceptCodeLens?.click();
|
||||
|
||||
const editorText = await editor.getText();
|
||||
|
||||
await TestUtils.waitForSuccess(
|
||||
async () =>
|
||||
!editorText.includes(originalEditorText) &&
|
||||
editorText.includes(llmResponse),
|
||||
DEFAULT_TIMEOUT.SM,
|
||||
);
|
||||
}).timeout(DEFAULT_TIMEOUT.XL);
|
||||
|
||||
it("Rejects an Edit using CodeLens buttons", async () => {
|
||||
const rejectCodeLens = await editor.getCodeLens("Reject");
|
||||
await rejectCodeLens?.click();
|
||||
|
||||
const editorText = await editor.getText();
|
||||
|
||||
await TestUtils.waitForSuccess(
|
||||
async () =>
|
||||
!editorText.includes(originalEditorText) &&
|
||||
editorText.includes(llmResponse),
|
||||
DEFAULT_TIMEOUT.SM,
|
||||
);
|
||||
}).timeout(DEFAULT_TIMEOUT.XL);
|
||||
});
|
||||
46
extensions/vscode/package-lock.json
generated
46
extensions/vscode/package-lock.json
generated
|
|
@ -35,6 +35,7 @@
|
|||
"https-proxy-agent": "^7.0.2",
|
||||
"ignore": "^5.3.0",
|
||||
"jsdom": "^24.0.0",
|
||||
"lru-cache": "^11.0.2",
|
||||
"minisearch": "^7.0.0",
|
||||
"monaco-editor": "^0.45.0",
|
||||
"monaco-vscode-textmate-theme-converter": "^0.1.7",
|
||||
|
|
@ -6739,6 +6740,18 @@
|
|||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/hosted-git-info/node_modules/lru-cache": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
|
||||
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"yallist": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/hpagent": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/hpagent/-/hpagent-1.2.0.tgz",
|
||||
|
|
@ -7920,15 +7933,11 @@
|
|||
}
|
||||
},
|
||||
"node_modules/lru-cache": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
|
||||
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
|
||||
"devOptional": true,
|
||||
"dependencies": {
|
||||
"yallist": "^4.0.0"
|
||||
},
|
||||
"version": "11.0.2",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.2.tgz",
|
||||
"integrity": "sha512-123qHRfJBmo2jXDbo/a5YOQrJoHF/GNQTLzQ5+IdK5pWpceK17yRc6ozlWd25FxvGKQbIUs91fDFkXmDHTKcyA==",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/lru-queue": {
|
||||
|
|
@ -9368,6 +9377,18 @@
|
|||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/node-gyp/node_modules/lru-cache": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
|
||||
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"yallist": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/node-gyp/node_modules/make-fetch-happen": {
|
||||
"version": "9.1.0",
|
||||
"resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-9.1.0.tgz",
|
||||
|
|
@ -14300,15 +14321,6 @@
|
|||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/vscode-extension-tester/node_modules/lru-cache": {
|
||||
"version": "11.0.2",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.2.tgz",
|
||||
"integrity": "sha512-123qHRfJBmo2jXDbo/a5YOQrJoHF/GNQTLzQ5+IdK5pWpceK17yRc6ozlWd25FxvGKQbIUs91fDFkXmDHTKcyA==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/vscode-extension-tester/node_modules/markdown-it": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz",
|
||||
|
|
|
|||
|
|
@ -689,6 +689,7 @@
|
|||
"https-proxy-agent": "^7.0.2",
|
||||
"ignore": "^5.3.0",
|
||||
"jsdom": "^24.0.0",
|
||||
"lru-cache": "^11.0.2",
|
||||
"minisearch": "^7.0.0",
|
||||
"monaco-editor": "^0.45.0",
|
||||
"monaco-vscode-textmate-theme-converter": "^0.1.7",
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ const {
|
|||
installNodeModuleInTempDirAndCopyToCurrent,
|
||||
downloadSqliteBinary,
|
||||
copyTokenizers,
|
||||
copyScripts,
|
||||
} = require("./utils");
|
||||
|
||||
// Clear folders that will be packaged to ensure clean slate
|
||||
|
|
@ -108,6 +109,9 @@ async function package(target, os, arch, exe) {
|
|||
// copy llama tokenizers to out
|
||||
copyTokenizers();
|
||||
|
||||
// Copy Linux scripts
|
||||
await copyScripts();
|
||||
|
||||
// *** Install @lancedb binary ***
|
||||
const lancePackageToInstall = {
|
||||
"darwin-arm64": "@lancedb/vectordb-darwin-arm64",
|
||||
|
|
|
|||
|
|
@ -222,6 +222,7 @@ const exe = os === "win32" ? ".exe" : "";
|
|||
"../../../core/llm/llamaTokenizerWorkerPool.mjs",
|
||||
"../../../core/llm/llamaTokenizer.mjs",
|
||||
"../../../core/llm/tiktokenWorkerPool.mjs",
|
||||
"../../../core/util/start_ollama.sh"
|
||||
];
|
||||
|
||||
for (const f of filesToCopy) {
|
||||
|
|
|
|||
|
|
@ -505,6 +505,26 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
}
|
||||
}
|
||||
|
||||
async function copyScripts() {
|
||||
process.chdir(path.join(continueDir, "extensions", "vscode"));
|
||||
console.log("[info] Copying scripts from core");
|
||||
await new Promise((resolve, reject) => {
|
||||
ncp(
|
||||
path.join(__dirname, "../../../core/scripts"),
|
||||
path.join(__dirname, "../out"),
|
||||
{ dereference: true },
|
||||
(error) => {
|
||||
if (error) {
|
||||
console.warn("[error] Error copying script files", error);
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
copyConfigSchema,
|
||||
installNodeModules,
|
||||
|
|
@ -519,4 +539,5 @@ module.exports = {
|
|||
downloadSqliteBinary,
|
||||
downloadRipgrepBinary,
|
||||
copyTokenizers,
|
||||
copyScripts
|
||||
};
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ import type {
|
|||
Location,
|
||||
Problem,
|
||||
RangeInFile,
|
||||
TerminalOptions,
|
||||
Thread,
|
||||
} from "core";
|
||||
|
||||
|
|
@ -398,17 +399,21 @@ class VsCodeIde implements IDE {
|
|||
);
|
||||
}
|
||||
|
||||
async runCommand(command: string): Promise<void> {
|
||||
if (vscode.window.terminals.length) {
|
||||
const terminal =
|
||||
vscode.window.activeTerminal ?? vscode.window.terminals[0];
|
||||
terminal.show();
|
||||
terminal.sendText(command, false);
|
||||
} else {
|
||||
const terminal = vscode.window.createTerminal();
|
||||
terminal.show();
|
||||
terminal.sendText(command, false);
|
||||
async runCommand(command: string, options: TerminalOptions = {reuseTerminal: true}): Promise<void> {
|
||||
let terminal: vscode.Terminal | undefined;
|
||||
if (vscode.window.terminals.length && options.reuseTerminal) {
|
||||
if (options.terminalName) {
|
||||
terminal = vscode.window.terminals.find(t => t?.name === options.terminalName);
|
||||
} else {
|
||||
terminal = vscode.window.activeTerminal ?? vscode.window.terminals[0];
|
||||
}
|
||||
}
|
||||
|
||||
if( !terminal) {
|
||||
terminal = vscode.window.createTerminal(options?.terminalName);
|
||||
}
|
||||
terminal.show();
|
||||
terminal.sendText(command, false);
|
||||
}
|
||||
|
||||
async saveFile(fileUri: string): Promise<void> {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,121 @@
|
|||
import { IDE } from "core";
|
||||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippetType,
|
||||
} from "core/autocomplete/snippets/types";
|
||||
import { PosthogFeatureFlag, Telemetry } from "core/util/posthog";
|
||||
import { LRUCache } from "lru-cache";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
/**
|
||||
* Service to keep track of recently visited ranges in files.
|
||||
*/
|
||||
export class RecentlyVisitedRangesService {
|
||||
private cache: LRUCache<
|
||||
string,
|
||||
Array<AutocompleteCodeSnippet & { timestamp: number }>
|
||||
>;
|
||||
// Default value, we override in initWithPostHog
|
||||
private numSurroundingLines = 5;
|
||||
private maxRecentFiles = 3;
|
||||
private maxSnippetsPerFile = 3;
|
||||
private isEnabled = false;
|
||||
|
||||
constructor(private readonly ide: IDE) {
|
||||
this.cache = new LRUCache<
|
||||
string,
|
||||
Array<AutocompleteCodeSnippet & { timestamp: number }>
|
||||
>({
|
||||
max: this.maxRecentFiles,
|
||||
});
|
||||
|
||||
void this.initWithPostHog();
|
||||
}
|
||||
|
||||
private async initWithPostHog() {
|
||||
const recentlyVisitedRangesNumSurroundingLines =
|
||||
await Telemetry.getValueForFeatureFlag(
|
||||
PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines,
|
||||
);
|
||||
|
||||
if (!recentlyVisitedRangesNumSurroundingLines) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isEnabled = true;
|
||||
this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines;
|
||||
vscode.window.onDidChangeTextEditorSelection(
|
||||
this.cacheCurrentSelectionContext,
|
||||
);
|
||||
}
|
||||
|
||||
private cacheCurrentSelectionContext = async (
|
||||
event: vscode.TextEditorSelectionChangeEvent,
|
||||
) => {
|
||||
const filepath = event.textEditor.document.uri.toString();
|
||||
const line = event.selections[0].active.line;
|
||||
const startLine = Math.max(0, line - this.numSurroundingLines);
|
||||
const endLine = Math.min(
|
||||
line + this.numSurroundingLines,
|
||||
event.textEditor.document.lineCount - 1,
|
||||
);
|
||||
|
||||
try {
|
||||
const fileContents = await this.ide.readFile(filepath);
|
||||
const lines = fileContents.split("\n");
|
||||
const relevantLines = lines
|
||||
.slice(startLine, endLine + 1)
|
||||
.join("\n")
|
||||
.trim();
|
||||
|
||||
const snippet: AutocompleteCodeSnippet & { timestamp: number } = {
|
||||
filepath,
|
||||
content: relevantLines,
|
||||
type: AutocompleteSnippetType.Code,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
const existing = this.cache.get(filepath) || [];
|
||||
const newSnippets = [...existing, snippet]
|
||||
.sort((a, b) => b.timestamp - a.timestamp)
|
||||
.slice(0, this.maxSnippetsPerFile);
|
||||
|
||||
this.cache.set(filepath, newSnippets);
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"Error caching recently visited ranges for autocomplete: ",
|
||||
err,
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns up to {@link maxSnippetsPerFile} snippets from the {@link maxRecentFiles} most recently visited files.
|
||||
* Excludes snippets from the currently active file.
|
||||
* @returns Array of code snippets from recently visited files
|
||||
*/
|
||||
public getSnippets(): AutocompleteCodeSnippet[] {
|
||||
if (!this.isEnabled) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const currentFilepath =
|
||||
vscode.window.activeTextEditor?.document.uri.toString();
|
||||
let allSnippets: Array<AutocompleteCodeSnippet & { timestamp: number }> =
|
||||
[];
|
||||
|
||||
// Get most recent snippets from each file in cache
|
||||
for (const filepath of Array.from(this.cache.keys())) {
|
||||
const snippets = (this.cache.get(filepath) || [])
|
||||
.sort((a, b) => b.timestamp - a.timestamp)
|
||||
.slice(0, this.maxSnippetsPerFile);
|
||||
allSnippets = [...allSnippets, ...snippets];
|
||||
}
|
||||
|
||||
return allSnippets
|
||||
.filter((s) => !currentFilepath || s.filepath !== currentFilepath)
|
||||
.sort((a, b) => b.timestamp - a.timestamp)
|
||||
.map(({ timestamp, ...snippet }) => snippet);
|
||||
}
|
||||
}
|
||||
|
|
@ -4,25 +4,28 @@ import {
|
|||
type AutocompleteOutcome,
|
||||
} from "core/autocomplete/util/types";
|
||||
import { ConfigHandler } from "core/config/ConfigHandler";
|
||||
import * as URI from "uri-js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import * as vscode from "vscode";
|
||||
const Diff = require("diff");
|
||||
|
||||
import { showFreeTrialLoginMessage } from "../util/messages";
|
||||
import { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
|
||||
import { getDefinitionsFromLsp } from "./lsp";
|
||||
import { RecentlyEditedTracker } from "./recentlyEdited";
|
||||
import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService";
|
||||
import {
|
||||
StatusBarStatus,
|
||||
getStatusBarStatus,
|
||||
setupStatusBar,
|
||||
stopStatusBarLoading,
|
||||
} from "./statusBar";
|
||||
import * as URI from "uri-js";
|
||||
|
||||
import type { IDE } from "core";
|
||||
import type { TabAutocompleteModel } from "../util/loadAutocompleteModel";
|
||||
import { startLocalOllama } from "core/util/ollamaHelper";
|
||||
import type { IDE } from "core";
|
||||
|
||||
const Diff = require("diff");
|
||||
|
||||
interface DiffType {
|
||||
count: number;
|
||||
|
|
@ -42,8 +45,10 @@ export class ContinueCompletionProvider
|
|||
{
|
||||
private onError(e: any) {
|
||||
const options = ["Documentation"];
|
||||
if (e.message.includes("https://ollama.ai")) {
|
||||
if (e.message.includes("Ollama may not be installed")) {
|
||||
options.push("Download Ollama");
|
||||
} else if (e.message.includes("Ollama may not be running")) {
|
||||
options.unshift("Start Ollama"); // We want "Start" to be the default choice
|
||||
}
|
||||
|
||||
if (e.message.includes("Please sign in with GitHub")) {
|
||||
|
|
@ -65,11 +70,14 @@ export class ContinueCompletionProvider
|
|||
);
|
||||
} else if (val === "Download Ollama") {
|
||||
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download"));
|
||||
} else if (val == "Start Ollama") {
|
||||
startLocalOllama(this.ide);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private completionProvider: CompletionProvider;
|
||||
private recentlyVisitedRanges: RecentlyVisitedRangesService;
|
||||
private recentlyEditedTracker = new RecentlyEditedTracker();
|
||||
|
||||
constructor(
|
||||
|
|
@ -85,6 +93,7 @@ export class ContinueCompletionProvider
|
|||
this.onError.bind(this),
|
||||
getDefinitionsFromLsp,
|
||||
);
|
||||
this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide);
|
||||
}
|
||||
|
||||
_lastShownCompletion: AutocompleteOutcome | undefined;
|
||||
|
|
@ -126,30 +135,6 @@ export class ContinueCompletionProvider
|
|||
}
|
||||
|
||||
let injectDetails: string | undefined = undefined;
|
||||
// Here we could use the details from the intellisense dropdown
|
||||
// and place them just above the line being typed but because
|
||||
// we don't have control over the formatting of the details and
|
||||
// they could be especially long, not doing this for now
|
||||
// if (context.selectedCompletionInfo) {
|
||||
// const results: any = await vscode.commands.executeCommand(
|
||||
// "vscode.executeCompletionItemProvider",
|
||||
// document.uri,
|
||||
// position,
|
||||
// null,
|
||||
// 1,
|
||||
// );
|
||||
// if (results?.items) {
|
||||
// injectDetails = results.items?.[0]?.detail;
|
||||
// // const label = results?.items?.[0].label;
|
||||
// // const workspaceSymbols = (
|
||||
// // (await vscode.commands.executeCommand(
|
||||
// // "vscode.executeWorkspaceSymbolProvider",
|
||||
// // label,
|
||||
// // )) as any
|
||||
// // ).filter((symbol: any) => symbol.name === label);
|
||||
// // console.log(label, "=>", workspaceSymbols);
|
||||
// }
|
||||
// }
|
||||
|
||||
// The first time intellisense dropdown shows up, and the first choice is selected,
|
||||
// we should not consider this. Only once user explicitly moves down the list
|
||||
|
|
@ -213,17 +198,17 @@ export class ContinueCompletionProvider
|
|||
let manuallyPassPrefix: string | undefined = undefined;
|
||||
|
||||
const input: AutocompleteInput = {
|
||||
isUntitledFile: document.isUntitled,
|
||||
completionId: uuidv4(),
|
||||
filepath: document.uri.toString(),
|
||||
pos,
|
||||
recentlyEditedFiles: [],
|
||||
recentlyEditedRanges:
|
||||
await this.recentlyEditedTracker.getRecentlyEditedRanges(),
|
||||
manuallyPassFileContents,
|
||||
manuallyPassPrefix,
|
||||
selectedCompletionInfo,
|
||||
injectDetails,
|
||||
isUntitledFile: document.isUntitled,
|
||||
completionId: uuidv4(),
|
||||
filepath: document.uri.toString(),
|
||||
recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(),
|
||||
recentlyEditedRanges:
|
||||
await this.recentlyEditedTracker.getRecentlyEditedRanges(),
|
||||
};
|
||||
|
||||
setupStatusBar(undefined, true);
|
||||
|
|
|
|||
|
|
@ -739,10 +739,12 @@ const getCommandsMap: (
|
|||
if (fullScreenTab && fullScreenPanel) {
|
||||
// Full screen open, but not focused - focus it
|
||||
fullScreenPanel.reveal();
|
||||
vscode.commands.executeCommand("continue.focusContinueInput");
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear the sidebar to prevent overwriting changes made in fullscreen
|
||||
vscode.commands.executeCommand("continue.newSession")
|
||||
|
||||
// Full screen not open - open it
|
||||
captureCommandTelemetry("openFullScreen");
|
||||
|
||||
|
|
@ -767,7 +769,7 @@ const getCommandsMap: (
|
|||
true,
|
||||
);
|
||||
|
||||
panel.onDidChangeViewState(() => {
|
||||
const sessionLoader = panel.onDidChangeViewState(() => {
|
||||
vscode.commands.executeCommand("continue.newSession");
|
||||
if (sessionId) {
|
||||
vscode.commands.executeCommand(
|
||||
|
|
@ -775,6 +777,7 @@ const getCommandsMap: (
|
|||
sessionId,
|
||||
);
|
||||
}
|
||||
sessionLoader.dispose()
|
||||
});
|
||||
|
||||
// When panel closes, reset the webview and focus
|
||||
|
|
|
|||
|
|
@ -13,13 +13,8 @@ export function registerDebugTracker(
|
|||
vscode.debug.registerDebugAdapterTrackerFactory("*", {
|
||||
createDebugAdapterTracker(_session: vscode.DebugSession) {
|
||||
const updateThreads = async () => {
|
||||
webviewProtocol?.request("updateSubmenuItems", {
|
||||
provider: "debugger",
|
||||
submenuItems: (await ide.getAvailableThreads()).map((thread) => ({
|
||||
id: `${thread.id}`,
|
||||
title: thread.name,
|
||||
description: `${thread.id}`,
|
||||
})),
|
||||
webviewProtocol?.request("refreshSubmenuItems", {
|
||||
providers: ["debugger"],
|
||||
});
|
||||
};
|
||||
|
||||
|
|
@ -33,30 +28,34 @@ export function registerDebugTracker(
|
|||
switch (message.event) {
|
||||
case "continued":
|
||||
case "stopped":
|
||||
if (typeof message.body.threadId !== "undefined")
|
||||
{threadStopped.set(
|
||||
if (typeof message.body.threadId !== "undefined") {
|
||||
threadStopped.set(
|
||||
Number(message.body.threadId),
|
||||
message.event === "stopped",
|
||||
);}
|
||||
);
|
||||
}
|
||||
|
||||
if (message.body.allThreadsStopped)
|
||||
{threadStopped.forEach((_, key) =>
|
||||
if (message.body.allThreadsStopped) {
|
||||
threadStopped.forEach((_, key) =>
|
||||
threadStopped.set(key, true),
|
||||
);}
|
||||
);
|
||||
}
|
||||
|
||||
if (message.body.allThreadsContinued)
|
||||
{threadStopped.forEach((_, key) =>
|
||||
if (message.body.allThreadsContinued) {
|
||||
threadStopped.forEach((_, key) =>
|
||||
threadStopped.set(key, false),
|
||||
);}
|
||||
);
|
||||
}
|
||||
|
||||
updateThreads();
|
||||
break;
|
||||
|
||||
case "thread":
|
||||
if (message.body.reason === "exited")
|
||||
{threadStopped.delete(Number(message.body.threadId));}
|
||||
else if (message.body.reason === "started")
|
||||
{threadStopped.set(Number(message.body.threadId), false);}
|
||||
if (message.body.reason === "exited") {
|
||||
threadStopped.delete(Number(message.body.threadId));
|
||||
} else if (message.body.reason === "started") {
|
||||
threadStopped.set(Number(message.body.threadId), false);
|
||||
}
|
||||
// somehow the threadId does not respect the specification in my vscodium (debugging C++)
|
||||
// expecting a number but got a string instead
|
||||
break;
|
||||
|
|
|
|||
|
|
@ -11,6 +11,9 @@
|
|||
// "plugin:@typescript-eslint/recommended-requiring-type-checking"
|
||||
// "plugin:react/recommended"
|
||||
],
|
||||
"rules": {
|
||||
"@typescript-eslint/naming-convention": "off"
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["src/**/*.{js,ts,jsx,tsx}"]
|
||||
|
|
|
|||
|
|
@ -1,11 +1,9 @@
|
|||
import { useState, useEffect, useRef } from "react";
|
||||
import {
|
||||
ContextSubmenuItemWithProvider,
|
||||
useSubmenuContextProviders,
|
||||
} from "../../context/SubmenuContextProviders";
|
||||
import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders";
|
||||
import { Combobox } from "@headlessui/react";
|
||||
import FileIcon from "../FileIcon";
|
||||
import { useAppSelector } from "../../redux/hooks";
|
||||
import { ContextSubmenuItemWithProvider } from "core";
|
||||
|
||||
export interface AddFileComboboxProps {
|
||||
onSelect: (filepaths: string[]) => void | Promise<void>;
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ export default function AcceptRejectAllButtons({
|
|||
<button
|
||||
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
|
||||
onClick={() => handleAcceptOrReject("rejectDiff")}
|
||||
data-testid="edit-reject-button"
|
||||
>
|
||||
<XMarkIcon className="mr-1 h-4 w-4 text-red-600" />
|
||||
{isSingleRangeEdit ? (
|
||||
|
|
@ -53,6 +54,7 @@ export default function AcceptRejectAllButtons({
|
|||
<button
|
||||
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
|
||||
onClick={() => handleAcceptOrReject("acceptDiff")}
|
||||
data-testid="edit-accept-button"
|
||||
>
|
||||
<CheckIcon className="mr-1 h-4 w-4 text-green-600" />
|
||||
{isSingleRangeEdit ? (
|
||||
|
|
|
|||
|
|
@ -79,10 +79,11 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) {
|
|||
if (!status) {
|
||||
return 0;
|
||||
}
|
||||
return Math.min(100, Math.max(0, status.progress * 100));
|
||||
return Math.min(100, Math.max(0, status.progress * 100)).toFixed(0);
|
||||
}, [status?.progress]);
|
||||
|
||||
const Icon = STATUS_TO_ICON[status?.status];
|
||||
const showProgressPercentage = progressPercentage !== "100";
|
||||
|
||||
if (hasDeleted) return null;
|
||||
|
||||
|
|
@ -116,7 +117,15 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) {
|
|||
<div className="text-xs text-stone-500">Pending...</div>
|
||||
) : (
|
||||
<div className="flex flex-row items-center gap-1 text-stone-500">
|
||||
<span className="text-xs">{progressPercentage.toFixed(0)}%</span>
|
||||
{showProgressPercentage && (
|
||||
<span className="text-xs">{progressPercentage}%</span>
|
||||
)}
|
||||
{status?.status !== "indexing" ? (
|
||||
<TrashIcon
|
||||
className="h-4 w-4 cursor-pointer text-stone-500 hover:brightness-125"
|
||||
onClick={onDelete}
|
||||
/>
|
||||
) : null}
|
||||
{Icon ? (
|
||||
<Icon
|
||||
className={`inline-block h-4 w-4 text-stone-500 ${
|
||||
|
|
@ -124,12 +133,6 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) {
|
|||
}`}
|
||||
></Icon>
|
||||
) : null}
|
||||
{status?.status !== "indexing" ? (
|
||||
<TrashIcon
|
||||
className="h-4 w-4 cursor-pointer text-stone-500"
|
||||
onClick={onDelete}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -26,10 +26,10 @@ function DocsIndexingStatuses() {
|
|||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex flex-row items-center justify-between">
|
||||
<h3 className="mb-1 mt-0 text-xl">@docs indexes</h3>
|
||||
<h3 className="mb-0 mt-0 text-xl">@docs indexes</h3>
|
||||
{configDocs.length ? (
|
||||
<SecondaryButton
|
||||
className="flex h-7 flex-col items-center justify-center"
|
||||
className="!my-0 flex h-7 flex-col items-center justify-center"
|
||||
onClick={() => {
|
||||
dispatch(setShowDialog(true));
|
||||
dispatch(setDialogMessage(<AddDocsDialog />));
|
||||
|
|
|
|||
|
|
@ -81,9 +81,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
|
|||
const availableContextProviders = useAppSelector(
|
||||
(state) => state.config.config.contextProviders,
|
||||
);
|
||||
const useTools = useAppSelector(
|
||||
(state) => state.config.config.experimental?.useTools !== false,
|
||||
);
|
||||
const editModeState = useAppSelector((state) => state.editModeState);
|
||||
|
||||
const filteredSlashCommands = props.isEditMode ? [] : availableSlashCommands;
|
||||
|
|
@ -114,9 +111,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
|
|||
hideTools: true,
|
||||
enterText: editModeState.editStatus === "accepting" ? "Retry" : "Edit",
|
||||
}
|
||||
: {
|
||||
hideTools: !useTools,
|
||||
};
|
||||
: {};
|
||||
|
||||
return (
|
||||
<div className={`${props.hidden ? "hidden" : ""}`}>
|
||||
|
|
|
|||
|
|
@ -2,17 +2,21 @@ import {
|
|||
ArrowRightIcon,
|
||||
ArrowUpOnSquareIcon,
|
||||
AtSymbolIcon,
|
||||
Bars3BottomLeftIcon,
|
||||
BoltIcon,
|
||||
BookOpenIcon,
|
||||
BugAntIcon,
|
||||
CircleStackIcon,
|
||||
CodeBracketIcon,
|
||||
CommandLineIcon,
|
||||
CpuChipIcon,
|
||||
DocumentTextIcon,
|
||||
ExclamationCircleIcon,
|
||||
ExclamationTriangleIcon,
|
||||
FolderIcon,
|
||||
FolderOpenIcon,
|
||||
GlobeAltIcon,
|
||||
MagnifyingGlassIcon,
|
||||
PaperClipIcon,
|
||||
PlusIcon,
|
||||
SparklesIcon,
|
||||
TrashIcon,
|
||||
|
|
@ -43,6 +47,10 @@ import SafeImg from "../SafeImg";
|
|||
import AddDocsDialog from "../dialogs/AddDocsDialog";
|
||||
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
|
||||
import { ComboBoxItem, ComboBoxItemType } from "./types";
|
||||
import { DiscordIcon } from "../svg/DiscordIcon";
|
||||
import { GoogleIcon } from "../svg/GoogleIcon";
|
||||
import { GitlabIcon } from "../svg/GitlabIcon";
|
||||
import { GithubIcon } from "../svg/GithubIcon";
|
||||
|
||||
const ICONS_FOR_DROPDOWN: { [key: string]: any } = {
|
||||
file: FolderIcon,
|
||||
|
|
@ -56,14 +64,23 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = {
|
|||
problems: ExclamationTriangleIcon,
|
||||
folder: FolderIcon,
|
||||
docs: BookOpenIcon,
|
||||
issue: ExclamationCircleIcon,
|
||||
trash: TrashIcon,
|
||||
web: GlobeAltIcon,
|
||||
clipboard: PaperClipIcon,
|
||||
database: CircleStackIcon,
|
||||
postgres: CircleStackIcon,
|
||||
debugger: BugAntIcon,
|
||||
os: CpuChipIcon,
|
||||
tree: Bars3BottomLeftIcon,
|
||||
"prompt-files": DocumentTextIcon,
|
||||
"repo-map": FolderIcon,
|
||||
"/clear": TrashIcon,
|
||||
"/share": ArrowUpOnSquareIcon,
|
||||
"/cmd": CommandLineIcon,
|
||||
issue: GithubIcon,
|
||||
discord: DiscordIcon,
|
||||
google: GoogleIcon,
|
||||
"gitlab-mr": GitlabIcon,
|
||||
http: GlobeAltIcon,
|
||||
};
|
||||
|
||||
export function getIconFromDropdownItem(
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
import { Editor, ReactRenderer } from "@tiptap/react";
|
||||
import { ContextProviderDescription, ContextSubmenuItem } from "core";
|
||||
import {
|
||||
ContextProviderDescription,
|
||||
ContextSubmenuItem,
|
||||
ContextSubmenuItemWithProvider,
|
||||
} from "core";
|
||||
import { MutableRefObject } from "react";
|
||||
import tippy from "tippy.js";
|
||||
import { IIdeMessenger } from "../../context/IdeMessenger";
|
||||
|
|
@ -112,7 +116,7 @@ export function getContextProviderDropdownOptions(
|
|||
(
|
||||
providerTitle: string | undefined,
|
||||
query: string,
|
||||
) => (ContextSubmenuItem & { providerTitle: string })[]
|
||||
) => ContextSubmenuItemWithProvider[]
|
||||
>,
|
||||
enterSubmenu: (editor: Editor, providerId: string) => void,
|
||||
onClose: () => void,
|
||||
|
|
@ -137,7 +141,7 @@ export function getContextProviderDropdownOptions(
|
|||
});
|
||||
}
|
||||
|
||||
const mainResults: any[] =
|
||||
const contextProviderMatches: ComboBoxItem[] =
|
||||
availableContextProvidersRef.current
|
||||
?.filter(
|
||||
(provider) =>
|
||||
|
|
@ -156,21 +160,8 @@ export function getContextProviderDropdownOptions(
|
|||
}))
|
||||
.sort((c, _) => (c.id === "file" ? -1 : 1)) || [];
|
||||
|
||||
if (mainResults.length === 0) {
|
||||
const results = getSubmenuContextItemsRef.current(undefined, query);
|
||||
return results.map((result) => {
|
||||
return {
|
||||
...result,
|
||||
label: result.title,
|
||||
type: result.providerTitle as ComboBoxItemType,
|
||||
query: result.id,
|
||||
icon: result.icon,
|
||||
};
|
||||
});
|
||||
} else if (
|
||||
mainResults.length === availableContextProvidersRef.current.length
|
||||
) {
|
||||
mainResults.push({
|
||||
if (contextProviderMatches.length) {
|
||||
contextProviderMatches.push({
|
||||
title: "Add more context providers",
|
||||
type: "action",
|
||||
action: () => {
|
||||
|
|
@ -181,8 +172,20 @@ export function getContextProviderDropdownOptions(
|
|||
},
|
||||
description: "",
|
||||
});
|
||||
return contextProviderMatches;
|
||||
}
|
||||
return mainResults;
|
||||
|
||||
// No provider matches -> search all providers
|
||||
const results = getSubmenuContextItemsRef.current(undefined, query);
|
||||
return results.map((result) => {
|
||||
return {
|
||||
...result,
|
||||
label: result.title,
|
||||
type: result.providerTitle as ComboBoxItemType,
|
||||
query: result.id,
|
||||
icon: result.icon,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
return getSuggestion(items, enterSubmenu, onClose, onOpen);
|
||||
|
|
|
|||
26
gui/src/components/svg/GitlabIcon.tsx
Normal file
26
gui/src/components/svg/GitlabIcon.tsx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
interface CustomGitlabIconProps extends React.SVGProps<SVGSVGElement> {
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export function GitlabIcon({
|
||||
size = 24,
|
||||
className,
|
||||
...props
|
||||
}: CustomGitlabIconProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
className={className}
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d="M22.363 14.565l-2.555-7.876A.684.684 0 0019.151 6a.684.684 0 00-.657.488l-2.555 7.878H7.935l-2.556-7.878A.684.684 0 004.722 6a.684.684 0 00-.657.488L1.51 14.564a.679.679 0 00.255.754l9.555 6.947a.686.686 0 00.79 0l9.555-6.947a.681.681 0 00.255-.754z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
26
gui/src/components/svg/GoogleIcon.tsx
Normal file
26
gui/src/components/svg/GoogleIcon.tsx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
interface CustomGoogleIconProps extends React.SVGProps<SVGSVGElement> {
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export function GoogleIcon({
|
||||
size = 24,
|
||||
className,
|
||||
...props
|
||||
}: CustomGoogleIconProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
className={className}
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d="M21.805 10.023H12v4h5.641C16.864 16.504 14.072 18 12 18c-3.309 0-6-2.691-6-6s2.691-6 6-6c1.58 0 3.031 0.594 4.137 1.563l3.1-3.1C17.389 3.565 14.833 2 12 2 6.477 2 2 6.477 2 12s4.477 10 10 10c5.377 0 10-4.623 10-10 0-.666-.07-1.313-.195-1.977z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,17 +1,14 @@
|
|||
import { ContextSubmenuItem } from "core";
|
||||
import {
|
||||
ContextProviderDescription,
|
||||
ContextProviderName,
|
||||
ContextSubmenuItemWithProvider,
|
||||
} from "core";
|
||||
import { createContext } from "react";
|
||||
import { deduplicateArray } from "core/util";
|
||||
import MiniSearch, { SearchResult } from "minisearch";
|
||||
import {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useCallback, useContext, useEffect, useRef, useState } from "react";
|
||||
import { IdeMessengerContext } from "./IdeMessenger";
|
||||
import { selectContextProviderDescriptions } from "../redux/selectors";
|
||||
import { selectSubmenuContextProviders } from "../redux/selectors";
|
||||
import { useWebviewListener } from "../hooks/useWebviewListener";
|
||||
import { useAppSelector } from "../redux/hooks";
|
||||
import {
|
||||
|
|
@ -26,142 +23,89 @@ const MINISEARCH_OPTIONS = {
|
|||
|
||||
const MAX_LENGTH = 70;
|
||||
|
||||
export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem {
|
||||
providerTitle: string;
|
||||
}
|
||||
|
||||
interface SubtextContextProvidersContextType {
|
||||
getSubmenuContextItems: (
|
||||
providerTitle: string | undefined,
|
||||
query: string,
|
||||
) => (ContextSubmenuItem & { providerTitle: string })[];
|
||||
addItem: (providerTitle: string, item: ContextSubmenuItem) => void;
|
||||
) => ContextSubmenuItemWithProvider[];
|
||||
initialLoadComplete: boolean;
|
||||
}
|
||||
|
||||
const initialContextProviders: SubtextContextProvidersContextType = {
|
||||
getSubmenuContextItems: () => [],
|
||||
addItem: () => {},
|
||||
initialLoadComplete: false,
|
||||
};
|
||||
|
||||
const SubmenuContextProvidersContext =
|
||||
createContext<SubtextContextProvidersContextType>(initialContextProviders);
|
||||
|
||||
function isOpenFilesChanged(
|
||||
newFiles: { id: string }[],
|
||||
oldFiles: { id: string }[],
|
||||
) {
|
||||
if (newFiles.length > oldFiles.length) {
|
||||
return true;
|
||||
}
|
||||
for (let i = 0; i < newFiles.length; ++i) {
|
||||
if (newFiles[i].id !== oldFiles[i].id) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export const SubmenuContextProvidersProvider = ({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
const [minisearches, setMinisearches] = useState<{
|
||||
[id: string]: MiniSearch;
|
||||
}>({});
|
||||
const [fallbackResults, setFallbackResults] = useState<{
|
||||
[id: string]: ContextSubmenuItem[];
|
||||
}>({});
|
||||
|
||||
const contextProviderDescriptions = useAppSelector(
|
||||
selectContextProviderDescriptions,
|
||||
);
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const submenuContextProviders = useAppSelector(selectSubmenuContextProviders);
|
||||
const disableIndexing = useAppSelector(
|
||||
(store) => store.config.config.disableIndexing,
|
||||
);
|
||||
|
||||
const [initialLoadComplete, setInitialLoadComplete] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [autoLoadTriggered, setAutoLoadTriggered] = useState(false);
|
||||
const [minisearches, setMinisearches] = useState<{
|
||||
[id: string]: MiniSearch<ContextSubmenuItemWithProvider>;
|
||||
}>({});
|
||||
const [fallbackResults, setFallbackResults] = useState<{
|
||||
[id: string]: ContextSubmenuItemWithProvider[];
|
||||
}>({});
|
||||
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const getOpenFilesItems = useCallback(async () => {
|
||||
const openFiles = await ideMessenger.ide.getOpenFiles();
|
||||
const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs();
|
||||
const withUniquePaths = getShortestUniqueRelativeUriPaths(
|
||||
openFiles,
|
||||
workspaceDirs,
|
||||
);
|
||||
|
||||
return withUniquePaths.map((file) => ({
|
||||
id: file.uri,
|
||||
title: getUriPathBasename(file.uri),
|
||||
description: file.uniquePath,
|
||||
providerTitle: "file",
|
||||
}));
|
||||
}, [ideMessenger]);
|
||||
|
||||
useWebviewListener("refreshSubmenuItems", async () => {
|
||||
if (!isLoading) {
|
||||
setInitialLoadComplete(false);
|
||||
setAutoLoadTriggered((prev) => !prev); // Toggle to trigger effect
|
||||
}
|
||||
});
|
||||
|
||||
useWebviewListener("updateSubmenuItems", async (data) => {
|
||||
const minisearch = new MiniSearch<ContextSubmenuItem>({
|
||||
fields: ["title", "description"],
|
||||
storeFields: ["id", "title", "description"],
|
||||
});
|
||||
|
||||
minisearch.addAll(data.submenuItems);
|
||||
|
||||
setMinisearches((prev) => ({ ...prev, [data.provider]: minisearch }));
|
||||
|
||||
if (data.provider === "file") {
|
||||
const openFiles = await getOpenFilesItems();
|
||||
setFallbackResults((prev) => ({
|
||||
...prev,
|
||||
file: [
|
||||
...openFiles,
|
||||
...data.submenuItems.slice(0, MAX_LENGTH - openFiles.length),
|
||||
],
|
||||
}));
|
||||
} else {
|
||||
setFallbackResults((prev) => ({
|
||||
...prev,
|
||||
[data.provider]: data.submenuItems.slice(0, MAX_LENGTH),
|
||||
}));
|
||||
}
|
||||
});
|
||||
|
||||
const addItem = useCallback(
|
||||
(providerTitle: string, item: ContextSubmenuItem) => {
|
||||
if (!minisearches[providerTitle]) {
|
||||
return;
|
||||
}
|
||||
minisearches[providerTitle].add(item);
|
||||
},
|
||||
[minisearches],
|
||||
);
|
||||
|
||||
const lastOpenFilesRef = useRef<
|
||||
Awaited<ReturnType<typeof getOpenFilesItems>>
|
||||
>([]);
|
||||
// Update open files for file provider on an interval
|
||||
const lastOpenFilesRef = useRef<ContextSubmenuItemWithProvider[]>([]);
|
||||
useEffect(() => {
|
||||
function hasOpenFilesChanged(
|
||||
newFiles: ContextSubmenuItemWithProvider[],
|
||||
oldFiles: ContextSubmenuItemWithProvider[],
|
||||
) {
|
||||
const newIds = new Set(newFiles.map((f) => f.id));
|
||||
const oldIds = new Set(oldFiles.map((f) => f.id));
|
||||
|
||||
if (newIds.size !== oldIds.size) return true;
|
||||
|
||||
for (const id of newIds) {
|
||||
if (!oldIds.has(id)) return true;
|
||||
}
|
||||
|
||||
for (const id of oldIds) {
|
||||
if (!newIds.has(id)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
let isMounted = true;
|
||||
const refreshOpenFiles = async () => {
|
||||
if (!isMounted) return;
|
||||
const openFiles = await getOpenFilesItems();
|
||||
if (isOpenFilesChanged(openFiles, lastOpenFilesRef.current)) {
|
||||
|
||||
const openFiles = await ideMessenger.ide.getOpenFiles();
|
||||
const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs();
|
||||
const withUniquePaths = getShortestUniqueRelativeUriPaths(
|
||||
openFiles,
|
||||
workspaceDirs,
|
||||
);
|
||||
const openFileItems = withUniquePaths.map((file) => ({
|
||||
id: file.uri,
|
||||
title: getUriPathBasename(file.uri),
|
||||
description: file.uniquePath,
|
||||
providerTitle: "file",
|
||||
}));
|
||||
|
||||
if (hasOpenFilesChanged(openFileItems, lastOpenFilesRef.current)) {
|
||||
setFallbackResults((prev) => ({
|
||||
...prev,
|
||||
file: deduplicateArray(
|
||||
[...openFiles, ...(Array.isArray(prev.file) ? prev.file : [])],
|
||||
[...openFileItems, ...(prev.file ?? [])],
|
||||
(a, b) => a.id === b.id,
|
||||
),
|
||||
}));
|
||||
lastOpenFilesRef.current = openFiles;
|
||||
}
|
||||
lastOpenFilesRef.current = openFileItems;
|
||||
};
|
||||
|
||||
const interval = setInterval(refreshOpenFiles, 2000);
|
||||
|
|
@ -172,117 +116,121 @@ export const SubmenuContextProvidersProvider = ({
|
|||
isMounted = false;
|
||||
clearInterval(interval);
|
||||
};
|
||||
}, [getOpenFilesItems]);
|
||||
}, [ideMessenger]);
|
||||
|
||||
const [initialLoadComplete, setInitialLoadComplete] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const getSubmenuContextItems = useCallback(
|
||||
(
|
||||
providerTitle: string | undefined,
|
||||
query: string,
|
||||
limit: number = MAX_LENGTH,
|
||||
): ContextSubmenuItemWithProvider[] => {
|
||||
try {
|
||||
// 1. Search using minisearch
|
||||
let searchResults: (SearchResult & ContextSubmenuItemWithProvider)[] =
|
||||
[];
|
||||
|
||||
const getSubmenuSearchResults = useMemo(
|
||||
() =>
|
||||
(providerTitle: string | undefined, query: string): SearchResult[] => {
|
||||
if (providerTitle === undefined) {
|
||||
// Return search combined from all providers
|
||||
const results = Object.keys(minisearches).map((providerTitle) => {
|
||||
const results = minisearches[providerTitle].search(
|
||||
query,
|
||||
MINISEARCH_OPTIONS,
|
||||
);
|
||||
return results.map((result) => {
|
||||
return { ...result, providerTitle };
|
||||
});
|
||||
});
|
||||
|
||||
return results.flat().sort((a, b) => b.score - a.score);
|
||||
}
|
||||
if (!minisearches[providerTitle]) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const results = minisearches[providerTitle]
|
||||
.search(query, MINISEARCH_OPTIONS)
|
||||
.map((result) => {
|
||||
return { ...result, providerTitle };
|
||||
});
|
||||
|
||||
return results;
|
||||
},
|
||||
[minisearches],
|
||||
);
|
||||
|
||||
const getSubmenuContextItems = useMemo(
|
||||
() =>
|
||||
(
|
||||
providerTitle: string | undefined,
|
||||
query: string,
|
||||
limit: number = MAX_LENGTH,
|
||||
): (ContextSubmenuItem & { providerTitle: string })[] => {
|
||||
try {
|
||||
const results = getSubmenuSearchResults(providerTitle, query);
|
||||
if (results.length === 0) {
|
||||
const fallbackItems = (
|
||||
providerTitle ? (fallbackResults[providerTitle] ?? []) : []
|
||||
)
|
||||
.slice(0, limit)
|
||||
// Include results from all providers
|
||||
searchResults = Object.keys(minisearches).flatMap((providerTitle) =>
|
||||
minisearches[providerTitle]
|
||||
.search(query, MINISEARCH_OPTIONS)
|
||||
.map((result) => {
|
||||
return {
|
||||
...result,
|
||||
providerTitle: providerTitle || "unknown",
|
||||
providerTitle,
|
||||
title: result.title,
|
||||
description: result.description,
|
||||
};
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
// Only include results from the specified provider
|
||||
if (minisearches[providerTitle]) {
|
||||
searchResults = minisearches[providerTitle]
|
||||
.search(query, MINISEARCH_OPTIONS)
|
||||
.map((result) => {
|
||||
return {
|
||||
...result,
|
||||
providerTitle,
|
||||
title: result.title,
|
||||
description: result.description,
|
||||
};
|
||||
});
|
||||
|
||||
if (fallbackItems.length === 0 && !initialLoadComplete) {
|
||||
return [
|
||||
{
|
||||
id: "loading",
|
||||
title: "Loading...",
|
||||
description: "Please wait while items are being loaded",
|
||||
providerTitle: providerTitle || "unknown",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return fallbackItems;
|
||||
}
|
||||
const limitedResults = results.slice(0, limit).map((result) => {
|
||||
return {
|
||||
id: result.id,
|
||||
title: result.title,
|
||||
description: result.description,
|
||||
providerTitle: result.providerTitle,
|
||||
};
|
||||
});
|
||||
return limitedResults;
|
||||
} catch (error) {
|
||||
console.error("Error in getSubmenuContextItems:", error);
|
||||
return [];
|
||||
}
|
||||
},
|
||||
[fallbackResults, getSubmenuSearchResults, initialLoadComplete],
|
||||
searchResults.sort((a, b) => b.score - a.score);
|
||||
|
||||
// 2. Add fallback results if no search results
|
||||
if (searchResults.length === 0) {
|
||||
const fallbackItems = (
|
||||
providerTitle ? (fallbackResults[providerTitle] ?? []) : []
|
||||
)
|
||||
.slice(0, limit)
|
||||
.map((result) => {
|
||||
return {
|
||||
...result,
|
||||
providerTitle: providerTitle || "unknown",
|
||||
};
|
||||
});
|
||||
|
||||
if (fallbackItems.length === 0 && !initialLoadComplete) {
|
||||
return [
|
||||
{
|
||||
id: "loading",
|
||||
title: "Loading...",
|
||||
description: "Please wait while items are being loaded",
|
||||
providerTitle: providerTitle || "unknown",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return fallbackItems;
|
||||
}
|
||||
const limitedResults = searchResults.slice(0, limit).map((result) => {
|
||||
return {
|
||||
id: result.id,
|
||||
title: result.title,
|
||||
description: result.description,
|
||||
providerTitle: result.providerTitle,
|
||||
};
|
||||
});
|
||||
return limitedResults;
|
||||
} catch (error) {
|
||||
console.error("Error in getSubmenuContextItems:", error);
|
||||
return [];
|
||||
}
|
||||
},
|
||||
[fallbackResults, minisearches, initialLoadComplete],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (contextProviderDescriptions.length === 0 || isLoading) {
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
|
||||
const loadSubmenuItems = async () => {
|
||||
try {
|
||||
await Promise.all(
|
||||
contextProviderDescriptions.map(async (description) => {
|
||||
const shouldSkipProvider =
|
||||
description.dependsOnIndexing && disableIndexing;
|
||||
|
||||
if (shouldSkipProvider) {
|
||||
console.debug(
|
||||
`Skipping ${description.title} provider due to disabled indexing`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const loadSubmenuItems = useCallback(
|
||||
async (providers: "dependsOnIndexing" | "all" | ContextProviderName[]) => {
|
||||
setIsLoading(true);
|
||||
|
||||
await Promise.allSettled(
|
||||
submenuContextProviders.map(
|
||||
async (description: ContextProviderDescription) => {
|
||||
try {
|
||||
const minisearch = new MiniSearch<ContextSubmenuItem>({
|
||||
fields: ["title", "description"],
|
||||
storeFields: ["id", "title", "description"],
|
||||
});
|
||||
const refreshProvider =
|
||||
providers === "all"
|
||||
? true
|
||||
: providers === "dependsOnIndexing"
|
||||
? description.dependsOnIndexing
|
||||
: providers.includes(description.title);
|
||||
|
||||
if (!refreshProvider) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (description.dependsOnIndexing && disableIndexing) {
|
||||
console.debug(
|
||||
`Skipping ${description.title} provider due to disabled indexing`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const result = await ideMessenger.request(
|
||||
"context/loadSubmenuItems",
|
||||
{
|
||||
|
|
@ -291,61 +239,88 @@ export const SubmenuContextProvidersProvider = ({
|
|||
);
|
||||
|
||||
if (result.status === "error") {
|
||||
console.error(
|
||||
`Error loading items for ${description.title}:`,
|
||||
result.error,
|
||||
);
|
||||
return;
|
||||
throw new Error(result.error);
|
||||
}
|
||||
const items = result.content;
|
||||
const submenuItems = result.content;
|
||||
const providerTitle = description.title;
|
||||
|
||||
minisearch.addAll(items);
|
||||
const itemsWithProvider = submenuItems.map((item) => ({
|
||||
...item,
|
||||
providerTitle,
|
||||
}));
|
||||
|
||||
const minisearch = new MiniSearch<ContextSubmenuItemWithProvider>(
|
||||
{
|
||||
fields: ["title", "description"],
|
||||
storeFields: ["id", "title", "description", "providerTitle"],
|
||||
},
|
||||
);
|
||||
|
||||
minisearch.addAll(
|
||||
submenuItems.map((item) => ({ ...item, providerTitle })),
|
||||
);
|
||||
|
||||
setMinisearches((prev) => ({
|
||||
...prev,
|
||||
[description.title]: minisearch,
|
||||
[providerTitle]: minisearch,
|
||||
}));
|
||||
|
||||
if (description.title === "file") {
|
||||
const openFiles = await getOpenFilesItems();
|
||||
if (providerTitle === "file") {
|
||||
setFallbackResults((prev) => ({
|
||||
...prev,
|
||||
file: [
|
||||
...openFiles,
|
||||
...items.slice(0, MAX_LENGTH - openFiles.length),
|
||||
],
|
||||
file: deduplicateArray(
|
||||
[...lastOpenFilesRef.current, ...(prev.file ?? [])],
|
||||
(a, b) => a.id === b.id,
|
||||
),
|
||||
}));
|
||||
} else {
|
||||
setFallbackResults((prev) => ({
|
||||
...prev,
|
||||
[description.title]: items.slice(0, MAX_LENGTH),
|
||||
[providerTitle]: itemsWithProvider,
|
||||
}));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error processing ${description.title}:`, error);
|
||||
console.error(
|
||||
`Error loading items for ${description.title}:`,
|
||||
error,
|
||||
);
|
||||
console.error(
|
||||
"Error details:",
|
||||
JSON.stringify(error, Object.getOwnPropertyNames(error)),
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error in loadSubmenuItems:", error);
|
||||
} finally {
|
||||
setInitialLoadComplete(true);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
},
|
||||
),
|
||||
);
|
||||
setInitialLoadComplete(true);
|
||||
setIsLoading(false);
|
||||
},
|
||||
[submenuContextProviders, disableIndexing],
|
||||
);
|
||||
|
||||
loadSubmenuItems();
|
||||
}, [contextProviderDescriptions, autoLoadTriggered]);
|
||||
useWebviewListener(
|
||||
"refreshSubmenuItems",
|
||||
async (data) => {
|
||||
if (isLoading) {
|
||||
return;
|
||||
}
|
||||
if (data.providers === "all") {
|
||||
setInitialLoadComplete(false);
|
||||
}
|
||||
await loadSubmenuItems(data.providers);
|
||||
},
|
||||
[isLoading, loadSubmenuItems],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void loadSubmenuItems("all");
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SubmenuContextProvidersContext.Provider
|
||||
value={{
|
||||
getSubmenuContextItems,
|
||||
addItem,
|
||||
initialLoadComplete,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
|
|
|||
|
|
@ -427,13 +427,12 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n
|
|||
},
|
||||
...completionParamsInputsConfigs,
|
||||
],
|
||||
packages: [
|
||||
models.llama318BChat, models.mistralChat
|
||||
].map((p) => {
|
||||
packages: [models.llama318BChat, models.mistralChat].map((p) => {
|
||||
p.params.contextLength = 4096;
|
||||
return p;
|
||||
}),
|
||||
apiKeyUrl: "https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link",
|
||||
apiKeyUrl:
|
||||
"https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link",
|
||||
},
|
||||
gemini: {
|
||||
title: "Google Gemini API",
|
||||
|
|
@ -671,8 +670,8 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
|
|||
provider: "free-trial",
|
||||
refPage: "freetrial",
|
||||
description:
|
||||
"New users can try out Continue for free using a proxy server that securely makes calls to OpenAI, Anthropic, Together, or Novita AI using our API key",
|
||||
longDescription: `New users can try out Continue for free using a proxy server that securely makes calls to OpenAI, Anthropic, Together or Novita AI using our API key. If you are ready to set up a model for long-term use or have used all ${FREE_TRIAL_LIMIT_REQUESTS} free uses, you can enter your API key or use a local model.`,
|
||||
"New users can try out Continue for free using a proxy server that securely makes calls to OpenAI, Anthropic, or Together using our API key",
|
||||
longDescription: `New users can try out Continue for free using a proxy server that securely makes calls to OpenAI, Anthropic, or Together using our API key. If you are ready to set up a model for long-term use or have used all ${FREE_TRIAL_LIMIT_REQUESTS} free uses, you can enter your API key or use a local model.`,
|
||||
icon: "openai.png",
|
||||
tags: [ModelProviderTags.Free],
|
||||
packages: [
|
||||
|
|
|
|||
|
|
@ -107,7 +107,7 @@ function IndexingProgress() {
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="mt-6 flex flex-col">
|
||||
<div className="mt-4 flex flex-col">
|
||||
<div className="mb-0 flex justify-between text-sm">
|
||||
<IndexingProgressTitleText update={update} />
|
||||
{update.status !== "loading" && (
|
||||
|
|
|
|||
|
|
@ -21,16 +21,15 @@ const STATUS_TO_ICON: Record<IndexingProgressUpdate["status"], any> = {
|
|||
};
|
||||
|
||||
function IndexingProgressIndicator({ update }: IndexingProgressIndicatorProps) {
|
||||
const progressPercentage = getProgressPercentage(update.progress);
|
||||
const progressPercentage = getProgressPercentage(update.progress).toFixed(0);
|
||||
const Icon = STATUS_TO_ICON[update.status];
|
||||
const animateIcon = update.status === "indexing";
|
||||
const showProgress = update.status !== "disabled";
|
||||
const showProgress =
|
||||
update.status !== "disabled" && progressPercentage !== "100";
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-1 text-stone-500">
|
||||
{showProgress && (
|
||||
<span className="text-xs">{progressPercentage.toFixed(0)}%</span>
|
||||
)}
|
||||
{showProgress && <span className="text-xs">{progressPercentage}%</span>}
|
||||
|
||||
{Icon && (
|
||||
<div className="flex items-center">
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import MoreHelpRow from "./MoreHelpRow";
|
|||
import IndexingProgress from "./IndexingProgress";
|
||||
import DocsIndexingStatuses from "../../components/indexing/DocsIndexingStatuses";
|
||||
import PageHeader from "../../components/PageHeader";
|
||||
import { useAppDispatch } from "../../redux/hooks";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import { saveCurrentSession } from "../../redux/thunks/session";
|
||||
|
||||
function MorePage() {
|
||||
|
|
@ -21,6 +21,9 @@ function MorePage() {
|
|||
const dispatch = useAppDispatch();
|
||||
const navigate = useNavigate();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const disableIndexing = useAppSelector(
|
||||
(state) => state.config.config.disableIndexing,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="overflow-y-scroll">
|
||||
|
|
@ -34,8 +37,15 @@ function MorePage() {
|
|||
Local embeddings of your codebase
|
||||
</span>
|
||||
</div>
|
||||
<IndexingProgress />
|
||||
{disableIndexing ? (
|
||||
<div className="pb-2 pt-5 text-center font-semibold">
|
||||
Indexing is disabled
|
||||
</div>
|
||||
) : (
|
||||
<IndexingProgress />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col py-5">
|
||||
<DocsIndexingStatuses />
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ export const selectSlashCommands = createSelector(
|
|||
},
|
||||
);
|
||||
|
||||
export const selectContextProviderDescriptions = createSelector(
|
||||
export const selectSubmenuContextProviders = createSelector(
|
||||
[(state: RootState) => state.config.config.contextProviders],
|
||||
(providers) => {
|
||||
return providers?.filter((desc) => desc.type === "submenu") || [];
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@ import {
|
|||
Session,
|
||||
SessionMetadata,
|
||||
ToolCall,
|
||||
ToolCallDelta,
|
||||
ToolCallState,
|
||||
} from "core";
|
||||
import { NEW_SESSION_TITLE } from "core/util/constants";
|
||||
import { incrementalParseJson } from "core/util/incrementalParseJson";
|
||||
|
|
@ -283,6 +285,28 @@ export const sessionSlice = createSlice({
|
|||
if (state.history.length) {
|
||||
const lastItem = state.history[state.history.length - 1];
|
||||
const lastMessage = lastItem.message;
|
||||
|
||||
function toolCallDeltaToState(
|
||||
toolCallDelta: ToolCallDelta,
|
||||
): ToolCallState {
|
||||
const [_, parsedArgs] = incrementalParseJson(
|
||||
toolCallDelta.function?.arguments ?? "{}",
|
||||
);
|
||||
return {
|
||||
status: "generating",
|
||||
toolCall: {
|
||||
id: toolCallDelta.id ?? "",
|
||||
type: toolCallDelta.type ?? "function",
|
||||
function: {
|
||||
name: toolCallDelta.function?.name ?? "",
|
||||
arguments: toolCallDelta.function?.arguments ?? "",
|
||||
},
|
||||
},
|
||||
toolCallId: toolCallDelta.id ?? "",
|
||||
parsedArgs,
|
||||
};
|
||||
}
|
||||
|
||||
for (const message of action.payload) {
|
||||
if (
|
||||
message.role &&
|
||||
|
|
@ -301,20 +325,21 @@ export const sessionSlice = createSlice({
|
|||
contextItems: [],
|
||||
};
|
||||
if (message.role === "assistant" && message.toolCalls?.[0]) {
|
||||
const toolCalls = message.toolCalls?.[0];
|
||||
if (toolCalls) {
|
||||
const [_, parsedArgs] = incrementalParseJson(
|
||||
message.toolCalls[0].function?.arguments ?? "{}",
|
||||
);
|
||||
historyItem.toolCallState = {
|
||||
status: "generating",
|
||||
toolCall: message.toolCalls[0] as ToolCall,
|
||||
toolCallId: message.toolCalls[0].id as ToolCall["id"],
|
||||
parsedArgs,
|
||||
};
|
||||
}
|
||||
}
|
||||
const toolCallDelta = message.toolCalls[0];
|
||||
|
||||
if (
|
||||
toolCallDelta.id &&
|
||||
toolCallDelta.function?.arguments &&
|
||||
toolCallDelta.function?.name &&
|
||||
toolCallDelta.type
|
||||
) {
|
||||
console.warn(
|
||||
"Received streamed tool call without required fields",
|
||||
toolCallDelta,
|
||||
);
|
||||
}
|
||||
historyItem.toolCallState = toolCallDeltaToState(toolCallDelta);
|
||||
}
|
||||
state.history.push(historyItem);
|
||||
} else {
|
||||
// Add to the existing message
|
||||
|
|
@ -322,40 +347,39 @@ export const sessionSlice = createSlice({
|
|||
lastMessage.content += renderChatMessage(message);
|
||||
} else if (
|
||||
message.role === "assistant" &&
|
||||
message.toolCalls &&
|
||||
message.toolCalls?.[0] &&
|
||||
lastMessage.role === "assistant"
|
||||
) {
|
||||
if (!lastMessage.toolCalls) {
|
||||
lastMessage.toolCalls = [];
|
||||
// Intentionally only supporting one tool call for now.
|
||||
const toolCallDelta = message.toolCalls[0];
|
||||
|
||||
// Update message tool call with delta data
|
||||
const newArgs =
|
||||
(lastMessage.toolCalls?.[0]?.function?.arguments ?? "") +
|
||||
(toolCallDelta.function?.arguments ?? "");
|
||||
if (lastMessage.toolCalls?.[0]) {
|
||||
lastMessage.toolCalls[0].function = {
|
||||
name:
|
||||
toolCallDelta.function?.name ??
|
||||
lastMessage.toolCalls[0].function?.name ??
|
||||
"",
|
||||
arguments: newArgs,
|
||||
};
|
||||
} else {
|
||||
lastMessage.toolCalls = [toolCallDelta];
|
||||
}
|
||||
message.toolCalls.forEach((toolCall, i) => {
|
||||
if (lastMessage.toolCalls!.length <= i) {
|
||||
lastMessage.toolCalls!.push(toolCall);
|
||||
} else {
|
||||
if (
|
||||
toolCall?.function?.arguments &&
|
||||
lastMessage?.toolCalls?.[i]?.function?.arguments &&
|
||||
lastItem.toolCallState
|
||||
) {
|
||||
lastMessage.toolCalls[i].function!.arguments +=
|
||||
toolCall.function.arguments;
|
||||
|
||||
const [_, parsedArgs] = incrementalParseJson(
|
||||
lastMessage.toolCalls[i].function!.arguments!,
|
||||
);
|
||||
// Update current tool call state
|
||||
if (!lastItem.toolCallState) {
|
||||
console.warn(
|
||||
"Received streamed tool call response prior to initial tool call delta",
|
||||
);
|
||||
lastItem.toolCallState = toolCallDeltaToState(toolCallDelta);
|
||||
}
|
||||
|
||||
lastItem.toolCallState.parsedArgs = parsedArgs;
|
||||
lastItem.toolCallState.toolCall.function.arguments +=
|
||||
toolCall.function.arguments;
|
||||
} else {
|
||||
console.error(
|
||||
"Unexpected tool call format received - this message added during gui strict null checks",
|
||||
message,
|
||||
lastMessage,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
const [_, parsedArgs] = incrementalParseJson(newArgs);
|
||||
lastItem.toolCallState.parsedArgs = parsedArgs;
|
||||
lastItem.toolCallState.toolCall.function.arguments = newArgs;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ const saveSubsetFilters = [
|
|||
// Don't persist any of the edit state for now
|
||||
createFilter("editModeState", []),
|
||||
createFilter("config", ["defaultModelTitle"]),
|
||||
createFilter("ui", ["toolSettings", "useTools"]),
|
||||
];
|
||||
|
||||
const migrations: MigrationManifest = {
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import {
|
|||
} from "../slices/sessionSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
import { callTool } from "./callTool";
|
||||
import { modelSupportsTools } from "core/llm/autodetect";
|
||||
|
||||
export const streamNormalInput = createAsyncThunk<
|
||||
void,
|
||||
|
|
@ -32,17 +33,11 @@ export const streamNormalInput = createAsyncThunk<
|
|||
defaultModel.title,
|
||||
streamAborter.signal,
|
||||
messages,
|
||||
useTools
|
||||
useTools && modelSupportsTools(defaultModel.title, defaultModel.provider)
|
||||
? {
|
||||
tools: Object.keys(toolSettings)
|
||||
.filter((tool) => toolSettings[tool] !== "disabled")
|
||||
.map((toolName) =>
|
||||
state.config.config.tools.find(
|
||||
(tool) => tool.function.name === toolName,
|
||||
),
|
||||
)
|
||||
.filter((tool) => !!tool)
|
||||
.map((tool) => tool!), // for type safety
|
||||
tools: state.config.config.tools.filter(
|
||||
(tool) => toolSettings[tool.function.name] !== "disabled",
|
||||
),
|
||||
}
|
||||
: {},
|
||||
);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue