Merge branch 'dev' into nate/jetbrains-inline-diff-red

This commit is contained in:
Nate Sesti 2024-10-04 17:59:55 -07:00 • committed by GitHub
commit beb11a4f02
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
183 changed files with 4036 additions and 2020 deletions

View file

@ -0,0 +1,7 @@
## 0.0.72 - 2024-10-04
### Added
* Listen for changes to Intellij settings without requiring window reload
### Changed
* Updated tutorial file
### Fixed
* Fix ability to load config.ts in JetBrains IDEs

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Improved loading/accept/reject UI for apply
time: 2024-09-27T14:29:40.283176-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Polished chat sidebar, especially context dropdown
time: 2024-09-27T14:30:05.576347-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Further prompt caching with Anthropic
time: 2024-09-29T09:56:27.946259-07:00

View file

@ -1,4 +0,0 @@
project: extensions/intellij
kind: Changed
body: Updated tutorial file
time: 2024-09-23T16:02:51.918152-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Changed
body: Improved styling on "More" page
time: 2024-09-29T09:54:07.999324-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Fixed
body: Fixed a number of apply bugs
time: 2024-09-27T14:29:24.69568-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Fixed
body: Fixed autoscrolling behavior
time: 2024-09-29T09:55:25.835696-07:00

20
.github/workflows/auto-assign.yaml vendored Normal file
View file

@ -0,0 +1,20 @@
name: Issue assignment
on:
issues:
types: [opened]
pull_request:
types: [opened]
jobs:
auto-assign:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- name: "Auto-assign issue"
uses: pozil/auto-assign-issue@v2
with:
repo-token: ${{ secrets.CI_GITHUB_TOKEN }}
assignees: sestinj,Patrick-Erichsen
numOfAssignee: 1

4
.gitignore vendored
View file

@ -169,4 +169,6 @@ Icon?
.prompts/
.aider*
notes.md
notes.md
manual-testing-sandbox/Continue/.idea/vcs.xml

View file

@ -1,4 +1,4 @@
extensions/vscode/continue_rc_schema.json
**/.continueignore
CHANGELOG.md
**/continue_tutorial.py
**/continue_tutorial.py

19
.prompts/test.prompt Normal file
View file

@ -0,0 +1,19 @@
temperature: 0.5
maxTokens: 4096
name: jest
description: Write Jest unit tests
---
<system>
You are an expert programmer
</system>
{{{ input }}}
Write unit tests for the above selected code, following each of these instructions:
- Use `jest`
- Properly set up and tear down
- Include important edge cases
- The tests should be complete and sophisticated
- Give the tests just as chat output, don't edit any file
- Don't explain how to set up `jest`
- Write a single code block, making sure to label with the language being used (e.g. "```typscript")

2
.vscode/launch.json vendored
View file

@ -12,7 +12,7 @@
"cwd": "${workspaceFolder}/extensions/vscode",
"args": [
// Pass a directory to manually test in
"${workspaceFolder}/gui",
"${workspaceFolder}/manual-testing-sandbox",
"${workspaceFolder}/manual-testing-sandbox/test.js",
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
],

View file

@ -17,9 +17,9 @@
"**/binary": true,
"binary/": false,
"**/core/vendor/**": true,
"**/gui/dist": true
"**/gui/dist": true,
"**/extensions/vscode/gui/**": true,
"**/extensions/vscode/out/**": true
},
"eslint.workingDirectories": [
"./core"
]
"eslint.workingDirectories": ["./core"]
}

View file

@ -68,12 +68,18 @@ You can run the documentation server locally using either of the following metho
#### Method 1: NPM Script
1. Open your terminal and navigate to the root directory of the project.
1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see there is a sign you're in the right place.
2. Run the following command to start the documentation server:
2. Run the following command to install the necessary dependencies for the documentation server:
```bash
npm run start --prefix docs
npm install
```
3. Run the following command to start the documentation server:
```bash
npm run start
```
#### Method 2: VS Code Task

View file

@ -54,7 +54,7 @@
## Getting Started
Learn about how to install and use Continue in the docs [here](https://continue.dev/docs/getting-started)
Learn about how to install and use Continue in the docs [here](https://continue.dev/docs/getting-started/install)
## Contributing

View file

@ -74,6 +74,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -2,6 +2,8 @@ import Parser from "web-tree-sitter";
import { RangeInFileWithContents } from "../commands/util.js";
import { getParserForFile } from "../util/treeSitter.js";
export type AstPath = Parser.SyntaxNode[];
export async function getAst(
filepath: string,
fileContents: string,
@ -23,7 +25,7 @@ export async function getAst(
export async function getTreePathAtCursor(
ast: Parser.Tree,
cursorIndex: number,
): Promise<Parser.SyntaxNode[] | undefined> {
): Promise<AstPath> {
const path = [ast.rootNode];
while (path[path.length - 1].childCount > 0) {
let foundChild = false;

View file

@ -1,4 +1,4 @@
import { stopAtStopTokens } from "./charStream";
import { stopAtStopTokens } from "./streamTransforms/charStream";
describe("stopAtStopTokens", () => {
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {

View file

@ -22,20 +22,18 @@ import {
} from "../util/parameters.js";
import { Telemetry } from "../util/posthog.js";
import { getRangeInString } from "../util/ranges.js";
import { ImportDefinitionsService } from "./ImportDefinitionsService.js";
import { BracketMatchingService } from "./brackets.js";
import AutocompleteLruCache from "./cache.js";
import {
noFirstCharNewline,
onlyWhitespaceAfterEndOfLine,
stopAtStopTokens,
} from "./charStream.js";
import {
constructAutocompletePrompt,
languageForFilepath,
} from "./constructPrompt.js";
import { isOnlyPunctuationAndWhitespace } from "./filter.js";
import { AutocompleteLanguageInfo } from "./languages.js";
import { postprocessCompletion } from "./postprocessing.js";
import { AutocompleteSnippet } from "./ranking.js";
import { RecentlyEditedRange } from "./recentlyEdited.js";
import { RootPathContextService } from "./services/RootPathContextService.js";
import {
avoidPathLineAndEmptyComments,
noTopLevelKeywordsMidline,
@ -44,15 +42,19 @@ import {
stopAtRepeatingLines,
stopAtSimilarLine,
streamWithNewLines,
} from "./lineStream.js";
import { postprocessCompletion } from "./postprocessing.js";
import { AutocompleteSnippet } from "./ranking.js";
import { RecentlyEditedRange } from "./recentlyEdited.js";
} from "./streamTransforms/lineStream.js";
import { getTemplateForModel } from "./templates.js";
import { GeneratorReuseManager } from "./util.js";
// @prettier-ignore
import Handlebars from "handlebars";
import { getConfigJsonPath } from "../util/paths.js";
import { BracketMatchingService } from "./services/BracketMatchingService.js";
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
import {
noFirstCharNewline,
onlyWhitespaceAfterEndOfLine,
stopAtStopTokens,
} from "./streamTransforms/charStream.js";
export interface AutocompleteInput {
completionId: string;
@ -158,9 +160,14 @@ export class CompletionProvider {
this.onError.bind(this),
);
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
this.rootPathContextService = new RootPathContextService(
this.importDefinitionsService,
this.ide,
);
}
private importDefinitionsService: ImportDefinitionsService;
private rootPathContextService: RootPathContextService;
private generatorReuseManager: GeneratorReuseManager;
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = new Set();
@ -542,6 +549,7 @@ export class CompletionProvider {
llm.model,
extrasSnippets,
this.importDefinitionsService,
this.rootPathContextService,
);
// If prefix is manually passed

View file

@ -1,4 +1,3 @@
import Parser from "web-tree-sitter";
import { RangeInFileWithContents } from "../commands/util.js";
import { TabAutocompleteOptions } from "../index.js";
@ -7,8 +6,7 @@ import {
pruneLinesFromBottom,
pruneLinesFromTop,
} from "../llm/countTokens.js";
import { ImportDefinitionsService } from "./ImportDefinitionsService.js";
import { getAst, getTreePathAtCursor } from "./ast.js";
import { AstPath, getAst, getTreePathAtCursor } from "./ast.js";
import {
AutocompleteLanguageInfo,
LANGUAGES,
@ -22,6 +20,8 @@ import {
type AutocompleteSnippet,
} from "./ranking.js";
import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js";
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
import { RootPathContextService } from "./services/RootPathContextService.js";
export function languageForFilepath(
filepath: string,
@ -32,7 +32,7 @@ export function languageForFilepath(
const BLOCK_TYPES = ["body", "statement_block"];
function shouldCompleteMultilineAst(
treePath: Parser.SyntaxNode[],
treePath: AstPath,
cursorLine: number,
): boolean {
// If at the base of the file, do multiline
@ -63,7 +63,7 @@ function isMidlineCompletion(prefix: string, suffix: string): boolean {
}
async function shouldCompleteMultiline(
filepath: string,
treePath: AstPath | undefined,
fullPrefix: string,
fullSuffix: string,
language: AutocompleteLanguageInfo,
@ -94,18 +94,6 @@ async function shouldCompleteMultiline(
}
// Use AST to determine whether to complete multiline
let treePath: Parser.SyntaxNode[] | undefined;
try {
const ast = await getAst(filepath, fullPrefix + fullSuffix);
if (!ast) {
return true;
}
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
} catch (e) {
console.error("Failed to parse AST", e);
}
let completeMultiline = false;
if (treePath) {
const cursorLine = fullPrefix.split("\n").length - 1;
@ -127,6 +115,7 @@ export async function constructAutocompletePrompt(
modelName: string,
extraSnippets: AutocompleteSnippet[],
importDefinitionsService: ImportDefinitionsService,
rootPathContextService: RootPathContextService,
): Promise<{
prefix: string;
suffix: string;
@ -145,6 +134,17 @@ export async function constructAutocompletePrompt(
);
const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
// Calculate AST Path
let treePath: AstPath | undefined;
try {
const ast = await getAst(filepath, fullPrefix + fullSuffix);
if (ast) {
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
}
} catch (e) {
console.error("Failed to parse AST", e);
}
// Find external snippets
let snippets: AutocompleteSnippet[] = [];
@ -215,6 +215,14 @@ export async function constructAutocompletePrompt(
snippets.push(...importSnippets);
}
if (options.useRootPathContext && treePath) {
const ctx = await rootPathContextService.getContextForPath(
filepath,
treePath,
);
snippets.push(...ctx);
}
// Filter out empty snippets and ones that are already in the prefix/suffix
snippets = snippets
.map((snippet) => ({ ...snippet }))
@ -269,7 +277,7 @@ export async function constructAutocompletePrompt(
suffix,
useFim: true,
completeMultiline: await shouldCompleteMultiline(
filepath,
treePath,
fullPrefix,
fullSuffix,
language,

View file

@ -1,4 +1,4 @@
import type { LineFilter } from "./lineStream.js";
import { LineFilter } from "./streamTransforms/lineStream";
export interface AutocompleteLanguageInfo {
name: string;
@ -26,7 +26,7 @@ export const Python = {
name: "Python",
// """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks.
// This stops the model from trying to complete the start of a new markdown block
topLevelKeywords: ["def", "class", "\"\"\"#"],
topLevelKeywords: ["def", "class", '"""#'],
singleLineComment: "#",
endOfLine: [],
};

View file

@ -1,5 +1,5 @@
import { jest } from "@jest/globals";
import * as lineStream from "./lineStream";
import * as lineStream from "./streamTransforms/lineStream";
describe("lineStream", () => {
let mockFullStop: jest.Mock;

View file

@ -1,6 +1,6 @@
import type { ILLM } from "../index.js";
import { longestCommonSubsequence } from "../util/lcs.js";
import { lineIsRepeated } from "./lineStream.js";
import { lineIsRepeated } from "./streamTransforms/lineStream.js";
function rewritesLineAbove(completion: string, prefix: string): boolean {
const lineAbove = prefix

View file

@ -80,7 +80,7 @@ export function deduplicateSnippets(
function mergeSnippetsByRange(
snippets: Required<AutocompleteSnippet>[],
): Required<AutocompleteSnippet>[] {
if (snippets.length === 0) {
if (snippets.length <= 1) {
return snippets;
}

View file

@ -1,11 +1,11 @@
import { IDE } from "../index.js";
import { RangeInFileWithContents } from "../commands/util.js";
import { PrecalculatedLruCache } from "../util/LruCache.js";
import { IDE } from "../..";
import { RangeInFileWithContents } from "../../commands/util";
import { PrecalculatedLruCache } from "../../util/LruCache";
import {
TSQueryType,
getParserForFile,
getQueryForFile,
} from "../util/treeSitter.js";
} from "../../util/treeSitter";
interface FileInfo {
imports: { [key: string]: RangeInFileWithContents[] };

View file

@ -0,0 +1,45 @@
import { IDE, Location } from "../..";
import { LANGUAGES } from "../languages";
import { getSymbolsForSnippet } from "../ranking";
interface FileInfo {
filepath: string;
}
export class NearbyDefinitionsService {
static N = 10;
constructor(private readonly ide: IDE) {}
async getDefinitionsForLine(filepath: string, line: number) {
const lineContent = await this.ide.readRangeInFile(filepath, {
start: {
line,
character: 0,
},
end: {
line: line + 1,
character: 0,
},
});
// Remove keywords
const lang = LANGUAGES[filepath.split(".").slice(-1)[0]];
const symbols = Array.from(getSymbolsForSnippet(lineContent))
.filter((s) => s.length > 0)
.filter((s) => !(lang && lang?.stopWords?.includes(s)));
return Promise.all(
symbols.map((s) => {
const character = lineContent.indexOf(s);
const pos: Location = {
filepath,
position: {
line,
character,
},
};
}),
);
}
}

View file

@ -0,0 +1,129 @@
import { createHash } from "crypto";
import { LRUCache } from "lru-cache";
import Parser from "web-tree-sitter";
import { IDE } from "../..";
import { getQueryForFile, TSQueryType } from "../../util/treeSitter";
import { AstPath } from "../ast";
import { AutocompleteSnippet } from "../ranking";
import { ImportDefinitionsService } from "./ImportDefinitionsService";
export class RootPathContextService {
private cache = new LRUCache<string, AutocompleteSnippet[]>({
max: 100,
});
constructor(
private readonly importDefinitionsService: ImportDefinitionsService,
private readonly ide: IDE,
) {}
private static getNodeId(node: Parser.SyntaxNode): string {
return `${node.startIndex}`;
}
private static TYPES_TO_USE = new Set([
"program",
"function_declaration",
"method_definition",
]);
/**
* Key comes from hash of parent key and node type and node id.
*/
private static keyFromNode(
parentKey: string,
astNode: Parser.SyntaxNode,
): string {
return createHash("sha256")
.update(parentKey)
.update(astNode.type)
.update(RootPathContextService.getNodeId(astNode))
.digest("hex");
}
private async getSnippetsForNode(
filepath: string,
node: Parser.SyntaxNode,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
let query: Parser.Query | undefined;
switch (node.type) {
case "program":
this.importDefinitionsService.get(filepath);
break;
case "function_declaration":
query = await getQueryForFile(
filepath,
TSQueryType.FunctionDeclaration,
);
break;
case "method_definition":
query = await getQueryForFile(filepath, TSQueryType.MethodDefinition);
break;
case "function_definition":
query = await getQueryForFile(filepath, TSQueryType.FunctionDefinition);
break;
case "method_declaration":
query = await getQueryForFile(filepath, TSQueryType.MethodDeclaration);
break;
default:
break;
}
if (!query) {
return snippets;
}
await Promise.all(
query.matches(node).map(async (match) => {
const startPosition = match.captures[0].node.startPosition;
const endPosition = match.captures[0].node.endPosition;
const definitions = await this.ide.gotoDefinition({
filepath,
position: {
line: endPosition.row,
character: endPosition.column,
},
});
const newSnippets = await Promise.all(
definitions.map(async (def) => ({
...def,
contents: await this.ide.readRangeInFile(def.filepath, def.range),
})),
);
snippets.push(...newSnippets);
}),
);
return snippets;
}
async getContextForPath(
filepath: string,
astPath: AstPath,
// cursorIndex: number,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
let parentKey = filepath;
for (const astNode of astPath.filter((node) =>
RootPathContextService.TYPES_TO_USE.has(node.type),
)) {
const key = RootPathContextService.keyFromNode(parentKey, astNode);
const foundInCache = this.cache.get(key);
const newSnippets =
foundInCache ?? (await this.getSnippetsForNode(filepath, astNode));
snippets.push(...newSnippets);
if (!foundInCache) {
this.cache.set(key, newSnippets);
}
parentKey = key;
}
return snippets;
}
}

View file

@ -1,6 +1,6 @@
import { distance } from "fastest-levenshtein";
import { DiffLine } from "../";
import { LineStream } from "../diff/util";
import { DiffLine } from "../..";
import { LineStream } from "../../diff/util";
export type LineFilter = (args: {
lines: LineStream;

View file

@ -1,3 +1,4 @@
import { ContextItemWithId, ILLM, SlashCommand } from "../../";
import {
filterCodeBlockLines,
filterEnglishLinesAtEnd,
@ -5,16 +6,15 @@ import {
fixCodeLlamaFirstLineIndentation,
stopAtLines,
streamWithNewLines,
} from "../../autocomplete/lineStream";
} from "../../autocomplete/streamTransforms/lineStream";
import { streamLines } from "../../diff/util";
import { ContextItemWithId, ILLM, SlashCommand } from "../../";
import { stripImages } from "../../llm/images";
import {
dedentAndGetCommonWhitespace,
getMarkdownLanguageTagForFile,
} from "../../util/";
import {
contextItemToRangeInFileWithContents,
ctxItemToRifWithContents,
type RangeInFileWithContents,
} from "../util";
@ -250,7 +250,7 @@ const EditSlashCommand: SlashCommand = {
}
const rif: RangeInFileWithContents =
contextItemToRangeInFileWithContents(contextItemToEdit);
ctxItemToRifWithContents(contextItemToEdit);
await ide.saveFile(rif.filepath);
const fullFileContents = await ide.readFile(rif.filepath);

View file

@ -9,20 +9,29 @@ export interface RangeInFileWithContents {
contents: string;
}
export function contextItemToRangeInFileWithContents(
export function ctxItemToRifWithContents(
item: ContextItemWithId,
): RangeInFileWithContents {
const lines = item.name.split("(")[1].split(")")[0].split("-");
let startLine = 0;
let endLine = 0;
const nameSplit = item.name.split("(");
if (nameSplit.length > 1) {
const lines = nameSplit[1].split(")")[0].split("-");
startLine = Number.parseInt(lines[0], 10);
endLine = Number.parseInt(lines[1], 10);
}
const rif: RangeInFileWithContents = {
filepath: item.uri?.value || "",
range: {
start: {
line: Number.parseInt(lines[0]),
line: startLine,
character: 0,
},
end: {
line: Number.parseInt(lines[1]),
line: endLine,
character: 0,
},
},

View file

@ -595,7 +595,24 @@ async function loadFullConfigNode(
try {
// Try config.ts first
const configJsPath = getConfigJsPath();
const module = await import(configJsPath);
let module: any;
try {
module = await import(configJsPath);
} catch (e) {
console.log(e);
console.log(
"Could not load config.ts as absolute path, retrying as file url ...",
);
try {
module = await import(`file://${configJsPath}`);
} catch (e) {
throw new Error("Could not load config.ts as file url either", {
cause: e,
});
}
}
if (typeof require !== "undefined") {
delete require.cache[require.resolve(configJsPath)];
}

View file

@ -47,6 +47,7 @@ declare global {
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
engine?: string;
apiVersion?: string;
@ -313,6 +314,7 @@ declare global {
apiKey?: string;
aiGatewaySlug?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
useLegacyCompletionsEndpoint?: boolean;
@ -341,8 +343,6 @@ declare global {
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
cacheSystemMessage?: boolean;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -547,7 +547,8 @@ declare global {
| "docs"
| "gitlab-mr"
| "os"
| "currentFile";
| "currentFile"
| "greptile;
type TemplateType =
| "llama2"
@ -687,6 +688,11 @@ declare global {
clientCertificate?: ClientCertificateOptions;
}
export interface CacheBehavior {
cacheSystemMessage?: boolean;
cacheConversation?: boolean;
}
export interface ClientCertificateOptions {
cert: string;
key: string;
@ -749,6 +755,7 @@ declare global {
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
capabilities?: ModelCapability;
cacheBehavior?: CacheBehavior;
}
export type EmbeddingsProviderName =

View file

@ -29,7 +29,7 @@ export function addContextProvider(provider: ContextProviderWithParams) {
});
}
export function addModel(model: ModelDescription) {
export function addModel(model: ModelDescription, role?: keyof ModelRoles) {
editConfigJson((config) => {
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {
return config;
@ -39,6 +39,18 @@ export function addModel(model: ModelDescription) {
}
config.models.push(model);
// Set the role for the model
if (role) {
if (!config.experimental) {
config.experimental = {};
}
if (!config.experimental.modelRoles) {
config.experimental.modelRoles = {};
}
config.experimental.modelRoles[role] = model.title;
}
return config;
});
}

View file

@ -4,14 +4,14 @@ import {
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
import { walkDir } from "../../indexing/walkDir.js";
} from "../../";
import { walkDir } from "../../indexing/walkDir";
import {
getBasename,
getUniqueFilePath,
groupByLastNPathParts,
} from "../../util/index.js";
import { BaseContextProvider } from "../index.js";
} from "../../util/";
import { BaseContextProvider } from "../";
const MAX_SUBMENU_ITEMS = 10_000;

View file

@ -0,0 +1,186 @@
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
import { execSync } from "child_process";
import * as path from "path";
import * as fs from "fs";
class GreptileContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "greptile",
displayTitle: "Greptile",
description: "Insert query to Greptile",
type: "query",
};
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const greptileToken = this.getGreptileToken();
if (!greptileToken) {
throw new Error("Greptile token not found.");
}
const githubToken = this.getGithubToken();
if (!githubToken) {
throw new Error("GitHub token not found.");
}
let absPath = await this.getWorkspaceDir(extras);
if (!absPath) {
throw new Error("Failed to determine the workspace directory.");
}
var remoteUrl = getRemoteUrl(absPath)
remoteUrl = getRemoteUrl(absPath);
const repoName = extractRepoName(remoteUrl);
const branch = getCurrentBranch(absPath);
const remoteType = getRemoteType(remoteUrl);
if (!remoteType) {
throw new Error("Unable to determine remote type.");
}
const options = {
method: 'POST',
headers: {
Authorization: `Bearer ${greptileToken}`,
'X-GitHub-Token': githubToken,
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: [{ id: "<string>", content: query, role: "user" }],
repositories: [{
remote: remoteType,
branch: branch,
repository: repoName
}],
sessionId: extras.config.userToken || "default-session",
stream: false,
genius: true,
}),
};
try {
const response = await extras.fetch('https://api.greptile.com/v2/query', options);
const rawText = await response.text();
// Check for HTTP errors
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Parse the response as JSON
const json = JSON.parse(rawText);
return json.sources.map((source: any) => ({
description: source.filepath,
content: `File: ${source.filepath}\nLines: ${source.linestart}-${source.lineend}\n\n${source.summary}`,
name: (source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "",
}));
} catch (error) {
console.error("Error getting context items from Greptile:", error);
throw new Error(`Error getting context items from Greptile`);
}
}
private getGreptileToken(): string | undefined {
return this.options.GreptileToken || process.env.GREPTILE_AUTH_TOKEN;
}
private getGithubToken(): string | undefined {
return this.options.GithubToken || process.env.GITHUB_TOKEN;
}
private async getWorkspaceDir(extras: ContextProviderExtras): Promise<string | null> {
try {
const workspaceDirs = await extras.ide.getWorkspaceDirs();
if (workspaceDirs && workspaceDirs.length > 0) {
return workspaceDirs[0];
} else {
console.warn(`extras.ide.getWorkspaceDirs() returned undefined or empty array.`);
}
} catch (err) {
console.warn(`Failed to get workspace directories from extras.ide.getWorkspaceDirs():`);
}
// Fallback to using Git commands
try {
const currentDir = process.cwd();
if (this.isGitRepository(currentDir)) {
const workspaceDir = execSync('git rev-parse --show-toplevel').toString().trim();
return workspaceDir;
} else {
console.warn(`Current directory is not a Git repository: ${currentDir}`);
return null;
}
} catch (err) {
console.warn(`Failed to get workspace directory using Git commands: `);
return null;
}
}
private isGitRepository(dir: string): boolean {
try {
const gitDir = path.join(dir, '.git');
return fs.existsSync(gitDir);
} catch (err) {
console.warn(`Failed to check if directory is a Git repository:`);
return false;
}
}
}
// Helper functions
function getRemoteUrl(absPath: string): string {
try {
const remote = execSync(`git -C ${absPath} remote get-url origin`).toString().trim();
return remote;
} catch (err) {
console.warn(`Failed to get remote URL`);
return "";
}
}
function getCurrentBranch(absPath: string): string {
try {
const branch = execSync(`git -C ${absPath} rev-parse --abbrev-ref HEAD`).toString().trim();
return branch;
} catch (err) {
console.warn(`Failed to get current branch`);
return "master"; // Default to 'master' if the current branch cannot be determined
}
}
function extractRepoName(remote: string): string {
if (remote.startsWith("http://") || remote.startsWith("https://")) {
const parts = remote.split("/");
if (parts.length >= 2) {
return parts[parts.length - 2] + "/" + parts[parts.length - 1].replace(".git", "");
}
} else if (remote.startsWith("git@")) {
const parts = remote.split(":");
if (parts.length >= 2) {
return parts[1].replace(".git", "");
}
}
return "";
}
function getRemoteType(remote: string): string {
if (remote.includes("github.com")) {
return "github";
} else if (remote.includes("gitlab.com")) {
return "gitlab";
} else if (remote.includes("azure.com")) {
return "azure";
}
return "";
}
export default GreptileContextProvider;

View file

@ -22,6 +22,7 @@ import SearchContextProvider from "./SearchContextProvider";
import TerminalContextProvider from "./TerminalContextProvider";
import URLContextProvider from "./URLContextProvider";
import RepoMapContextProvider from "./RepoMapContextProvider";
import GreptileContextProvider from "./GreptileContextProvider";
/**
* Note: We are currently omitting the following providers due to bugs:
@ -53,6 +54,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
URLContextProvider,
ContinueProxyContextProvider,
RepoMapContextProvider,
GreptileContextProvider,
];
export function contextProviderClassFromName(

View file

@ -1,12 +1,13 @@
import path from "path";
import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider";
import { resolveRelativePathInWorkspace } from "../../util/ideUtils";
import { getRelativePath } from "../../util/";
import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils";
import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline";
import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline";
import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline";
import path from "path";
const DEFAULT_N_FINAL = 25;
export async function retrieveContextItemsFromEmbeddings(
extras: ContextProviderExtras,
@ -43,7 +44,8 @@ export async function retrieveContextItemsFromEmbeddings(
const contextLength = extras.llm.contextLength;
const tokensPerSnippet = 512;
const nFinal =
options?.nFinal ?? Math.min(50, contextLength / tokensPerSnippet / 2);
options?.nFinal ??
Math.min(DEFAULT_N_FINAL, contextLength / tokensPerSnippet / 2);
const useReranking = !!extras.reranker;
const nRetrieve = useReranking ? options?.nRetrieve || 2 * nFinal : nFinal;

View file

@ -21,7 +21,8 @@ export interface ControlPlaneModelDescription extends ModelDescription {}
export const DEFAULT_CONTROL_PLANE_PROXY_URL =
process.env.CONTROL_PLANE_ENV === "local"
? "http://localhost:3001/"
: "https://control-plane-proxy.continue.dev/";
: "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/";
// : "https://control-plane-proxy.continue.dev/";
export const CONTROL_PLANE_URL =
process.env.CONTROL_PLANE_ENV === "local"

View file

@ -226,7 +226,7 @@ export class Core {
// Edit config
on("config/addModel", (msg) => {
const model = msg.data.model;
addModel(model);
addModel(model, msg.data.role);
void this.configHandler.reloadConfig();
});

View file

@ -154,4 +154,8 @@ describe("deterministicApplyLazyEdit(", () => {
test("no lazy blocks in single top level class", async () => {
await expectDiff("no-lazy-single-class.js");
});
test("should acknowledge jsx_expression lazy comments", async () => {
await expectDiff("migration-page.tsx");
});
});

View file

@ -135,10 +135,10 @@ export async function deterministicApplyLazyEdit(
}
}
const acc: AstReplacements = [];
findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, acc);
const replacements: AstReplacements = [];
findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements);
const newFullFile = reconstructNewFile(oldFile, newLazyFile, acc);
const newFullFile = reconstructNewFile(oldFile, newLazyFile, replacements);
const diff = myersDiff(oldFile, newFullFile);
// If the diff is too messy and seems likely borked, we fall back to LLM strategy
@ -155,9 +155,27 @@ export function isLazyLine(text: string): boolean {
}
function isLazyBlock(node: Parser.SyntaxNode): boolean {
// Special case for "{/* ... existing code ... */}"
if (
node.type === "jsx_expression" &&
node.namedChildCount === 1 &&
isLazyBlock(node.namedChildren[0])
) {
return true;
}
return node.type.includes("comment") && isLazyLine(node.text);
}
function stringsWithinLevDistThreshold(
a: string,
b: string,
threshold: number,
) {
const dist = distance(a, b);
return dist / Math.min(a.length, b.length) <= threshold;
}
/**
* Determine whether two nodes are similar
* @param a
@ -184,11 +202,23 @@ function nodesAreSimilar(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean {
return true;
}
// Matching jsx_elements needs to be different because they have such a minimal first line
if (
a.type === "jsx_element" &&
b.type === "jsx_element" &&
// Check that the tag names match
a.namedChildren[0]?.children[1]?.text ===
b.namedChildren[0]?.children[1]?.text
) {
if (stringsWithinLevDistThreshold(a.text, b.text, 0.3)) {
return true;
}
}
const lineOneA = a.text.split("\n")[0];
const lineOneB = b.text.split("\n")[0];
const levDist = distance(lineOneA, lineOneB);
return levDist / Math.min(lineOneA.length, lineOneB.length) <= 0.2;
return stringsWithinLevDistThreshold(lineOneA, lineOneB, 0.2);
}
function nodesAreExact(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean {
@ -204,7 +234,7 @@ function nodesAreExact(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean {
function findLazyBlockReplacements(
oldNode: Parser.SyntaxNode,
newNode: Parser.SyntaxNode,
acc: AstReplacements,
replacements: AstReplacements,
): void {
// Base case
if (nodesAreExact(oldNode, newNode)) {
@ -254,7 +284,7 @@ function findLazyBlockReplacements(
}
// then recurse at the match
findLazyBlockReplacements(L, rightChildren[0], acc);
findLazyBlockReplacements(L, rightChildren[0], replacements);
// then consume L and R
leftChildren.shift();
@ -263,7 +293,7 @@ function findLazyBlockReplacements(
// Exit "lazy mode"
if (isLazy) {
// Record the replacement lines
acc.push({
replacements.push({
nodeToReplace: currentLazyBlockNode!,
replacementNodes: [...currentLazyBlockReplacementNodes],
});
@ -275,7 +305,7 @@ function findLazyBlockReplacements(
}
if (isLazy) {
acc.push({
replacements.push({
nodeToReplace: currentLazyBlockNode!,
replacementNodes: [...currentLazyBlockReplacementNodes, ...leftChildren],
});
@ -284,7 +314,7 @@ function findLazyBlockReplacements(
// Cut out any extraneous lazy blocks
for (const R of rightChildren) {
if (isLazyBlock(R)) {
acc.push({
replacements.push({
nodeToReplace: R,
replacementNodes: [],
});

View file

@ -2,7 +2,7 @@ import { ILLM } from "../..";
import {
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/lineStream";
} from "../../autocomplete/streamTransforms/lineStream";
import { streamLines } from "../../diff/util";
import { dedent } from "../../util";

View file

@ -2,7 +2,7 @@ import {
filterLeadingAndTrailingNewLineInsertion,
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/lineStream.js";
} from "../../autocomplete/streamTransforms/lineStream";
import { streamDiff } from "../../diff/streamDiff.js";
import { LineStream, streamLines } from "../../diff/util.js";
import { DiffLine, ILLM } from "../../index.js";

View file

@ -0,0 +1,166 @@
import { useNavigate } from "react-router-dom";
import ContinueButton from "../components/mainInput/ContinueButton";
function MigrationPage() {
const navigate = useNavigate();
return (
<div className="p-8">
<h1>
Migration to <code>config.json</code>
</h1>
<p>
Continue now uses a .json config file. We hope that this takes the
guesswork out of setting up.
</p>
<p>
Your configuration should have been automatically migrated, but we
recommend double-checking that everything looks correct.
</p>
<p>
For a summary of what changed and examples of <code>config.json</code>,
please see the{" "}
<a
href="https://docs.continue.dev/walkthroughs/config-file-migration"
target="_blank"
>
migration walkthrough
</a>
, and if you have any questions please reach out to us on{" "}
<a href="https://discord.gg/Y83xkG3uUW" target="_blank">
Discord
</a>
.
</p>
<i>
Note: If you are running the server manually and have not updated the
server, this message does not apply.
</i>
<ContinueButton
showStop={false}
onClick={() => {
navigate("/");
}}
disabled={false}
/>
</div>
);
}
export default MigrationPage;
---
import { useNavigate } from "react-router-dom";
import ContinueButton from "../components/mainInput/ContinueButton";
function MigrationPage() {
const navigate = useNavigate();
return (
<div className="p-8">
<h1>
Migration to <code>config.json</code>
</h1>
<p className="text-sm">
Continue now uses a .json config file. We hope that this takes the
guesswork out of setting up.
</p>
<p className="text-sm">
Your configuration should have been automatically migrated, but we
recommend double-checking that everything looks correct.
</p>
<p className="text-sm">
For a summary of what changed and examples of <code>config.json</code>,
please see the{" "}
<a
href="https://docs.continue.dev/walkthroughs/config-file-migration"
target="_blank"
>
migration walkthrough
</a>
, and if you have any questions please reach out to us on{" "}
<a href="https://discord.gg/Y83xkG3uUW" target="_blank">
Discord
</a>
.
</p>
<i className="text-sm">
Note: If you are running the server manually and have not updated the
server, this message does not apply.
</i>
{/* ... existing code ... */}
</div>
);
}
export default MigrationPage;
---
import { useNavigate } from "react-router-dom";
import ContinueButton from "../components/mainInput/ContinueButton";
function MigrationPage() {
const navigate = useNavigate();
return (
<div className="p-8">
<h1>
Migration to <code>config.json</code>
</h1>
- <p>
+ <p className="text-sm">
Continue now uses a .json config file. We hope that this takes the
guesswork out of setting up.
</p>
- <p>
+ <p className="text-sm">
Your configuration should have been automatically migrated, but we
recommend double-checking that everything looks correct.
</p>
- <p>
+ <p className="text-sm">
For a summary of what changed and examples of <code>config.json</code>,
please see the{" "}
<a
href="https://docs.continue.dev/walkthroughs/config-file-migration"
target="_blank"
>
migration walkthrough
</a>
, and if you have any questions please reach out to us on{" "}
<a href="https://discord.gg/Y83xkG3uUW" target="_blank">
Discord
</a>
.
</p>
- <i>
+ <i className="text-sm">
Note: If you are running the server manually and have not updated the
server, this message does not apply.
</i>
<ContinueButton
showStop={false}
onClick={() => {
navigate("/");
}}
disabled={false}
/>
</div>
);
}
export default MigrationPage;

View file

@ -5,7 +5,7 @@ import {
filterLeadingAndTrailingNewLineInsertion,
skipLines,
stopAtLines,
} from "../autocomplete/lineStream.js";
} from "../autocomplete/streamTransforms/lineStream.js";
import { streamDiff } from "../diff/streamDiff.js";
import { streamLines } from "../diff/util.js";
import {

12
core/index.d.ts vendored
View file

@ -70,6 +70,7 @@ export interface ILLM extends LLMOptions {
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
engine?: string;
apiVersion?: string;
@ -342,6 +343,7 @@ export interface LLMOptions {
apiKey?: string;
aiGatewaySlug?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
useLegacyCompletionsEndpoint?: boolean;
@ -371,8 +373,6 @@ export interface LLMOptions {
watsonxStopToken?: string;
watsonxApiVersion?: string;
watsonxFullUrl?: string;
cacheSystemMessage?: boolean;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -580,6 +580,7 @@ type ContextProviderName =
| "gitlab-mr"
| "os"
| "currentFile"
| "greptile"
| "outline"
| "continue-proxy"
| "highlights"
@ -729,6 +730,11 @@ export interface RequestOptions {
clientCertificate?: ClientCertificateOptions;
}
export interface CacheBehavior {
cacheSystemMessage?: boolean;
cacheConversation?: boolean;
}
export interface ClientCertificateOptions {
cert: string;
key: string;
@ -791,6 +797,7 @@ export interface ModelDescription {
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
capabilities?: ModelCapability;
cacheBehavior?: CacheBehavior;
}
export type EmbeddingsProviderName =
@ -875,6 +882,7 @@ export interface TabAutocompleteOptions {
recentLinePrefixMatchMinLength: number;
disableInFiles?: string[];
useImports?: boolean;
useRootPathContext?: boolean;
}
export interface ContinueUIConfig {

View file

@ -534,8 +534,12 @@ export default class DocsService {
await table.delete(`title = '${mockRowTitle}'`);
}
private removeInvalidLanceTableNameChars(tableName: string) {
return tableName.replace(/:/g, "");
/**
* From Lance: Table names can only contain alphanumeric characters,
* underscores, hyphens, and periods
*/
private sanitizeLanceTableName(name: string) {
return name.replace(/[^a-zA-Z0-9_.-]/g, "_");
}
private async getLanceTableNameFromEmbeddingsProvider(
@ -544,10 +548,10 @@ export default class DocsService {
const embeddingsProvider = await this.getEmbeddingsProvider(
isPreIndexedDoc,
);
const embeddingsProviderId = this.removeInvalidLanceTableNameChars(
embeddingsProvider.id,
const tableName = this.sanitizeLanceTableName(
`${DocsService.lanceTableName}${embeddingsProvider.id}`,
);
const tableName = `${DocsService.lanceTableName}${embeddingsProviderId}`;
return tableName;
}

View file

@ -68,6 +68,8 @@ export const DEFAULT_IGNORE_FILETYPES = [
"*.uasset",
"*.pdb",
"*.bin",
"*.pag",
"*.swp",
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
];

View file

@ -5,9 +5,10 @@ const SYSTEM_MESSAGE = `When generating new code:
1. Always produce a single code block.
2. Never separate the code into multiple code blocks.
3. Only include the code that is being added.
4. Replace existing code with a "lazy" block like this: "// ... existing code ..."
5. You must always provide 1-2 lines of context above and below a "lazy" block
6. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block.
4. Replace existing code with a "lazy" comment like this: "// ... existing code ..."
5. The "lazy" comment must always be a valid comment in the current context (e.g. "<!-- ... existing code ... -->" for HTML, "// ... existing code ..." for JavaScript, "{/* ... existing code */}" for TSX, etc.)
6. You must always provide 1-2 lines of context above and below a "lazy" comment
7. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block.
Example 1:
Input:

View file

@ -1,6 +1,7 @@
import { findLlmInfo } from "@continuedev/llm-info";
import Handlebars from "handlebars";
import {
CacheBehavior,
ChatMessage,
ChatMessageRole,
CompletionOptions,
@ -102,6 +103,7 @@ export abstract class BaseLLM implements ILLM {
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
engine?: string;
@ -120,8 +122,6 @@ export abstract class BaseLLM implements ILLM {
watsonxApiVersion?: string;
watsonxFullUrl?: string;
cacheSystemMessage?: boolean;
private _llmOptions: LLMOptions;
constructor(_options: LLMOptions) {
@ -184,6 +184,7 @@ export abstract class BaseLLM implements ILLM {
this.apiKey = options.apiKey;
this.aiGatewaySlug = options.aiGatewaySlug;
this.apiBase = options.apiBase;
this.cacheBehavior = options.cacheBehavior;
// for watsonx only
this.watsonxUrl = options.watsonxUrl;
@ -193,8 +194,6 @@ export abstract class BaseLLM implements ILLM {
this.watsonxApiVersion = options.watsonxApiVersion;
this.watsonxFullUrl = options.watsonxFullUrl;
this.cacheSystemMessage = options.cacheSystemMessage;
if (this.apiBase && !this.apiBase.endsWith("/")) {
this.apiBase = `${this.apiBase}/`;
}

View file

@ -35,17 +35,40 @@ class Anthropic extends BaseLLM {
}
private _convertMessages(msgs: ChatMessage[]): any[] {
const messages = msgs
.filter((m) => m.role !== "system")
.map((message) => {
const filteredmessages = msgs.filter((m) => m.role !== "system")
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1).slice(-2);
const messages = filteredmessages.map((message, filteredMsgIdx) => {
// Add cache_control parameter to the last two user messages
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx);
if (typeof message.content === "string") {
return message;
var chatMessage = {
...message,
content: [{
type: "text",
text: message.content,
...(addCaching? { cache_control: { type: "ephemeral" } } : {})
}]
};
return chatMessage;
}
return {
...message,
content: message.content.map((part) => {
content: message.content.map((part, contentIdx) => {
if (part.type === "text") {
return part;
const newpart = {
...part,
// If multiple text parts, only add cache_control to the last one
...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {})
};
return newpart;
}
return {
type: "image",
@ -75,9 +98,7 @@ class Anthropic extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const shouldCacheSystemMessage =
!!this.systemMessage && !!this.cacheSystemMessage;
const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const systemMessage: string = stripImages(
messages.filter((m) => m.role === "system")[0]?.content,
);
@ -89,7 +110,7 @@ class Anthropic extends BaseLLM {
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": this.apiKey as string,
...(shouldCacheSystemMessage
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
? { "anthropic-beta": "prompt-caching-2024-07-31" }
: {}),
},
@ -115,6 +136,7 @@ class Anthropic extends BaseLLM {
}
for await (const value of streamSse(response)) {
if (value.type == "message_start") console.log(value);
if (value.delta?.text) {
yield { role: "assistant", content: value.delta.text };
}

View file

@ -1,8 +1,18 @@
import { ModelProvider } from "../../index.js";
import { LLMOptions, ModelProvider } from "../../index.js";
import OpenAI from "./OpenAI.js";
class Azure extends OpenAI {
static providerName: ModelProvider = "azure";
static defaultOptions: Partial<LLMOptions> = {
apiVersion: "2024-02-15-preview",
apiType: "azure",
};
constructor(options: LLMOptions) {
super(options);
this.engine = options.model;
}
}
export default Azure;

View file

@ -3,6 +3,7 @@ import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
class HuggingFaceTGI extends BaseLLM {
private static MAX_STOP_TOKENS = 4;
static providerName: ModelProvider = "huggingface-tgi";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:8080/",
@ -36,7 +37,10 @@ class HuggingFaceTGI extends BaseLLM {
top_k: options.topK,
presence_penalty: options.presencePenalty,
frequency_penalty: options.frequencyPenalty,
stop: options.stop,
stop: options.stop?.slice(
0,
this.maxStopWords ?? HuggingFaceTGI.MAX_STOP_TOKENS,
),
};
return finalOptions;

View file

@ -15,6 +15,8 @@ class Ollama extends BaseLLM {
model: "codellama-7b",
};
private fimSupported: boolean = false;
constructor(options: LLMOptions) {
super(options);
@ -31,7 +33,7 @@ class Ollama extends BaseLLM {
body: JSON.stringify({ name: this._getModel() }),
})
.then(async (response) => {
if (response.status !== 200) {
if (response?.status !== 200) {
// console.warn(
// "Error calling Ollama /api/show endpoint: ",
// await response.text(),
@ -70,6 +72,13 @@ class Ollama extends BaseLLM {
}
}
}
/**
* There is no API to get the model's FIM capabilities, so we have to
* make an educated guess. If a ".Suffix" variable appears in the template
* it's a good indication the model supports FIM.
*/
this.fimSupported = !!body?.template?.includes(".Suffix");
})
.catch((e) => {
// console.warn("Error calling the Ollama /api/show endpoint: ", e);
@ -251,7 +260,7 @@ class Ollama extends BaseLLM {
}
supportsFim(): boolean {
return true;
return this.fimSupported;
}
protected async *_streamFim(

21
core/package-lock.json generated
View file

@ -39,6 +39,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
@ -1342,6 +1343,15 @@
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
"dev": true,
"dependencies": {
"yallist": "^3.0.2"
}
},
"node_modules/@babel/helper-compilation-targets/node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
@ -10481,12 +10491,11 @@
"integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q=="
},
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
"dev": true,
"dependencies": {
"yallist": "^3.0.2"
"version": "10.2.2",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz",
"integrity": "sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==",
"engines": {
"node": "14 || >=16.14"
}
},
"node_modules/mac-ca": {

View file

@ -69,6 +69,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -1,5 +1,3 @@
import type { AutocompleteInput } from "../autocomplete/completionProvider";
import { ProfileDescription } from "../config/ConfigHandler";
import type {
BrowserSerializedContinueConfig,
ChatMessage,
@ -10,12 +8,15 @@ import type {
LLMFullCompletionOptions,
MessageContent,
ModelDescription,
ModelRoles,
PersistedSessionInfo,
RangeInFile,
SerializedContinueConfig,
SessionInfo,
SiteIndexingConfig,
} from "../";
import type { AutocompleteInput } from "../autocomplete/completionProvider";
import { ProfileDescription } from "../config/ConfigHandler";
export type ProtocolGeneratorType<T> = AsyncGenerator<{
done?: boolean;
@ -50,7 +51,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"devdata/log": [{ tableName: string; data: any }, void];
"config/addOpenAiKey": [string, void];
"config/addModel": [
{ model: SerializedContinueConfig["models"][number] },
{
model: SerializedContinueConfig["models"][number];
role?: keyof ModelRoles;
},
void,
];
"config/newPromptFile": [undefined, void];

View file

@ -97,4 +97,5 @@ export type ToWebviewOrCoreFromIdeProtocol = {
{ sessionInfo: ControlPlaneSessionInfo | undefined },
void,
];
didChangeIdeSettings: [{ settings: IdeSettings }, void];
};

View file

@ -15,7 +15,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
},
];
openUrl: [string, void];
applyToCurrentFile: [{ text: string }, void];
applyToCurrentFile: [{ text: string; streamId: string }, void];
showTutorial: [undefined, void];
showFile: [{ filepath: string }, void];
openConfigJson: [undefined, void];
@ -32,6 +32,11 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
rejectDiff: [{ filepath: string }, void];
};
export interface ApplyState {
streamId: string;
status: "streaming" | "done" | "closed";
}
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setInactive: [undefined, void];
setTTSActive: [boolean, void];
@ -65,4 +70,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
incrementFtc: [undefined, void];
openOnboardingCard: [undefined, void];
applyCodeFromChat: [undefined, void];
updateApplyState: [ApplyState, void];
};

View file

@ -0,0 +1,76 @@
// File generated by Continue
import { dedentAndGetCommonWhitespace } from "../../util";
describe("dedentAndGetCommonWhitespace", () => {
let originalString: string;
beforeEach(() => {
// Setup any global variables or states if needed
originalString = " line1\n line2\n line3";
});
afterEach(() => {
// Tear down any changes to global variables or states if needed
originalString = "";
});
test("should dedent and return common whitespace for a simple case", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", " "]);
});
test("should handle empty string", () => {
const input = "";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["", ""]);
});
test("should handle string with only whitespace", () => {
const input = " ";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["", ""]);
});
test("should handle string with mixed whitespace and content", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([" line1\nline2\n line3", " "]);
});
test("should handle string with no common leading whitespace", () => {
const input = "line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([input, ""]);
});
test("should handle string with empty lines", () => {
const input = " line1\n\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\n\nline3", " "]);
});
test("should handle string with only empty lines", () => {
const input = "\n\n";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["\n\n", ""]);
});
test("should handle string with tabs as whitespace", () => {
const input = "\tline1\n\tline2\n\tline3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", "\t"]);
});
test("should handle string with mixed tabs and spaces", () => {
const input = "\t line1\n\t line2\n\t line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", "\t "]);
});
test("should handle string with different leading whitespace lengths", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([" line1\nline2\n line3", " "]);
});
});

View file

@ -0,0 +1,51 @@
// File generated by Continue
import { getLastNPathParts } from "../../util";
describe("getLastNPathParts", () => {
const SEP_REGEX = /[\\/]+/;
beforeAll(() => {
// Setup code if needed
});
afterAll(() => {
// Teardown code if needed
});
test("returns the last N parts of a filepath with forward slashes", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt");
});
test("returns the last N parts of a filepath with backward slashes", () => {
const filepath = "C:\\home\\user\\documents\\project\\file.txt";
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
});
test("returns the last part if N is 1", () => {
const filepath = "/home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 1)).toBe("file.txt");
});
test("returns the entire path if N is greater than the number of parts", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 10)).toBe(
"home/user/documents/project/file.txt",
);
});
test("returns an empty string if N is 0", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 0)).toBe("");
});
test("handles paths with mixed forward and backward slashes", () => {
const filepath = "home\\user/documents\\project/file.txt";
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
});
test("handles edge case with empty filepath", () => {
const filepath = "";
expect(getLastNPathParts(filepath, 2)).toBe("");
});
});

View file

@ -0,0 +1,40 @@
// This file is generated by Continue
import { longestCommonSubsequence } from "../../util/lcs";
describe("longestCommonSubsequence", () => {
beforeAll(() => {
// Setup if needed
});
afterAll(() => {
// Teardown if needed
});
test("should return the longest common subsequence for non-empty strings", () => {
expect(longestCommonSubsequence("abcde", "ace")).toBe("ace");
expect(longestCommonSubsequence("abc", "abc")).toBe("abc");
expect(longestCommonSubsequence("abc", "def")).toBe("");
});
test("should handle cases where one or both strings are empty", () => {
expect(longestCommonSubsequence("", "abc")).toBe("");
expect(longestCommonSubsequence("abc", "")).toBe("");
expect(longestCommonSubsequence("", "")).toBe("");
});
test("should handle cases with no common subsequence", () => {
expect(longestCommonSubsequence("abc", "def")).toBe("");
expect(longestCommonSubsequence("xyz", "abc")).toBe("");
});
test("should handle cases with special characters", () => {
expect(longestCommonSubsequence("a!@#b$c", "!@#$")).toBe("!@#$");
expect(longestCommonSubsequence("a!@#b$c", "xyz")).toBe("");
});
test("should handle long strings efficiently", () => {
const str1 = "a".repeat(1000) + "b".repeat(1000);
const str2 = "a".repeat(1000) + "c".repeat(1000);
expect(longestCommonSubsequence(str1, str2)).toBe("a".repeat(1000));
});
});

View file

@ -0,0 +1,100 @@
// File generated by Continue
import { mergeJson } from "../../util/merge";
describe("mergeJson", () => {
it("should merge two simple JSON objects", () => {
const first = { a: 1, b: 2 };
const second = { b: 3, c: 4 };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: 3, c: 4 });
});
it('should overwrite values when mergeBehavior is "overwrite"', () => {
const first = { a: 1, b: 2 };
const second = { b: 3, c: 4 };
const result = mergeJson(first, second, "overwrite");
expect(result).toEqual({ a: 1, b: 3, c: 4 });
});
it("should merge nested objects", () => {
const first = { a: { b: 1 } };
const second = { a: { c: 2 } };
const result = mergeJson(first, second);
expect(result).toEqual({ a: { b: 1, c: 2 } });
});
it("should merge arrays without mergeKeys", () => {
const first = { a: [1, 2] };
const second = { a: [3, 4] };
const result = mergeJson(first, second);
expect(result).toEqual({ a: [1, 2, 3, 4] });
});
it("should merge arrays with mergeKeys", () => {
const first = {
a: [
{ id: 1, value: "first" },
{ id: 2, value: "second" },
],
};
const second = {
a: [
{ id: 2, value: "updated" },
{ id: 3, value: "third" },
],
};
const mergeKeys = {
a: (item1: any, item2: any) => item1.id === item2.id,
};
const result = mergeJson(first, second, undefined, mergeKeys);
expect(result).toEqual({
a: [
{ id: 1, value: "first" },
{ id: 2, value: "updated" },
{ id: 3, value: "third" },
],
});
});
it("should handle non-object values correctly", () => {
const first = { a: 1, b: "string", c: true };
const second = { a: 2, b: "new string", c: false };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 2, b: "new string", c: false });
});
it("should handle null and undefined values correctly", () => {
const first = { a: 1, b: null };
const second = { b: 2, c: undefined };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: 2, c: undefined });
});
it("should handle empty objects", () => {
const first = {};
const second = { a: 1 };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1 });
});
it("should handle empty second object", () => {
const first = { a: 1 };
const second = {};
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1 });
});
it("should handle errors gracefully", () => {
const first = { a: 1 };
const second = { b: () => {} }; // Functions are not serializable in JSON
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: expect.any(Function) });
});
it("should merge deeply nested objects", () => {
const first = { a: { b: { c: 1 } } };
const second = { a: { b: { d: 2 } } };
const result = mergeJson(first, second);
expect(result).toEqual({ a: { b: { c: 1, d: 2 } } });
});
});

View file

@ -0,0 +1,105 @@
// This file is generated by Continue
import { getRangeInString } from "../../../util/ranges";
describe.skip("getRangeInString", () => {
let content: string;
beforeEach(() => {
content = `Line 1
Line 2
Line 3
Line 4
Line 5`;
});
afterEach(() => {
content = "";
});
test("should return substring within the same line", () => {
const range = {
start: { line: 1, character: 0 },
end: { line: 1, character: 4 },
};
expect(getRangeInString(content, range)).toBe("Line");
});
test("should return substring spanning multiple lines", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 3, character: 3 },
};
const expected = `ne 2
Line 3
Line 4`;
expect(getRangeInString(content, range)).toBe(expected);
});
test("should handle range that starts and ends at the same character", () => {
const range = {
start: { line: 2, character: 0 },
end: { line: 2, character: 0 },
};
expect(getRangeInString(content, range)).toBe("L");
});
test("should handle range that spans entire content", () => {
const range = {
start: { line: 0, character: 0 },
end: { line: 4, character: 5 },
};
expect(getRangeInString(content, range)).toBe(content);
});
test("should handle range that spans to the end of the last line", () => {
const range = {
start: { line: 3, character: 2 },
end: { line: 4, character: 5 },
};
const expected = `ne 4
Line 5`;
expect(getRangeInString(content, range)).toBe(expected);
});
test("should handle empty content", () => {
content = "";
const range = {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle invalid range (start line > end line)", () => {
const range = {
start: { line: 3, character: 0 },
end: { line: 2, character: 0 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle invalid range (start character > end character on same line)", () => {
const range = {
start: { line: 1, character: 5 },
end: { line: 1, character: 2 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle range that starts and ends at the same line but different characters", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 1, character: 6 },
};
expect(getRangeInString(content, range)).toBe("ne 2");
});
test("should handle range that starts and ends at the same line and same characters", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 1, character: 2 },
};
expect(getRangeInString(content, range)).toBe("n");
});
});

View file

@ -0,0 +1,123 @@
// This file is generated by Continue
import { intersection } from "../../../util/ranges";
interface Position {
line: number;
character: number;
}
interface Range {
start: Position;
end: Position;
}
describe("intersection", () => {
let rangeA: Range;
let rangeB: Range;
beforeEach(() => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 3, character: 5 },
};
rangeB = {
start: { line: 2, character: 2 },
end: { line: 4, character: 0 },
};
});
test("returns correct intersection for overlapping ranges", () => {
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 2 },
end: { line: 3, character: 5 },
});
});
test("returns null for non-overlapping ranges", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 2, character: 0 },
};
rangeB = {
start: { line: 3, character: 0 },
end: { line: 4, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toBeNull();
});
// TODO
test.skip("returns correct intersection for single line overlap", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 5 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 2, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 3 },
end: { line: 1, character: 5 },
});
});
test("returns null for single line non-overlapping ranges", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 2 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 1, character: 5 },
};
const result = intersection(rangeA, rangeB);
expect(result).toBeNull();
});
test("returns correct intersection when one range is fully within another", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 4, character: 5 },
};
rangeB = {
start: { line: 2, character: 2 },
end: { line: 3, character: 3 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 2 },
end: { line: 3, character: 3 },
});
});
test("returns correct intersection when ranges touch at the edge", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 2, character: 0 },
};
rangeB = {
start: { line: 2, character: 0 },
end: { line: 3, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 0 },
end: { line: 2, character: 0 },
});
});
});

View file

@ -0,0 +1,70 @@
import { maxPosition, minPosition } from "../../../util/ranges";
// This file is generated by Continue
interface Position {
line: number;
character: number;
}
describe("Position comparison functions", () => {
let pos1: Position;
let pos2: Position;
let pos3: Position;
let pos4: Position;
beforeAll(() => {
// Setup: Initializing positions
pos1 = { line: 1, character: 5 };
pos2 = { line: 2, character: 3 };
pos3 = { line: 1, character: 7 };
pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality
});
describe("maxPosition", () => {
it("should return the position with the greater line number", () => {
expect(maxPosition(pos1, pos2)).toEqual(pos2);
});
it("should return the position with the greater character number when lines are equal", () => {
expect(maxPosition(pos1, pos3)).toEqual(pos3);
});
it("should return the first position when both positions are equal", () => {
expect(maxPosition(pos2, pos4)).toEqual(pos2);
});
it("should handle positions with negative line numbers", () => {
const posNegative = { line: -1, character: 0 };
expect(maxPosition(posNegative, pos1)).toEqual(pos1);
});
it("should handle positions with negative character numbers", () => {
const posNegativeChar = { line: 1, character: -1 };
expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1);
});
});
describe("minPosition", () => {
it("should return the position with the lesser line number", () => {
expect(minPosition(pos1, pos2)).toEqual(pos1);
});
it("should return the position with the lesser character number when lines are equal", () => {
expect(minPosition(pos1, pos3)).toEqual(pos1);
});
it("should return the first position when both positions are equal", () => {
expect(minPosition(pos2, pos4)).toEqual(pos2);
});
it("should handle positions with negative line numbers", () => {
const posNegative = { line: -1, character: 0 };
expect(minPosition(posNegative, pos1)).toEqual(posNegative);
});
it("should handle positions with negative character numbers", () => {
const posNegativeChar = { line: 1, character: -1 };
expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar);
});
});
});

View file

@ -0,0 +1,92 @@
import { union } from "../../../util/ranges";
// This file is generated by Continue
interface Position {
line: number;
character: number;
}
interface Range {
start: Position;
end: Position;
}
describe("union", () => {
let rangeA: Range;
let rangeB: Range;
beforeEach(() => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 3, character: 5 },
};
rangeB = {
start: { line: 2, character: 3 },
end: { line: 4, character: 2 },
};
});
test("should return the union of two overlapping ranges", () => {
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 4, character: 2 },
});
});
test("should return the union when ranges are identical", () => {
const result = union(rangeA, rangeA);
expect(result).toEqual(rangeA);
});
test("should return the union when ranges do not overlap but are adjacent", () => {
rangeB = {
start: { line: 3, character: 5 },
end: { line: 4, character: 2 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 4, character: 2 },
});
});
test("should return the union when one range is completely within the other", () => {
rangeB = {
start: { line: 2, character: 1 },
end: { line: 2, character: 4 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual(rangeA);
});
test("should return the union when ranges do not overlap and are not adjacent", () => {
rangeB = {
start: { line: 4, character: 3 },
end: { line: 5, character: 1 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 5, character: 1 },
});
});
// TODO
test.skip("should handle edge case where start and end lines are the same", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 5 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 1, character: 7 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 1, character: 7 },
});
});
});

View file

@ -20,6 +20,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
recentLinePrefixMatchMinLength: 7,
disableInFiles: undefined,
useImports: true,
useRootPathContext: true,
};
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;

View file

@ -129,6 +129,11 @@ export async function getLanguageForFile(
export enum TSQueryType {
CodeSnippets = "code-snippet-queries",
Imports = "import-queries",
// Used in RootPathContextService.ts
FunctionDeclaration = "root-path-context-queries/function_declaration",
MethodDefinition = "root-path-context-queries/method_definition",
FunctionDefinition = "root-path-context-queries/function_definition",
MethodDeclaration = "root-path-context-queries/method_declaration",
}
export async function getQueryForFile(

View file

@ -320,7 +320,7 @@ export class NoBadWordsLogitsProcessor extends LogitsProcessor {
* @property {number} [eta_cutoff=0.0] Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
* @property {number} [diversity_penalty=0.0] This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
* @property {number} [repetition_penalty=1.0] The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
* @property {number} [encoder_repetition_penalty=1.0] The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
* @property {number} [encoder_repetition_penalty=1.0] The parameter for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
* @property {number} [length_penalty=1.0] Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.
* @property {number} [no_repeat_ngram_size=0] If set to int > 0, all ngrams of that size can only occur once.
* @property {number[][]} [bad_words_ids=null] List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use `(await tokenizer(bad_words, {add_prefix_space: true, add_special_tokens: false})).input_ids`.
@ -488,7 +488,7 @@ export type GenerationConfigType = {
*/
repetition_penalty?: number;
/**
* The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
* The parameter for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
*/
encoder_repetition_penalty?: number;
/**
@ -590,4 +590,4 @@ export type GenerationConfigType = {
};
import { Tensor } from './tensor.js';
export {};
//# sourceMappingURL=generation.d.ts.map
//# sourceMappingURL=generation.d.ts.map

View file

@ -28,7 +28,7 @@ If there is information from the codebase, documentation, IDE, or other tools th
## Apply generated code to your file
When the LLM replies with code, you can hover over the top right of the code block and select “Apply to current file” to update the existing code in the editor to this new version.
When the LLM replies with edits to a file, you can click the “Apply” button. This will update the existing code in the editor to reflect the suggested changes.
## Start a fresh session for a new task

View file

@ -51,7 +51,7 @@ Indexing will begin upon submission.
To add multiple documentation sites, we recommend adding them in bulk to your `config.json` file. Indexing will kick off upon file save.
The configuration schema is as follows:
The [configuration schema for docs](https://github.com/continuedev/continue/blob/v0.9.212-vscode/extensions/vscode/config_schema.json#L1943-L1973) is as follows:
```json
"docs": [

View file

@ -48,14 +48,17 @@ Anthropic currently does not offer any reranking models.
Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching).
Currently, we only allow caching of the system message. To enable this feature, update your your model configuration with `"cacheSystemMessage": true`:
To enable caching of the system message and the turn-by-turn conversation, update your your model configuration as following:
```json
{
"models": [
{
// Enable prompt caching
"cacheSystemMessage": true,
"cacheBehavior": {
"cacheSystemMessage": true,
"cacheConversation": true
},
"title": "Anthropic",
"provider": "anthropic",
"model": "claude-3-5-sonnet-20240620",

View file

@ -42,7 +42,7 @@ We recommend configuring **Codestral** as your autocomplete model.
We recommend configuring **text-embedding-3-large** as your embeddings model.
```json title="config.json"
"embeddingsProvider": [{
"embeddingsProvider": {
"provider": "azure",
"model": "text-embedding-3-large",
"apiBase": "<YOUR_DEPLOYMENT_BASE>",
@ -50,7 +50,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model.
"apiVersion": "<YOUR_API_VERSION>",
"apiType": "azure",
"apiKey": "<MY_API_KEY>"
}]
}
```
## Reranking model

View file

@ -38,13 +38,11 @@ We recommend configuring **text-embedding-004** as your embeddings model.
```json title="config.json"
{
"embeddingsProvider": [
{
"provider": "gemini",
"model": "models/text-embedding-004",
"apiKey": "[API_KEY]"
}
]
"embeddingsProvider": {
"provider": "gemini",
"model": "models/text-embedding-004",
"apiKey": "[API_KEY]"
}
}
```

View file

@ -46,14 +46,12 @@ We recommend configuring **Mistral Embed** as your embeddings model.
```json title="config.json"
{
"embeddingsProvider": [
{
"provider": "mistral",
"model": "mistral-embed",
"apiKey": "[API_KEY]",
"apiBase": "https://api.mistral.ai/v1"
}
]
"embeddingsProvider": {
"provider": "mistral",
"model": "mistral-embed",
"apiKey": "[API_KEY]",
"apiBase": "https://api.mistral.ai/v1"
}
}
```

View file

@ -38,13 +38,11 @@ We recommend configuring **text-embedding-3-large** as your embeddings model.
```json title="config.json"
{
"embeddingsProvider": [
{
"provider": "openai",
"model": "text-embedding-3-large",
"apiKey": "[API_KEY]"
}
]
"embeddingsProvider": {
"provider": "openai",
"model": "text-embedding-3-large",
"apiKey": "[API_KEY]"
}
}
```

View file

@ -48,7 +48,8 @@ func = get_registry().get("openai").create(
class CodeChunks(LanceModel):
filename: str
text: str = func.SourceField()
vector: Vector(func.ndims()) = func.VectorField()
# 1536 is the embedding dimension of the `voyage-code-2` model.
vector: Vector(1536) = func.VectorField()
table = db.create_table("code_chunks", schema=CodeChunks, mode="overwrite")
table.add([

View file

@ -20,6 +20,6 @@ keywords:
**Continue is the leading open-source AI code assistant inside of [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)**
- [Chat](chat/how-to-use-it.md) to understand and iterate on code in the sidebar
- [Autocomplete](autocomplete/how-to-use-it.md) to recieve inline code suggestions as you type
- [Autocomplete](autocomplete/how-to-use-it.md) to receive inline code suggestions as you type
- [Edit](edit/how-to-use-it.md) to modify code without leaving your current file
- [Actions](actions/how-to-use-it.md) to establish shortcuts for common use cases

View file

@ -5,7 +5,7 @@
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"start": "nodemon --watch sidebars.js --watch docusaurus.config.js --exec 'docusaurus start'",
"start": "nodemon --watch sidebars.js --watch docusaurus.config.js --exec \"docusaurus start\"",
"build": "docusaurus build",
"build:netlify": "docusaurus build --out-dir build/docs",
"swizzle": "docusaurus swizzle",

View file

@ -8,10 +8,6 @@ const sidebars = {
type: "category",
label: "Getting started",
collapsed: false,
link: {
type: "doc",
id: "getting-started/install",
},
items: [
{
type: "autogenerated",
@ -22,10 +18,6 @@ const sidebars = {
{
type: "category",
label: "Chat",
link: {
type: "doc",
id: "chat/how-to-use-it",
},
items: [
{
type: "autogenerated",
@ -36,10 +28,6 @@ const sidebars = {
{
type: "category",
label: "Autocomplete",
link: {
type: "doc",
id: "autocomplete/how-to-use-it",
},
items: [
{
type: "autogenerated",
@ -50,10 +38,6 @@ const sidebars = {
{
type: "category",
label: "Edit",
link: {
type: "doc",
id: "edit/how-to-use-it",
},
items: [
{
type: "autogenerated",
@ -64,10 +48,6 @@ const sidebars = {
{
type: "category",
label: "Actions",
link: {
type: "doc",
id: "actions/how-to-use-it",
},
items: [
{
type: "autogenerated",

View file

@ -699,8 +699,17 @@
},
"then": {
"properties": {
"cacheSystemMessage": {
"type": "boolean"
"cacheBehavior": {
"title": "Caching Behavior",
"description": "Options for the prompt caching",
"properties": {
"cacheSystemMessage": {
"type": "boolean"
},
"cacheConversation": {
"type": "boolean"
}
}
},
"model": {
"anyOf": [
@ -796,8 +805,14 @@
},
"then": {
"properties": {
"cacheSystemMessage": {
"type": "boolean"
"cacheBehavior": {
"title": "Caching Behavior",
"description": "Options for the prompt caching",
"properties": {
"cacheSystemMessage": {
"type": "boolean"
}
}
},
"model": {
"enum": [
@ -1017,8 +1032,17 @@
},
"then": {
"properties": {
"cacheSystemMessage": {
"type": "boolean"
"cacheBehavior": {
"title": "Caching Behavior",
"description": "Options for the prompt caching",
"properties": {
"cacheSystemMessage": {
"type": "boolean"
},
"cacheConversation": {
"type": "boolean"
}
}
},
"model": {
"enum": ["deepseek-chat", "deepseek-coder"]
@ -1528,7 +1552,8 @@
"url",
"database",
"os",
"repo-map"
"repo-map",
"greptile"
],
"markdownEnumDescriptions": [
"Reference the contents of the current changes as given by `git diff`",
@ -1552,7 +1577,8 @@
"Reference the contents of a page at a URL",
"Reference table schemas",
"Operating system and CPU Information",
"Map of files in the repository with important code highlights"
"Map of files in the repository with important code highlights",
"Query your greptile index of the current repo"
],
"type": "string"
},
@ -1930,6 +1956,36 @@
},
"required": ["host", "port", "user", "password", "database"]
}
},
{
"if": {
"properties": {
"name": {
"enum": ["greptile"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"GithubToken": {
"title": "GithubToken",
"description": "Your github access token",
"default": "",
"type": "string"
},
"GreptileToken": {
"title": "GreptileToken",
"description": "Your greptile access token",
"default": "",
"type": "string"
}
}
}
},
"required": ["GreptileToken", "GithubToken"]
}
}
],
"required": ["name"]

View file

@ -5,9 +5,13 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).
Pre-release Changes
## 0.0.72 - 2024-10-04
### Added
* Listen for changes to Intellij settings without requiring window reload
### Changed
* Updated tutorial file
### Fixed
* Fix ability to load config.ts in JetBrains IDEs
## 0.0.69 - 2024-09-22
### Added

View file

@ -1,35 +1,26 @@
# IntelliJ Platform Artifacts Repositories -> https://plugins.jetbrains.com/docs/intellij/intellij-artifacts.html
pluginGroup = com.github.continuedev.continueintellijextension
pluginName = continue-intellij-extension
pluginRepositoryUrl = https://github.com/continuedev/continue
pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion = 0.0.69
pluginVersion=0.0.73
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild = 223
pluginSinceBuild=223
#pluginUntilBuild = 232.*
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
platformType = IC
platformVersion = 2022.3.3
platformType=IC
platformVersion=2022.3.3
#platformVersion = LATEST-EAP-SNAPSHOT
# Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html
# Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22
platformPlugins = org.jetbrains.plugins.terminal
platformPlugins=org.jetbrains.plugins.terminal
# Gradle Releases -> https://github.com/gradle/gradle/releases
gradleVersion = 8.3
gradleVersion=8.3
# Opt-out flag for bundling Kotlin standard library -> https://jb.gg/intellij-platform-kotlin-stdlib
kotlin.stdlib.default.dependency = false
kotlin.stdlib.default.dependency=false
# Enable Gradle Configuration Cache -> https://docs.gradle.org/current/userguide/configuration_cache.html
org.gradle.configuration-cache = true
org.gradle.configuration-cache=true
# Enable Gradle Build Cache -> https://docs.gradle.org/current/userguide/build_cache.html
org.gradle.caching = true
org.gradle.caching=true
# Enable Gradle Kotlin DSL Lazy Property Assignment -> https://docs.gradle.org/current/userguide/kotlin_dsl.html#kotdsl:assignment
systemProp.org.gradle.unsafe.kotlin.assignment = true
systemProp.org.gradle.unsafe.kotlin.assignment=true

View file

@ -141,6 +141,9 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
connection.subscribe(SettingsListener.TOPIC, object : SettingsListener {
override fun settingsUpdated(settings: ContinueExtensionSettings.ContinueState) {
continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", settings, null) { _ -> }
continuePluginService.sendToWebview("didChangeIdeSettings", mapOf(
"settings" to settings
))
}
})

View file

@ -5,10 +5,7 @@ import com.github.continuedev.continueintellijextension.services.ContinueExtensi
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.*
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
@ -93,11 +90,11 @@ class AutocompleteService(private val project: Project) {
val completions = response as List<*>
if (completions.isNotEmpty()) {
val completion = completions[0].toString()
val finalTextToInsert = deduplicateCompletion(editor, offset, completion)
if (completion.isNotEmpty() && (completion.lines().size === 1 || column >= lineLength)) {
// Do not render if completion is multi-line and caret is in middle of line
renderCompletion(editor, offset, completion)
pendingCompletion = pendingCompletion?.copy(text = completion)
if (shouldRenderCompletion(finalTextToInsert, column, lineLength, editor)) {
renderCompletion(editor, offset, finalTextToInsert)
pendingCompletion = pendingCompletion?.copy(text = finalTextToInsert)
// Hide auto-popup
// AutoPopupController.getInstance(project).cancelAllRequests()
@ -106,17 +103,48 @@ class AutocompleteService(private val project: Project) {
}))
}
private fun renderCompletion(editor: Editor, offset: Int, text: String) {
if (text.isEmpty()) {
return
private fun shouldRenderCompletion(completion: String, column: Int, lineLength: Int, editor: Editor): Boolean {
if (completion.isEmpty()) {
return false
}
if (isInjectedFile(editor)) return
// Do not render if completion is multi-line and caret is in middle of line
return !(completion.lines().size > 1 && column < lineLength)
}
private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String {
// Check if completion matches the first 10 characters after the cursor
return ApplicationManager.getApplication().runReadAction<String> {
val document = editor.document
val caretOffset = editor.caretModel.offset
val N = 10
var textAfterCursor = if (caretOffset + N <= document.textLength) {
document.getText(com.intellij.openapi.util.TextRange(caretOffset, caretOffset + N))
} else {
document.getText(com.intellij.openapi.util.TextRange(caretOffset, document.textLength))
}
val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor)
if (indexOfTextAfterCursorInCompletion > 0) {
return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1)
} else if (indexOfTextAfterCursorInCompletion == 0) {
return@runReadAction ""
}
return@runReadAction completion
}
}
private fun renderCompletion(editor: Editor, offset: Int, completion: String) {
if (completion.isEmpty()) {
return
}
if (isInjectedFile(editor)) return
// Don't render completions when code completion dropdown is visible
if (!autocompleteLookupListener.isLookupEmpty()) {
return
}
ApplicationManager.getApplication().invokeLater {
WriteAction.run<Throwable> {
// Clear existing completions
@ -126,10 +154,10 @@ class AutocompleteService(private val project: Project) {
properties.relatesToPrecedingText(true)
properties.disableSoftWrapping(true)
if (text.lines().size > 1) {
editor.inlayModel.addBlockElement(offset, properties, ContinueMultilineCustomElementRenderer(editor, text))
if (completion.lines().size > 1) {
editor.inlayModel.addBlockElement(offset, properties, ContinueMultilineCustomElementRenderer(editor, completion))
} else {
editor.inlayModel.addInlineElement(offset, properties, ContinueCustomElementRenderer(editor, text))
editor.inlayModel.addInlineElement(offset, properties, ContinueCustomElementRenderer(editor, completion))
}
// val attributes = TextAttributes().apply {

View file

@ -1,4 +1,4 @@
package com.github.continuedev.continueintellijextension.toolWindow
package com.github.continuedev.continueintellijextension.constants
class MessageTypes {
companion object {
@ -38,7 +38,6 @@ class MessageTypes {
"getTags",
"getIdeInfo",
"getIdeSettings",
"errorPopup",
"getRepoName",
"listDir",
"getGitRootPath",
@ -50,7 +49,8 @@ class MessageTypes {
"pathSep",
"getControlPlaneSessionInfo",
"logoutOfControlPlane",
"getTerminalContents"
"getTerminalContents",
"showToast",
)
val PASS_THROUGH_TO_WEBVIEW = listOf<String>(

View file

@ -3,7 +3,7 @@ package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.services.TelemetryService
import com.github.continuedev.continueintellijextension.toolWindow.MessageTypes
import com.github.continuedev.continueintellijextension.constants.MessageTypes
import com.google.gson.Gson
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
@ -15,7 +15,13 @@ import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
class CoreMessenger(private val project: Project, esbuildPath: String, continueCorePath: String, ideProtocolClient: IdeProtocolClient, private val coroutineScope: CoroutineScope) {
class CoreMessenger(
private val project: Project,
esbuildPath: String,
continueCorePath: String,
ideProtocolClient: IdeProtocolClient,
private val coroutineScope: CoroutineScope
) {
private var writer: Writer? = null
private var reader: BufferedReader? = null
private var process: Process? = null
@ -42,11 +48,13 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
val id = messageId ?: uuid()
val message = gson.toJson(mapOf(
val message = gson.toJson(
mapOf(
"messageId" to id,
"messageType" to messageType,
"data" to data
))
)
)
responseListeners[id] = onResponse
write(message)
}
@ -60,11 +68,13 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
// IDE listeners
if (MessageTypes.ideMessageTypes.contains(messageType)) {
ideProtocolClient.handleMessage(json) { data ->
val message = gson.toJson(mapOf(
val message = gson.toJson(
mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to data
))
)
)
write(message)
};
}
@ -76,11 +86,13 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
if (messageType == "getDefaultModelTitle") {
val continueSettingsService = service<ContinueExtensionSettings>()
val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel;
val message = gson.toJson(mapOf(
val message = gson.toJson(
mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to defaultModelTitle
))
)
)
write(message)
}
val continuePluginService = project.service<ContinuePluginService>()
@ -94,7 +106,8 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
val done = (data as Map<String, Boolean?>)["done"]
if (done == true) {
responseListeners.remove(messageId)
} else {}
} else {
}
} else {
responseListeners.remove(messageId)
}
@ -106,10 +119,10 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
val osName = System.getProperty("os.name").toLowerCase()
if (osName.contains("mac") || osName.contains("darwin")) {
ProcessBuilder(
"xattr",
"-dr",
"com.apple.quarantine",
destination
"xattr",
"-dr",
"com.apple.quarantine",
destination
).start()
setFilePermissions(destination, "rwxr-xr-x")
} else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) {
@ -177,7 +190,7 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
// Start the subprocess
val processBuilder = ProcessBuilder(continueCorePath)
.directory(File(continueCorePath).parentFile)
.directory(File(continueCorePath).parentFile)
process = processBuilder.start()
val outputStream = process!!.outputStream
@ -200,14 +213,16 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
println("Core process exited with output: $err")
CoroutineScope(Dispatchers.Main).launch {
ideProtocolClient.showMessage("Core process exited with output: $err")
ideProtocolClient.showToast("error", "Core process exited with output: $err")
}
// Log the cause of the failure
val telemetryService = service<TelemetryService>()
telemetryService.capture("jetbrains_core_exit", mapOf(
"error" to err
))
telemetryService.capture(
"jetbrains_core_exit", mapOf(
"error" to err
)
)
// Clean up all resources
writer?.close()

View file

@ -14,6 +14,9 @@ import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
@ -154,8 +157,8 @@ private fun readConfigJson(): Map<String, Any> {
val configJsonPath = getConfigJsonPath()
val reader = FileReader(configJsonPath)
val config: Map<String, Any> = gson.fromJson(
reader,
object : TypeToken<Map<String, Any>>() {}.type
reader,
object : TypeToken<Map<String, Any>>() {}.type
)
reader.close()
return config
@ -167,9 +170,13 @@ class AsyncFileSaveListener : AsyncFileListener {
constructor(ideProtocolClient: IdeProtocolClient) {
this.ideProtocolClient = ideProtocolClient
}
override fun prepareChange(events: MutableList<out VFileEvent>): AsyncFileListener.ChangeApplier? {
for (event in events) {
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(".continue\\config.json") || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json")) {
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(
".continue\\config.json"
) || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json")
) {
return object : AsyncFileListener.ChangeApplier {
override fun afterVfsChange() {
val config = readConfigJson()
@ -183,14 +190,15 @@ class AsyncFileSaveListener : AsyncFileListener {
}
class IdeProtocolClient (
class IdeProtocolClient(
private val continuePluginService: ContinuePluginService,
private val textSelectionStrategy: TextSelectionStrategy,
private val coroutineScope: CoroutineScope,
private val workspacePath: String?,
private val project: Project
): DumbAware {
) : DumbAware {
val diffManager = DiffManager(project)
private val CONTINUE_NOTIFICATION_GROUP = NotificationGroup("Continue", NotificationDisplayType.BALLOON, true)
private val ripgrep: String
init {
@ -202,7 +210,8 @@ class IdeProtocolClient (
})
val myPluginId = "com.github.continuedev.continueintellijextension"
val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found")
val pluginDescriptor =
PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found")
val pluginPath = pluginDescriptor.pluginPath
val osName = System.getProperty("os.name").toLowerCase()
@ -213,7 +222,8 @@ class IdeProtocolClient (
else -> "linux"
}
ripgrep = Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + (if (os == "win32") ".exe" else "")).toString()
ripgrep =
Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + (if (os == "win32") ".exe" else "")).toString()
}
private fun send(messageType: String, data: Any?, messageId: String? = null) {
@ -224,8 +234,8 @@ class IdeProtocolClient (
fun handleMessage(text: String, respond: (Any?) -> Unit) {
coroutineScope.launch(Dispatchers.IO) {
val parsedMessage: Map<String, Any> = Gson().fromJson(
text,
object : TypeToken<Map<String, Any>>() {}.type
text,
object : TypeToken<Map<String, Any>>() {}.type
)
val messageType = parsedMessage["messageType"] as? String
if (messageType == null) {
@ -239,16 +249,20 @@ class IdeProtocolClient (
"uniqueId" -> respond(
mapOf("uniqueId" to uniqueId())
)
"getIdeSettings" -> {
val settings =
ServiceManager.getService(ContinueExtensionSettings::class.java)
respond(mapOf(
"remoteConfigServerUrl" to settings.continueState.remoteConfigServerUrl,
"remoteConfigSyncPeriod" to settings.continueState.remoteConfigSyncPeriod,
"userToken" to settings.continueState.userToken,
"enableControlServerBeta" to settings.continueState.enableContinueTeamsBeta
))
ServiceManager.getService(ContinueExtensionSettings::class.java)
respond(
mapOf(
"remoteConfigServerUrl" to settings.continueState.remoteConfigServerUrl,
"remoteConfigSyncPeriod" to settings.continueState.remoteConfigSyncPeriod,
"userToken" to settings.continueState.userToken,
"enableControlServerBeta" to settings.continueState.enableContinueTeamsBeta
)
)
}
"getControlPlaneSessionInfo" -> {
val silent = (data as? Map<String, Any>)?.get("silent") as? Boolean ?: false
@ -261,12 +275,15 @@ class IdeProtocolClient (
respond(null)
}
}
"logoutOfControlPlane" -> {
val authService = service<ContinueAuthService>()
authService.signOut()
ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC).handleUpdatedSessionInfo(null)
ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC)
.handleUpdatedSessionInfo(null)
respond(null)
}
"getIdeInfo" -> {
val applicationInfo = ApplicationInfo.getInstance()
val ideName: String = applicationInfo.fullApplicationName
@ -283,13 +300,15 @@ class IdeProtocolClient (
val plugin = PluginManagerCore.getPlugin(PluginId.getId(pluginId))
val extensionVersion = plugin?.version ?: "Unknown"
respond(mapOf(
"ideType" to "jetbrains",
"name" to ideName,
"version" to ideVersion,
"remoteName" to remoteName,
"extensionVersion" to extensionVersion
))
respond(
mapOf(
"ideType" to "jetbrains",
"name" to ideName,
"version" to ideVersion,
"remoteName" to remoteName,
"extensionVersion" to extensionVersion
)
)
}
"getUniqueId" -> {
@ -307,9 +326,9 @@ class IdeProtocolClient (
"showDiff" -> {
val data = data as Map<String, Any>
diffManager.showDiff(
data["filepath"] as String,
data["newContents"] as String,
(data["stepIndex"] as Double).toInt()
data["filepath"] as String,
data["newContents"] as String,
(data["stepIndex"] as Double).toInt()
)
respond(null)
}
@ -333,7 +352,8 @@ class IdeProtocolClient (
val endLine = end["line"] as Int
val endCharacter = end["character"] as Int
val firstLine = fullContents.split("\n")[startLine].slice(startCharacter until fullContents.split("\n")[startLine].length)
val firstLine =
fullContents.split("\n")[startLine].slice(startCharacter until fullContents.split("\n")[startLine].length)
val lastLine = fullContents.split("\n")[endLine].slice(0 until endCharacter)
val between = fullContents.split("\n").slice(startLine + 1 until endLine).joinToString("\n")
@ -391,6 +411,7 @@ class IdeProtocolClient (
saveFile((data as Map<String, String>)["filepath"] ?: throw Exception("No filepath provided"))
respond(null)
}
"showVirtualFile" -> {
val data = data as Map<String, Any>
showVirtualFile(
@ -401,15 +422,11 @@ class IdeProtocolClient (
}
"connected" -> {}
"showMessage" -> {
showMessage(data as String)
respond(null)
}
"setFileOpen" -> {
val data = data as Map<String, Any>
setFileOpen(
data["filepath"] as String,
data["open"] as Boolean
data["filepath"] as String,
data["open"] as Boolean
)
respond(null)
}
@ -420,14 +437,14 @@ class IdeProtocolClient (
val startLine = (data["startLine"] as Double).toInt()
val endLine = (data["endLine"] as Double).toInt()
highlightCode(
RangeInFile(
filepath,
Range(
Position(startLine, 0),
Position(endLine, 0)
)
),
data["color"] as String?
RangeInFile(
filepath,
Range(
Position(startLine, 0),
Position(endLine, 0)
)
),
data["color"] as String?
)
respond(null)
}
@ -438,7 +455,7 @@ class IdeProtocolClient (
val json = gson.toJson(data["rangeInFile"])
val type = object : TypeToken<RangeInFile>() {}.type
val rangeInFile =
gson.fromJson<RangeInFile>(json, type)
gson.fromJson<RangeInFile>(json, type)
highlightCode(rangeInFile, data["color"] as String)
respond(null)
}
@ -456,6 +473,7 @@ class IdeProtocolClient (
}.toMap()
respond(pathToLastModified)
}
"listDir" -> {
val data = data as Map<String, Any>
val dir = data["dir"] as String
@ -465,6 +483,7 @@ class IdeProtocolClient (
} ?: emptyList()
respond(files)
}
"getGitRootPath" -> {
val data = data as Map<String, Any>
val directory = data["dir"] as String
@ -478,12 +497,14 @@ class IdeProtocolClient (
respond(output)
}
"getBranch" -> {
// Get the current branch name
val dir = (data as Map<String, Any>)["dir"] as String
val branch = getBranch(dir)
respond(branch)
}
"getRepoName" -> {
// Get the current repository name
val dir = (data as Map<String, Any>)["dir"] as String
@ -522,6 +543,7 @@ class IdeProtocolClient (
respond(output.toString());
}
"getProblems" -> {
// Get currently active editor
var editor: Editor? = null
@ -570,46 +592,58 @@ class IdeProtocolClient (
// }
// respond(problems)
}
"getConfigJsUrl" -> {
// Calculate a data URL for the config.js file
val configJsPath = getConfigJsPath()
val configJsContents = File(configJsPath).readText()
val configJsDataUrl = "data:text/javascript;base64,${Base64.getEncoder().encodeToString(configJsContents.toByteArray())}"
val configJsDataUrl = "data:text/javascript;base64,${
Base64.getEncoder().encodeToString(configJsContents.toByteArray())
}"
respond(configJsDataUrl)
}
"writeFile" -> {
val msg = data as Map<String, String>;
val file = File(msg["path"])
file.writeText(msg["contents"] as String)
respond(null);
}
"fileExists" -> {
val msg = data as Map<String, String>;
val file = File(msg["filepath"])
respond(file.exists())
}
"getContinueDir" -> {
respond(getContinueGlobalPath())
}
"openFile" -> {
setFileOpen((data as Map<String, Any>)["path"] as String)
respond(null)
}
"runCommand" -> {
respond(null)
// Running commands not yet supported in JetBrains
}
"errorPopup" -> {
val data = data as Map<String, Any>
val message = data["message"] as String
showMessage(message)
"showToast" -> {
val data = data as ArrayList<String>
val toast_type = data[0]
val message = data[1]
showToast(toast_type, message)
respond(null)
}
"listFolders" -> {
val workspacePath = workspacePath ?: return@launch
val workspaceDir = File(workspacePath)
val folders = workspaceDir.listFiles { file -> file.isDirectory }?.map { file -> file.absolutePath } ?: emptyList()
val folders =
workspaceDir.listFiles { file -> file.isDirectory }?.map { file -> file.absolutePath }
?: emptyList()
respond(folders)
}
@ -623,16 +657,19 @@ class IdeProtocolClient (
val openFiles = visibleFiles()
respond(openFiles)
}
"getCurrentFile" -> {
val currentFile = currentFile()
respond(currentFile)
}
"getPinnedFiles" -> {
ApplicationManager.getApplication().invokeLater {
val pinnedFiles = pinnedFiles()
respond(pinnedFiles)
}
}
"insertAtCursor" -> {
val msg = data as Map<String, String>;
val text = msg["text"] as String
@ -649,8 +686,10 @@ class IdeProtocolClient (
}
}
}
"applyToFile" -> {
}
"getGitHubAuthToken" -> {
val continueSettingsService = service<ContinueExtensionSettings>()
val ghAuthToken = continueSettingsService.continueState.ghAuthToken;
@ -663,26 +702,30 @@ class IdeProtocolClient (
respond(ghAuthToken)
}
}
"setGitHubAuthToken" -> {
val continueSettingsService = service<ContinueExtensionSettings>()
val data = data as Map<String, String>
continueSettingsService.continueState.ghAuthToken = data["token"]
respond(null)
}
"openUrl" -> {
val url = data as String
java.awt.Desktop.getDesktop().browse(java.net.URI(url))
respond(null)
}
"pathSep" -> {
respond(File.separator)
}
else -> {
println("Unknown messageType: $messageType")
}
}
} catch (error: Exception) {
showMessage("Error handling message of type $messageType: $error")
showToast("error", "Error handling message of type $messageType: $error")
}
}
}
@ -696,8 +739,8 @@ class IdeProtocolClient (
val configJsonPath = getConfigJsonPath()
val reader = FileReader(configJsonPath)
val config: MutableMap<String, Any> = gson.fromJson(
reader,
object : TypeToken<Map<String, Any>>() {}.type
reader,
object : TypeToken<Map<String, Any>>() {}.type
)
reader.close()
@ -818,7 +861,8 @@ class IdeProtocolClient (
val result = ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
// Get the editor instance for the currently active editor window
val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return@runReadAction null
val virtualFile = editor.let { FileDocumentManager.getInstance().getFile(it.document) } ?: return@runReadAction null
val virtualFile =
editor.let { FileDocumentManager.getInstance().getFile(it.document) } ?: return@runReadAction null
// Get the selection range and content
val selectionModel: SelectionModel = editor.selectionModel
@ -838,10 +882,12 @@ class IdeProtocolClient (
val startChar = startOffset - document.getLineStartOffset(startLine)
val endChar = endOffset - document.getLineStartOffset(endLine)
return@runReadAction RangeInFileWithContents(virtualFile.path, Range(
return@runReadAction RangeInFileWithContents(
virtualFile.path, Range(
Position(startLine, startChar),
Position(endLine, endChar)
), selectedText)
), selectedText
)
}
return result
@ -856,8 +902,8 @@ class IdeProtocolClient (
// ))
continuePluginService.sendToWebview(
"highlightedCode",
mapOf(
"highlightedCode",
mapOf(
"rangeInFileWithContents" to rif,
"edit" to edit
)
@ -877,29 +923,30 @@ class IdeProtocolClient (
}
private val DEFAULT_IGNORE_DIRS = listOf(
".git",
".vscode",
".idea",
".vs",
"venv",
".venv",
"env",
".env",
"node_modules",
"dist",
"build",
"target",
"out",
"bin",
".pytest_cache",
".vscode-test",
".continue",
"__pycache__",
"site-packages",
".gradle",
".cache",
"gems",
".git",
".vscode",
".idea",
".vs",
"venv",
".venv",
"env",
".env",
"node_modules",
"dist",
"build",
"target",
"out",
"bin",
".pytest_cache",
".vscode-test",
".continue",
"__pycache__",
"site-packages",
".gradle",
".cache",
"gems",
)
private fun shouldIgnoreDirectory(name: String): Boolean {
val components = File(name).path.split(File.separator)
return DEFAULT_IGNORE_DIRS.any { dir ->
@ -976,21 +1023,16 @@ class IdeProtocolClient (
return virtualFile?.path
}
suspend fun showMessage(msg: String) {
withContext(Dispatchers.Main) {
val statusBar = WindowManager.getInstance().getStatusBar(project)
fun showToast(type: String, content: String) {
val notificationType = when (type.uppercase()) {
"ERROR" -> NotificationType.ERROR
"WARNING" -> NotificationType.WARNING
else -> NotificationType.INFORMATION
}
JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(msg, MessageType.INFO, null)
.setFadeoutTime(10000)
.setHideOnAction(false)
.createBalloon()
.show(
RelativePoint.getSouthEastOf(statusBar.component),
Balloon.Position.atRight
)
CONTINUE_NOTIFICATION_GROUP.createNotification(content, notificationType)
.notify(project);
}
}
fun highlightCode(rangeInFile: RangeInFile, color: String?) {
val file =

View file

@ -24,46 +24,65 @@ import com.intellij.util.ui.UIUtil
import net.miginfocom.swing.MigLayout
import org.jdesktop.swingx.JXPanel
import org.jdesktop.swingx.JXTextArea
import org.jdesktop.swingx.border.DropShadowBorder
import java.awt.*
import java.awt.event.*
import java.awt.geom.RoundRectangle2D
import java.awt.geom.Path2D
import javax.swing.*
import javax.swing.border.EmptyBorder
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.plaf.basic.BasicComboBoxUI
import kotlin.math.max
import java.awt.geom.RoundRectangle2D
import java.awt.geom.AffineTransform
import javax.swing.event.ListDataListener
const val SHADOW_SIZE = 7
const val MAIN_FONT_SIZE = 13
fun makeTextArea(): JTextArea {
val textArea = CustomTextArea( 2, 40).apply {
val textArea = CustomTextArea(1, 40).apply {
lineWrap = true
wrapStyleWord = true
isOpaque = false
background = GetTheme().getSecondaryDark()
maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
margin = JBUI.insets(8)
margin = JBUI.insets(6, 4, 6, 4)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
preferredSize = Dimension(400, 75)
}
textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
return textArea
}
fun makePanel(project: Project, customPanelRef: Ref<CustomPanel>, textArea: JTextArea, inlayRef: Ref<Disposable>, comboBoxRef: Ref<JComboBox<String>>, leftInset: Int, modelTitles: List<String>, onEnter: () -> Unit, onCancel: () -> Unit, onAccept: () -> Unit, onReject: () -> Unit): JPanel {
val topPanel = ShadowPanel(MigLayout("wrap 1, insets 4 $leftInset 2 2, gap 0!")).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
// background = defaultBackground
background = JBColor(0x20888888.toInt(), 0x20888888.toInt())
fun makePanel(
project: Project,
customPanelRef: Ref<CustomPanel>,
textArea: JTextArea,
inlayRef: Ref<Disposable>,
comboBoxRef: Ref<JComboBox<String>>,
leftInset: Int,
modelTitles: List<String>,
onEnter: () -> Unit,
onCancel: () -> Unit,
onAccept: () -> Unit,
onReject: () -> Unit
): JPanel {
val topPanel = ShadowPanel(MigLayout("wrap 1, insets 2 ${leftInset} 2 2, gap 0!")).apply {
background = JBColor(0x20888888.toInt(), 0x20888888.toInt())
isOpaque = false
}
val panel = CustomPanel(MigLayout("wrap 1, insets 0, gap 0!, fillx"), project, modelTitles, comboBoxRef, onEnter, onCancel, onAccept, onReject).apply {
val panel = CustomPanel(
MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
project,
modelTitles,
comboBoxRef,
onEnter,
onCancel,
onAccept,
onReject,
textArea
).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
background = defaultBackground
@ -71,16 +90,9 @@ fun makePanel(project: Project, customPanelRef: Ref<CustomPanel>, textArea: JTex
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
preferredSize = textArea.preferredSize
isOpaque = false
setup()
val shadow = DropShadowBorder()
shadow.shadowColor = JBColor(0xb0b0b0, 0x505050)
shadow.isShowRightShadow = true
shadow.isShowBottomShadow = true
shadow.shadowSize = SHADOW_SIZE
border = shadow
}
customPanelRef.set(panel)
textArea.addComponentListener(object : ComponentAdapter() {
@ -99,9 +111,9 @@ fun openInlineEdit(project: Project?, editor: Editor) {
if (project == null) return
// Don't open in terminal
if (EditorUtils().isTerminal(editor)) {
return
}
if (EditorUtils().isTerminal(editor)) {
return
}
val manager = EditorComponentInlaysManager.from(editor, true)
@ -142,7 +154,8 @@ fun openInlineEdit(project: Project?, editor: Editor) {
val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
val text = editor.document.getText(TextRange(lineStart, lineEnd))
val indentation = text.takeWhile { it == ' ' }.length
val charWidth = editor.contentComponent.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)).charWidth(' ')
val charWidth =
editor.contentComponent.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)).charWidth(' ')
val leftInset = indentation * charWidth * 2 / 3
val inlayRef = Ref<Disposable>()
@ -165,8 +178,9 @@ fun openInlineEdit(project: Project?, editor: Editor) {
val comboBoxRef = Ref<JComboBox<String>>()
fun onEnter() {
val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(" ▾")
customPanelRef.get().enter()
diffStreamHandler.run(textArea.text, prefix, highlighted, suffix, comboBoxRef.get().selectedItem as String)
diffStreamHandler.run(textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret)
}
val panel = makePanel(project, customPanelRef, textArea, inlayRef, comboBoxRef, leftInset, modelTitles, {onEnter()}, {
@ -180,6 +194,7 @@ fun openInlineEdit(project: Project?, editor: Editor) {
inlayRef.get().dispose()
})
val inlay = manager.insert(startLineNum, panel, true)
panel.revalidate()
inlayRef.set(inlay)
val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
@ -187,20 +202,40 @@ fun openInlineEdit(project: Project?, editor: Editor) {
// Add key listener to text area
textArea.addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_ESCAPE) {
diffStreamService.reject(editor)
override fun keyTyped(e: KeyEvent) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
// Re-highlight the selected text
val documentLength = editor.document.textLength
val safeEnd = minOf(end, documentLength)
selectionModel.setSelection(start, safeEnd)
} else if (e.keyCode == KeyEvent.VK_ENTER) {
if (e.modifiersEx == KeyEvent.SHIFT_DOWN_MASK) {
textArea.document.insertString(textArea.caretPosition, "\n", null)
} else if (e.modifiersEx == 0) {
onEnter()
e.consume()
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> {
diffStreamService.reject(editor)
selectionModel.setSelection(start, end)
}
KeyEvent.VK_ENTER -> {
when (e.modifiersEx) {
KeyEvent.SHIFT_DOWN_MASK -> {
textArea.document.insertString(textArea.caretPosition, "\n", null)
}
0 -> {
onEnter()
e.consume()
}
}
}
}
}
// We need this because backspace/delete is not registering properly on keyPressed for an unknown reason
override fun keyReleased(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
}
@ -216,6 +251,7 @@ fun openInlineEdit(project: Project?, editor: Editor) {
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
}
}
override fun insertUpdate(e: DocumentEvent?) {
updateSize()
}
@ -253,19 +289,67 @@ class InlineEditAction : AnAction(), DumbAware {
}
}
class CustomPanel(layout: MigLayout, project: Project, modelTitles: List<String>, comboBoxRef: Ref<JComboBox<String>>, onEnter: () -> Unit, onCancel: () -> Unit, onAccept: () -> Unit, onReject: () -> Unit): JPanel(layout) {
class CustomPanel(
layout: MigLayout,
project: Project,
modelTitles: List<String>,
comboBoxRef: Ref<JComboBox<String>>,
private val onEnter: () -> Unit,
private val onCancel: () -> Unit,
private val onAccept: () -> Unit,
private val onReject: () -> Unit,
private val textArea: JTextArea
) : JPanel(layout) {
private val shadowSize = 5
private val cornerRadius = 8
private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow
private val borderColor = Color(128, 128, 128, 128)
private val borderThickness = 1
private val triangleSize = 6
private val rightMargin = 3.0
private val closeButton: JComponent = createCloseButton()
private val originalTextColor: Color = textArea.foreground
private val greyTextColor: Color = Color(128, 128, 128, 200)
public var isFinished = false
init {
isOpaque = false
add(closeButton, "pos 100%-25 0 -3 3, w 20!, h 20!")
}
private fun createCloseButton(): JComponent {
return JLabel("X").apply {
foreground = Color(128, 128, 128, 128)
background = Color(0, 0, 0, 0)
font = UIUtil.getFontWithFallback("Arial", Font.BOLD, 10)
border = EmptyBorder(2, 6, 2, 6)
toolTipText = "`esc` to cancel"
isOpaque = false
addMouseListener(object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
foreground = Color(128, 128, 128, 255)
cursor = Cursor(Cursor.HAND_CURSOR)
}
override fun mouseExited(e: MouseEvent) {
foreground = Color(128, 128, 128, 128)
cursor = Cursor.getDefaultCursor()
}
override fun mouseClicked(e: MouseEvent) {
onCancel()
}
})
}
}
private val subPanelA: JPanel = JPanel(MigLayout("insets 0, fillx")).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val leftButton = CustomButton("Esc to cancel") { onCancel() }.apply {
foreground = Color(128, 128, 128, 200)
background = defaultBackground
}
val continueSettingsService = service<ContinueExtensionSettings>()
val dropdown = JComboBox(modelTitles.toTypedArray()).apply {
setUI(TransparentArrowButtonUI())
isEditable = true
background = defaultBackground
foreground = Color(128, 128, 128, 200)
@ -275,7 +359,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List<String>
isEditable = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
renderer = DefaultListCellRenderer().apply {
horizontalAlignment = SwingConstants.RIGHT
horizontalAlignment = SwingConstants.LEFT
}
selectedIndex = continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
if (modelTitles.isEmpty()) -1 else {
@ -287,16 +371,14 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List<String>
addActionListener {
continueSettingsService.continueState.lastSelectedInlineEditModel = selectedItem as String
}
// setUI(TransparentArrowButtonUI())
}
comboBoxRef.set(dropdown)
val rightButton = CustomButton("Submit") { onEnter() }.apply {
// background = GetTheme().getHighlight()
background = JBColor(0xe04573e8.toInt(), 0xe04573e8.toInt())
foreground = JBColor(0xffffffff.toInt(), 0xffffffff.toInt())
val rightButton = CustomButton("⏎ Enter") { onEnter() }.apply {
background = JBColor(0x999998.toInt(), 0x999998.toInt())
foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt())
border = EmptyBorder(2, 6, 2, 6)
}
val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
@ -306,75 +388,43 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List<String>
add(rightButton, "align right")
}
border = EmptyBorder(4, 8, 4, 8)
border = EmptyBorder(0, 0, 20, 16)
add(leftButton, "align left")
add(rightPanel, "align right")
add(dropdown, "align left")
add(rightPanel, "align right, split 2")
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
}
private val subPanelB: JPanel = JPanel(MigLayout("insets 0, fillx")).apply {
// Get the global color scheme and default background color
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val leftButton = CustomButton("Esc to cancel") { onCancel() }.apply {
foreground = Color(128, 128, 128, 200)
background = defaultBackground
}
val dropdown = JComboBox(modelTitles.toTypedArray()).apply {
isEditable = true
background = defaultBackground
foreground = Color(128, 128, 128, 200)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = EmptyBorder(2, 4, 2, 4)
isOpaque = false
isEditable = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
renderer = DefaultListCellRenderer().apply {
horizontalAlignment = SwingConstants.RIGHT
}
isVisible = false
// setUI(TransparentArrowButtonUI())
}
val progressBar = JProgressBar()
progressBar.isIndeterminate = true
val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
border = EmptyBorder(0, 0, 0, 0)
add(dropdown, "align right")
add(progressBar, "align right")
}
border = EmptyBorder(4, 8, 4, 8)
add(leftButton, "align left")
add(rightPanel, "align right")
private val subPanelB: JPanel = JPanel(BorderLayout()).apply {
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
val progressBar = JProgressBar().apply {
isIndeterminate = true
}
add(progressBar, BorderLayout.CENTER)
border = BorderFactory.createEmptyBorder(0, 0, 20, 16)
}
private val subPanelC: JPanel = JPanel(MigLayout("insets 0, fillx")).apply {
val leftLabel = JLabel("Enter follow-up instructions").apply {
foreground = Color(128, 128, 128, 200)
val leftLabel = JLabel("Type to re-prompt").apply {
foreground = Color(156, 163, 175) // text-gray-400
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = EmptyBorder(0, 4, 0, 0)
}
val leftButton = CustomButton("${getAltKeyLabel()}⇧N") { onReject() }.apply {
background = Color(255, 0, 0, 64)
val leftButton = CustomButton("Reject (${getAltKeyLabel()}⇧N)") { onReject() }.apply {
background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt())
foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt())
}
val rightButton = CustomButton("${getAltKeyLabel()}⇧Y") { onAccept() }.apply {
background = Color(0, 255, 0, 64)
val rightButton = CustomButton("Accept (${getAltKeyLabel()}⇧Y)") { onAccept() }.apply {
background = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt())
foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt())
}
val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
@ -386,7 +436,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List<String>
add(leftLabel, "align left")
add(rightPanel, "align right")
border = EmptyBorder(4, 8, 4, 8)
border = BorderFactory.createEmptyBorder(0, 0, 20, 16)
isOpaque = false
}
@ -394,6 +444,10 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List<String>
remove(subPanelB)
remove(subPanelC)
add(subPanelA, "grow, gap 0!")
isFinished = false
revalidate()
repaint()
textArea.foreground = originalTextColor
}
fun enter() {
@ -409,33 +463,63 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List<String>
add(subPanelC, "grow, gap 0!")
revalidate()
repaint()
isFinished = true
textArea.foreground = greyTextColor
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
// Draw the rounded border
val borderColor = Color(128, 128, 128, 128)
val borderThickness = 1
val borderRadius = 8
val w = width - shadowSize
val h = height - shadowSize
g2.color = borderColor
g2.stroke = BasicStroke(borderThickness.toFloat())
g2.drawRoundRect(
borderThickness / 2,
borderThickness / 2,
width - borderThickness - SHADOW_SIZE + 1,
height - borderThickness - SHADOW_SIZE + 1,
borderRadius,
borderRadius
// Create the shape for the tooltip/triangle
val shape = Path2D.Double()
shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
shape.quadTo(borderThickness / 2.0, borderThickness / 2.0, cornerRadius.toDouble(), borderThickness / 2.0)
shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
borderThickness / 2.0,
w - borderThickness / 2.0 - rightMargin,
cornerRadius.toDouble()
)
shape.lineTo(w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble())
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
h - triangleSize.toDouble(),
w - cornerRadius.toDouble() - rightMargin,
h - triangleSize.toDouble()
)
shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble())
shape.lineTo(borderThickness / 2.0, h.toDouble())
shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble())
// Draw shadow
g2.color = shadowColor
g2.fill(
shape.createTransformedShape(
AffineTransform.getTranslateInstance(
shadowSize.toDouble(),
shadowSize.toDouble()
)
)
)
super.paintComponent(g)
// Draw main shape
g2.color = background
g2.fill(shape)
// Draw border
g2.color = borderColor
g2.stroke = BasicStroke(borderThickness.toFloat())
g2.draw(shape)
}
}
class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
private var isHovered = false
@ -458,26 +542,41 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
}
})
// verticalAlignment = CENTER
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = EmptyBorder(2, 4, 2, 4)
border = EmptyBorder(2, 6, 2, 6)
}
override fun paintComponent(g: Graphics) {
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val cornerRadius = 8
val rect = Rectangle(0, 0, width, height)
val roundRect = RoundRectangle2D.Float(rect.x.toFloat(), rect.y.toFloat(), rect.width.toFloat(), rect.height.toFloat(), cornerRadius.toFloat(), cornerRadius.toFloat())
val roundRect = RoundRectangle2D.Float(
rect.x.toFloat(),
rect.y.toFloat(),
rect.width.toFloat(),
rect.height.toFloat(),
cornerRadius.toFloat(),
cornerRadius.toFloat()
)
if (isHovered) {
g2.color = background.brighter()
val brightenFactor = 1.1f
val brighterColor = Color(
(background.red * brightenFactor).toInt(),
(background.green * brightenFactor).toInt(),
(background.blue * brightenFactor).toInt()
)
g2.color = brighterColor
} else {
g2.color = background
}
g2.fill(roundRect)
g2.color = foreground
g2.drawString(text, (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
(height / 2 + g.fontMetrics.ascent / 2).toFloat())
g2.drawString(
text, (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
(height / 2 + g.fontMetrics.ascent / 2).toFloat()
)
}
}
@ -492,7 +591,7 @@ class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
if (text.isEmpty()) {
g.color = Color(128, 128, 128, 255)
g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
g.drawString("Enter instructions to edit highlighted code", 8, 20)
g.drawString("Enter instructions...", 3, 20)
}
super.paintComponent(g)
@ -514,37 +613,69 @@ class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
}
class TransparentArrowButtonUI : BasicComboBoxUI() {
override fun createArrowButton() = object : JButton() {
override fun paintComponent(g: Graphics) {
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val size = 6
val x = (width - size) / 2
val y = (height - size / 2) / 2
val triangle = Polygon(
intArrayOf(x, x + size, x + size / 2),
intArrayOf(y, y, (y + size / 1.16).toInt()),
3
)
g2.color = Color.GRAY
g2.fill(triangle)
}
}.apply {
border = EmptyBorder(0, 0, 0, 0)
// background = Color(0, 0, 0, 0)
isOpaque = false
override fun createArrowButton() = JButton().apply {
isVisible = false
preferredSize = Dimension(0, 0)
}
override fun getInsets(): Insets {
return JBUI.insets(0, 0, 0, 0)
return JBUI.insets(0, 6, 0, 0)
}
override fun installUI(c: JComponent?) {
super.installUI(c)
comboBox.border = EmptyBorder(0, 0, 0, 0)
comboBox.isOpaque = false
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
comboBox.background = defaultBackground
// Modify the ComboBoxModel to include the down symbol
val originalModel = comboBox.model
comboBox.model = object : ComboBoxModel<Any> {
override fun getSize(): Int = originalModel.size
override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
override fun setSelectedItem(anItem: Any?) {
originalModel.selectedItem = anItem
}
override fun getSelectedItem(): Any? {
val item = originalModel.selectedItem
return "$item ▾"
}
override fun addListDataListener(l: ListDataListener?) {
originalModel.addListDataListener(l)
}
override fun removeListDataListener(l: ListDataListener?) {
originalModel.removeListDataListener(l)
}
}
}
}
override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
// Do nothing to prevent painting the background
}
override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
val renderer = comboBox.renderer
val item = comboBox.selectedItem
if (item != null) {
val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false)
c.font = comboBox.font
c.foreground = Color(156, 163, 175) // text-gray-400
c.background = comboBox.background
if (c is JComponent) {
c.isOpaque = false
}
val currentValuePane = currentValuePane
currentValuePane.paintComponent(g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true)
}
}
}

View file

@ -2,71 +2,96 @@ import com.github.continuedev.continueintellijextension.actions.focusContinueInp
import com.github.continuedev.continueintellijextension.editor.openInlineEdit
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.ui.components.JBPanel
import java.awt.*
import java.awt.event.ActionEvent
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.util.*
import javax.swing.JButton
import java.awt.geom.RoundRectangle2D
class StyledButton(text: String, foregroundColor: Color) : JButton(text) {
class StyledButton(text: String) : JButton(text) {
private var isHovered = false
private val editorBackground: Color
init {
cursor = Cursor(Cursor.HAND_CURSOR)
isOpaque = false
border = null
isContentAreaFilled = false
isFocusPainted = false
border = null // Remove the border
foreground = foregroundColor
cursor = Cursor(Cursor.HAND_CURSOR)
val scheme = EditorColorsManager.getInstance().globalScheme
val editorFont = scheme.getFont(EditorFontType.PLAIN)
val editorFontSize = editorFont.size
font = font.deriveFont(editorFontSize.toFloat() * 0.75f)
editorBackground = scheme.defaultBackground
addMouseListener(object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
isHovered = true
repaint()
}
override fun mouseExited(e: MouseEvent) {
isHovered = false
repaint()
}
})
}
override fun paintComponent(g: Graphics) {
val g2 = g.create() as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val arc = 24f // Corner radius
val padding = 0f
val x = padding
val y = padding
val w = (width - 2 * padding)
val h = (height - 2 * padding)
val width = width.toFloat()
val height = height.toFloat()
val arc = 6f
// Draw flat background
// g2.color = if (model.isPressed) Color(70, 70, 70) else Color(100, 100, 100)
// g2.fill(RoundRectangle2D.Float(x, y, w, h, arc, arc))
// Draw semi-transparent background
g2.color = editorBackground
g2.fill(RoundRectangle2D.Float(0f, 0f, width, height, arc, arc))
// Draw border
// g2.color = Color(120, 120, 120)
// g2.draw(RoundRectangle2D.Float(x, y, w - 1, h - 1, arc, arc))
g2.dispose()
g2.color = if (isHovered) foreground else foreground.darker()
g2.stroke = BasicStroke(1f)
g2.draw(RoundRectangle2D.Float(0.5f, 0.5f, width - 1f, height - 1f, arc, arc))
super.paintComponent(g)
g2.dispose()
}
}
class ToolTipComponent(editor: Editor, x: Int, y: Int) :
JBPanel<ToolTipComponent>() {
private var addToChatButton: StyledButton
private var editButton: StyledButton
private var backgroundColor: Color
private var foregroundColor: Color
init {
layout = null // Remove the FlowLayout
val globalScheme = EditorColorsManager.getInstance().globalScheme
backgroundColor = globalScheme.defaultBackground
foregroundColor = Color(
globalScheme.defaultForeground.red,
globalScheme.defaultForeground.green,
globalScheme.defaultForeground.blue,
200
)
// Make the background transparent
isOpaque = false
background = Color(0, 0, 0, 0)
val cmdCtrlChar = if (System.getProperty("os.name").lowercase(Locale.getDefault()).contains("mac")) "⌘" else "Ctrl"
addToChatButton = StyledButton("${cmdCtrlChar}J Chat", foregroundColor)
editButton = StyledButton("${cmdCtrlChar}I Edit", foregroundColor)
val cmdCtrlChar =
if (System.getProperty("os.name").lowercase(Locale.getDefault()).contains("mac")) "⌘" else "Ctrl"
val buttonHeight = 16
val buttonHorizontalPadding = 2
val buttonVerticalPadding = 2
val componentHorizontalPadding = 4
val buttonMargin = 4
addToChatButton = StyledButton("Chat (${cmdCtrlChar}J)")
editButton = StyledButton("Edit (${cmdCtrlChar}I)")
addToChatButton.addActionListener { e: ActionEvent? ->
focusContinueInput(editor.project)
@ -77,45 +102,28 @@ class ToolTipComponent(editor: Editor, x: Int, y: Int) :
editor.contentComponent.remove(this)
}
// Set bounds for buttons to remove spacing
addToChatButton.setBounds(0, 0, addToChatButton.preferredSize.width, addToChatButton.preferredSize.height)
editButton.setBounds(addToChatButton.preferredSize.width, 0, editButton.preferredSize.width, editButton.preferredSize.height)
// Calculate button widths
val addToChatWidth = addToChatButton.preferredSize.width + (2 * buttonHorizontalPadding)
val editWidth = editButton.preferredSize.width + (2 * buttonHorizontalPadding)
// Set bounds for buttons
addToChatButton.setBounds(componentHorizontalPadding, buttonVerticalPadding, addToChatWidth, buttonHeight)
editButton.setBounds(
componentHorizontalPadding + addToChatWidth + buttonMargin,
buttonVerticalPadding,
editWidth,
buttonHeight
)
add(addToChatButton)
add(editButton)
val totalWidth = addToChatButton.preferredSize.width + editButton.preferredSize.width
val totalHeight = addToChatButton.preferredSize.height
setBounds(x, y, totalWidth, totalHeight)
val totalWidth = addToChatWidth + editWidth + buttonMargin + (2 * componentHorizontalPadding)
val totalHeight = buttonHeight + (2 * buttonVerticalPadding)
// Make the background transparent
isOpaque = false
background = Color(0, 0, 0, 0)
}
override fun paintComponent(g: Graphics) {
val arc = 12f
val g2 = g.create() as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
// Draw rounded rectangle background
g2.color = backgroundColor
g2.fill(RoundRectangle2D.Float(0f, 0f, width.toFloat(), height.toFloat(), arc, arc))
// Draw rounded rectangle border
g2.color = Color(120, 120, 120)
val strokeWidth = 1.0f
g2.stroke = BasicStroke(1.0f)
g2.draw(RoundRectangle2D.Float(0f, 0f, width.toFloat() - strokeWidth, height.toFloat() - strokeWidth, arc, arc))
// Draw border between buttons
g2.color = Color(120, 120, 120)
g2.stroke = BasicStroke(1.0f)
val middleX = addToChatButton.width.toFloat()
g2.drawLine(middleX.toInt(), 0, middleX.toInt(), height)
g2.dispose()
super.paintComponent(g)
// Center the component on the provided y coordinate
val yPosition = y - (totalHeight / 2)
setBounds(x, yPosition, totalWidth, totalHeight)
}
}

View file

@ -12,25 +12,44 @@ import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.SelectionModel
import com.intellij.openapi.editor.event.SelectionEvent
import com.intellij.openapi.editor.event.SelectionListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.util.TextRange
import kotlinx.coroutines.CoroutineScope
import kotlin.math.max
import kotlin.math.min
import com.intellij.openapi.editor.Document
class ContinuePluginSelectionListener(
private val ideProtocolClient: IdeProtocolClient,
private val coroutineScope: CoroutineScope
) : SelectionListener, DumbAware {
private val debouncer = Debouncer(100L, coroutineScope)
private val debouncer = Debouncer(100, coroutineScope)
private var toolTipComponents: ArrayList<ToolTipComponent> = ArrayList()
override fun selectionChanged(e: SelectionEvent) {
debouncer.debounce { handleSelection(e) }
}
private var toolTipComponents: ArrayList<ToolTipComponent> = ArrayList()
private fun handleSelection(e: SelectionEvent) {
ApplicationManager.getApplication().runReadAction {
val editor = e.editor
val model: SelectionModel = editor.selectionModel
val selectedText = model.selectedText
private fun removeExistingTooltips(editor: Editor, onComplete : () -> Unit = {}) {
if (shouldRemoveTooltip(selectedText, editor)) {
removeExistingTooltips(editor)
return@runReadAction
}
updateTooltip(editor, model)
}
}
private fun shouldRemoveTooltip(selectedText: String?, editor: Editor): Boolean {
return selectedText.isNullOrEmpty() ||
!service<ContinueExtensionSettings>().continueState.displayEditorTooltip ||
EditorUtils().isTerminal(editor)
}
private fun removeExistingTooltips(editor: Editor, onComplete: () -> Unit = {}) {
ApplicationManager.getApplication().invokeLater {
toolTipComponents.forEach {
editor.contentComponent.remove(it)
@ -42,76 +61,114 @@ class ContinuePluginSelectionListener(
}
}
private fun handleSelection(e: SelectionEvent) {
ApplicationManager.getApplication().runReadAction {
val editor = e.editor
val model: SelectionModel = editor.selectionModel
val selectedText = model.selectedText
private fun updateTooltip(editor: Editor, model: SelectionModel) {
removeExistingTooltips(editor) {
ApplicationManager.getApplication().invokeLater {
val document = editor.document
val (startLine, endLine, isFullLineSelection) = getSelectionInfo(model, document)
val selectionTopY = calculateSelectionTopY(editor, startLine, endLine, isFullLineSelection)
val tooltipX = calculateTooltipX(editor, document, startLine, endLine, isFullLineSelection)
// If selected text is empty, remove the tooltip
if (selectedText.isNullOrEmpty()) {
removeExistingTooltips(editor)
return@runReadAction
}
// Allow user to disable editor tooltip
// Note that we still check for empty selected text before this
val extensionSettingsService = service<ContinueExtensionSettings>()
if (extensionSettingsService.continueState.displayEditorTooltip == false) {
return@runReadAction
}
// Don't display in the terminal
if (EditorUtils().isTerminal(editor)) {
return@runReadAction
}
val document = editor.document
val startOffset = model.selectionStart
val endOffset = model.selectionEnd
val startLine = document.getLineNumber(startOffset)
val endLine = document.getLineNumber(endOffset)
val startCharacter =
startOffset - document.getLineStartOffset(startLine)
val endCharacter = endOffset - document.getLineStartOffset(endLine)
val virtualFile: VirtualFile? =
FileDocumentManager.getInstance().getFile(document)
val filepath = virtualFile?.path ?: "Unknown path"
removeExistingTooltips(editor) {
ApplicationManager.getApplication().invokeLater {
editor.contentComponent.layout = null
val line = startLine - 2
if (line > 0 && startLine < endLine) {
// Get the text on line number "line"
// val text = document.getText(document.getLineStartOffset(line), document.getLineEndOffset(line))
val pos = LogicalPosition(line, selectedText.split("\n")[0].length + 1)
val y: Int = editor.logicalPositionToXY(pos).y + editor.lineHeight
var x: Int = editor.logicalPositionToXY(pos).x
// Check if x is out of bounds
val maxEditorWidth = editor.contentComponent.width
val maxToolTipWidth = 600
x = max(0, min(x, maxEditorWidth - maxToolTipWidth))
val toolTipComponent = ToolTipComponent(editor, x, y)
toolTipComponents.add(toolTipComponent)
editor.contentComponent.add(toolTipComponent)
}
editor.contentComponent.revalidate()
editor.contentComponent.repaint()
if (tooltipX != null) {
addToolTipComponent(editor, tooltipX, selectionTopY)
}
}
}
}
private fun getSelectionInfo(model: SelectionModel, document: Document): Triple<Int, Int, Boolean> {
val startOffset = model.selectionStart
val endOffset = model.selectionEnd
val startLine = document.getLineNumber(startOffset)
val endLine = document.getLineNumber(endOffset)
val isFullLineSelection = startOffset == document.getLineStartOffset(startLine) &&
(endOffset == document.getLineEndOffset(endLine - 1) || endOffset == document.getLineStartOffset(endLine))
val adjustedEndLine = if (isFullLineSelection && endLine > startLine) endLine - 1 else endLine
return Triple(startLine, adjustedEndLine, isFullLineSelection)
}
private fun calculateSelectionTopY(
editor: Editor,
startLine: Int,
endLine: Int,
isFullLineSelection: Boolean
): Int {
return if (startLine == endLine || isFullLineSelection) {
val lineTopY = editor.logicalPositionToXY(LogicalPosition(startLine, 0)).y
lineTopY + (editor.lineHeight / 2)
} else {
editor.logicalPositionToXY(LogicalPosition(startLine, 0)).y
}
}
private fun calculateTooltipX(
editor: Editor,
document: Document,
startLine: Int,
endLine: Int,
isFullLineSelection: Boolean
): Int? {
fun isLineEmpty(lineNumber: Int): Boolean {
val lineStartOffset = document.getLineStartOffset(lineNumber)
val lineEndOffset = document.getLineEndOffset(lineNumber)
return document.getText(TextRange(lineStartOffset, lineEndOffset)).trim().isEmpty()
}
fun getLineEndX(lineNumber: Int): Int {
val lineStartOffset = document.getLineStartOffset(lineNumber)
val lineEndOffset = document.getLineEndOffset(lineNumber)
val lineText = document.getText(TextRange(lineStartOffset, lineEndOffset)).trimEnd()
val endOfLinePos = LogicalPosition(lineNumber, lineText.length)
return editor.logicalPositionToXY(endOfLinePos).x
}
val offset = 40
// If only one line is selected and it's empty, return null
if (startLine == endLine && isLineEmpty(startLine) && !isFullLineSelection) {
return null
}
// Find the topmost non-empty line within the selection
var topNonEmptyLine = startLine
while (topNonEmptyLine <= endLine && isLineEmpty(topNonEmptyLine)) {
topNonEmptyLine++
}
// If all lines in the selection are empty, return null
if (topNonEmptyLine > endLine) {
return null
}
// Always display inline if the selection is a single line
if (isFullLineSelection || startLine == endLine) {
return getLineEndX(topNonEmptyLine) + offset
}
// Check the line above the start of the selection (if it exists)
val lineAboveSelection = maxOf(0, startLine - 1)
// Get x-coordinates
val xCoordTopNonEmpty = getLineEndX(topNonEmptyLine)
val xCoordLineAbove = getLineEndX(lineAboveSelection)
// Use the maximum of the two x-coordinates
val baseXCoord = maxOf(xCoordTopNonEmpty, xCoordLineAbove)
// Calculate the final x-coordinate
return baseXCoord + offset
}
private fun addToolTipComponent(editor: Editor, tooltipX: Int, selectionTopY: Int) {
val toolTipComponent = ToolTipComponent(editor, tooltipX, selectionTopY)
toolTipComponents.add(toolTipComponent)
editor.contentComponent.add(toolTipComponent)
editor.contentComponent.revalidate()
editor.contentComponent.repaint()
}
}

View file

@ -27,7 +27,7 @@ class ContinueSettingsComponent: DumbAware {
val remoteConfigSyncPeriod: JTextField = JTextField()
val userToken: JTextField = JTextField()
val enableTabAutocomplete: JCheckBox = JCheckBox("Enable Tab Autocomplete")
val enableContinueTeamsBeta: JCheckBox = JCheckBox("Enable Continue for Teams Beta (requires restart)")
val enableContinueTeamsBeta: JCheckBox = JCheckBox("Enable Continue for Teams Beta")
val displayEditorTooltip: JCheckBox = JCheckBox("Display Editor Tooltip")
init {

View file

@ -1,6 +1,7 @@
package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.activities.showTutorial
import com.github.continuedev.continueintellijextension.constants.MessageTypes
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.github.continuedev.continueintellijextension.`continue`.*
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
@ -8,7 +9,6 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer

View file

@ -5,7 +5,8 @@
<vendor>continue-dev</vendor>
<depends>com.intellij.modules.platform</depends>
<depends>com.intellij.modules.json</depends>
<idea-version since-build="223.0"/>
<!-- com.intellij.openapi.module.ModuleManager.Companion is only available since this build -->
<idea-version since-build="223.7571.182"/>
<extensions defaultExtensionNs="JavaScript.JsonSchema">
<ProviderFactory implementation="com.github.continuedev.continueintellijextension.continue.ConfigJsonSchemaProviderFactory"/>

View file

@ -699,8 +699,17 @@
},
"then": {
"properties": {
"cacheSystemMessage": {
"type": "boolean"
"cacheBehavior": {
"title": "Caching Behavior",
"description": "Options for the prompt caching",
"properties": {
"cacheSystemMessage": {
"type": "boolean"
},
"cacheConversation": {
"type": "boolean"
}
}
},
"model": {
"anyOf": [
@ -796,8 +805,14 @@
},
"then": {
"properties": {
"cacheSystemMessage": {
"type": "boolean"
"cacheBehavior": {
"title": "Caching Behavior",
"description": "Options for the prompt caching",
"properties": {
"cacheSystemMessage": {
"type": "boolean"
}
}
},
"model": {
"enum": [
@ -1017,8 +1032,17 @@
},
"then": {
"properties": {
"cacheSystemMessage": {
"type": "boolean"
"cacheBehavior": {
"title": "Caching Behavior",
"description": "Options for the prompt caching",
"properties": {
"cacheSystemMessage": {
"type": "boolean"
},
"cacheConversation": {
"type": "boolean"
}
}
},
"model": {
"enum": ["deepseek-chat", "deepseek-coder"]
@ -1528,7 +1552,8 @@
"url",
"database",
"os",
"repo-map"
"repo-map",
"greptile"
],
"markdownEnumDescriptions": [
"Reference the contents of the current changes as given by `git diff`",
@ -1552,7 +1577,8 @@
"Reference the contents of a page at a URL",
"Reference table schemas",
"Operating system and CPU Information",
"Map of files in the repository with important code highlights"
"Map of files in the repository with important code highlights",
"Query your greptile index of the current repo"
],
"type": "string"
},
@ -1930,6 +1956,36 @@
},
"required": ["host", "port", "user", "password", "database"]
}
},
{
"if": {
"properties": {
"name": {
"enum": ["greptile"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"GithubToken": {
"title": "GithubToken",
"description": "Your github access token",
"default": "",
"type": "string"
},
"GreptileToken": {
"title": "GreptileToken",
"description": "Your greptile access token",
"default": "",
"type": "string"
}
}
}
},
"required": ["GreptileToken", "GithubToken"]
}
}
],
"required": ["name"]

View file

@ -6,10 +6,17 @@ and is generated by [Changie](https://github.com/miniscruff/changie).
Pre-release Changes
### Added
* Improved loading/accept/reject UI for apply
* Polished chat sidebar, especially context dropdown
* Further prompt caching with Anthropic
### Changed
* Updated tutorial file
* Improved styling on "More" page
### Fixed
* Continue for teams auth bug fix
* Fixed a number of apply bugs
* Fixed autoscrolling behavior
## 0.9.210 - 2024-09-15

Some files were not shown because too many files have changed in this diff Show more