Merge branch 'main' into pe/fix-lancedb-unsupported-cpus

This commit is contained in:
Patrick Erichsen 2025-01-10 09:25:58 -08:00 • committed by GitHub
commit f271024563
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
159 changed files with 2799 additions and 1771 deletions

View file

@ -0,0 +1,83 @@
---
name: 📖 Documentation Issue Report
description: Report issues related to the documentation
labels: [area:docs]
body:
- type: markdown
attributes:
value: |
## Thank you for helping us improve our documentation!
We appreciate your feedback. Before submitting, please check if a similar issue already exists.
### Quick Contribution Tips:
- Click "Edit this page" at the bottom of any page on [docs.continue.dev](https://docs.continue.dev) to contribute directly.
- For local development, see [CONTRIBUTING.md](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md#-updating--improving-documentation).
- type: dropdown
id: doc-issue-category
attributes:
label: Issue Category
description: Select the category that best describes your issue.
options:
- Undocumented feature or missing documentation
- Incorrect or outdated information
- Suggestion for existing article
- Broken or dead link
- Documentation organization issue
- Other (please describe in the details section)
validations:
required: true
- type: input
id: page-url
attributes:
label: Affected Documentation Page URL
description: Provide the URL of the specific page where you encountered the issue.
placeholder: "https://docs.continue.dev/path/to/page"
validations:
required: false
- type: textarea
id: details
attributes:
label: Issue Description
description: Please describe the issue in detail. Include specifics about missing information, outdated content, or improvements needed.
placeholder: |
Examples:
- Missing section on [topic]
- Incorrect information about [subject]
- Outdated example code for [feature]
- Suggestion to improve [section] by [details]
validations:
required: true
- type: textarea
id: expected-content
attributes:
label: Expected Content
description: If applicable, provide the content you believe should be added or updated.
placeholder: "Suggested details or changes for the documentation..."
- type: textarea
id: additional-info
attributes:
label: Additional Information
description: Add any other relevant information that may help us understand and resolve your issue.
placeholder: "Additional context, screenshots, or related links..."
- type: input
id: related-issue
attributes:
label: Related Issue
description: If this issue is related to an existing GitHub issue, provide the issue number.
placeholder: "#123"
- type: checkboxes
id: terms
attributes:
label: Code of Conduct
description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/continuedev/continue/blob/main/CODE_OF_CONDUCT.md)
options:
- label: I agree to follow this project's Code of Conduct
required: true

View file

@ -96,7 +96,7 @@ jobs:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
install-gui:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -157,7 +157,7 @@ jobs:
npx tsc --noEmit
binary-checks:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -193,7 +193,7 @@ jobs:
npx tsc --noEmit
install-vscode:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -277,7 +277,7 @@ jobs:
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
needs: [install-root, install-vscode]
needs: [ install-root, install-vscode ]
outputs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
@ -306,7 +306,7 @@ jobs:
vscode-package-extension:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
needs: [ install-vscode, install-core ]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@ -338,7 +338,7 @@ jobs:
vscode-download-e2e-dependencies:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
needs: [ install-vscode, install-core ]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@ -445,7 +445,7 @@ jobs:
path: extensions/vscode/e2e/storage/screenshots
gui-tests:
needs: [install-gui, install-core]
needs: [ install-gui, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -476,7 +476,7 @@ jobs:
npm test
jetbrains-tests:
needs: [install-root, install-core]
needs: [ install-root, core-checks ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -573,3 +573,5 @@ jobs:
name: jb-failure-report
path: |
${{ github.workspace }}/extensions/intellij/build/reports

View file

@ -7,7 +7,7 @@ Continue now provides support for tab autocomplete in [VS Code](https://marketpl
We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model:
```bash
ollama run qwen2.5-coder:1.5b
ollama run qwen2.5-coder:1.5b-base
```
Once it has been downloaded, you should begin to see completions in VS Code.
@ -101,7 +101,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
},
"tabAutocompleteOptions": {
@ -123,9 +123,9 @@ Follow these steps to ensure that everything is set up correctly:
1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar).
2. Make sure you have downloaded Ollama.
3. Run `ollama run qwen2.5-coder:1.5b` to verify that the model is downloaded.
3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded.
4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere.
5. Make sure that you aren't also using another Ollama model for chat. This will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both.
5. If you are using another Ollama model for chat and your resources are limited, this will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. A resolution for this could be using the same model for chat and autocomplete.
6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains).
7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible.

View file

@ -5,7 +5,7 @@ const CommitMessageCommand: SlashCommand = {
name: "commit",
description: "Generate a commit message for current changes",
run: async function* ({ ide, llm, params }) {
const includeUnstaged = params?.includeUnstaged ?? true;
const includeUnstaged = params?.includeUnstaged ?? false;
const diff = await ide.getDiff(includeUnstaged);
if (diff.length === 0) {

View file

@ -1,5 +1,6 @@
import { SlashCommand } from "../../index.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { streamResponse } from "../../llm/stream.js";
const HttpSlashCommand: SlashCommand = {
name: "http",
@ -23,14 +24,8 @@ const HttpSlashCommand: SlashCommand = {
if (response.body === null) {
throw new Error("Response body is null");
}
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const decoded = new TextDecoder("utf-8").decode(value);
yield decoded;
for await (const chunk of streamResponse(response)) {
yield chunk;
}
},
};

View file

@ -25,6 +25,7 @@ import {
ProfileDescription,
ProfileLifecycleManager,
} from "./ProfileLifecycleManager.js";
import { pathToFileURL } from "url";
export type { ProfileDescription };
@ -88,7 +89,7 @@ export class ConfigHandler {
async openConfigProfile(profileId?: string) {
let openProfileId = profileId || this.selectedProfileId;
if (openProfileId === "local") {
await this.ide.openFile(getConfigJsonPath());
await this.ide.openFile(pathToFileURL(getConfigJsonPath()).toString());
} else {
await this.ide.openUrl(
"https://app.continue.dev/",

View file

@ -72,6 +72,7 @@ class MCPConnection {
return new StdioClientTransport({
command: options.transport.command,
args: options.transport.args,
env: options.transport.env,
});
case "websocket":
return new WebSocketClientTransport(new URL(options.transport.url));

View file

@ -0,0 +1,57 @@
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
import { clipboardCache } from "../../util/clipboardCache";
const MAX_CLIPBOARD_ITEMS = 10;
class ClipboardContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "clipboard",
displayTitle: "Clipboard",
description: "Recent copies",
type: "submenu",
};
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Assume the query is a cache id
const id = query.trim();
const content = clipboardCache.get(id);
if (content) {
clipboardCache.select(id);
return [
{
name: "Clipboard item",
description: content.slice(0, 20),
content,
},
];
}
return [];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const recentClipboardItems = clipboardCache.getNItems(MAX_CLIPBOARD_ITEMS);
console.log(recentClipboardItems);
return recentClipboardItems.map((item, index) => {
return {
id: item.id,
title: item.content.slice(0, 20),
description: `#${index + 1}`,
};
});
}
}
export default ClipboardContextProvider;

View file

@ -80,22 +80,28 @@ class DocsContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Get docs service
const docsService = DocsService.getSingleton();
if (!docsService) {
console.error(`${DocsService.name} has not been initialized`);
return [];
}
await docsService.isInitialized;
// Get chunks
let chunks = await docsService.retrieveChunksFromQuery(
extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case
query,
this.options?.nRetrieve ?? DocsContextProvider.nRetrieve,
);
if (!chunks?.length) {
return [];
}
// We found chunks, so check if there's a favicon for the docs page
const favicon = await docsService.getFavicon(query);
// Rerank if there's a rerankder
if (extras.reranker) {
chunks = await this._rerankChunks(
chunks,
@ -139,18 +145,30 @@ class DocsContextProvider extends BaseContextProvider {
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
// Get docs service
const docsService = DocsService.getSingleton();
if (!docsService) {
console.error(`${DocsService.name} has not been initialized`);
return [];
}
await docsService.isInitialized;
const docs = (await docsService.listMetadata()) ?? [];
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
// Create map of docs url -> submenu item
const submenuItemsMap = new Map<string, ContextSubmenuItem>();
// Add custom docs from config
const docs = (await docsService.listMetadata()) ?? [];
for (const { startUrl, title, favicon } of docs) {
submenuItemsMap.set(startUrl, {
title,
id: startUrl,
description: new URL(startUrl).hostname,
icon: favicon,
});
}
// Add pre-indexed docs if supported
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
if (canUsePreindexedDocs) {
for (const { startUrl, title } of Object.values(preIndexedDocs)) {
submenuItemsMap.set(startUrl, {
@ -164,17 +182,8 @@ class DocsContextProvider extends BaseContextProvider {
}
}
for (const { startUrl, title, favicon } of docs) {
submenuItemsMap.set(startUrl, {
title,
id: startUrl,
description: new URL(startUrl).hostname,
icon: favicon,
});
}
// Create array and sort if pre-indexed is supported
const submenuItems = Array.from(submenuItemsMap.values());
if (canUsePreindexedDocs) {
return this._sortByPreIndexedDocs(submenuItems);
}

View file

@ -22,6 +22,9 @@ class HttpContextProvider extends BaseContextProvider {
this.options.description ||
"Retrieve a context item from a custom server",
type: "normal",
renderInlineAs:
this.options.renderInlineAs ||
HttpContextProvider.description.renderInlineAs,
};
}

View file

@ -73,7 +73,15 @@ class MCPContextProvider extends BaseContextProvider {
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
return (this.options as MCPContextProviderOptions).submenuItems;
return (this.options as MCPContextProviderOptions).submenuItems.map(
(item, index) => ({
...item,
id: JSON.stringify({
mcpId: String(index),
uri: item.id,
}),
}),
);
}
}

View file

@ -1,5 +1,6 @@
import { BaseContextProvider } from "../";
import { ContextProviderName } from "../../";
import ClipboardContextProvider from "./ClipboardContextProvider";
import CodeContextProvider from "./CodeContextProvider";
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
@ -62,6 +63,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
GreptileContextProvider,
WebContextProvider,
MCPContextProvider,
ClipboardContextProvider,
];
export function contextProviderClassFromName(

View file

@ -12,7 +12,7 @@ import {
setupLocalConfigAfterFreeTrial,
setupQuickstartConfig,
} from "./config/onboarding";
import { addModel, deleteModel } from "./config/util";
import { addContextProvider, addModel, deleteModel } from "./config/util";
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
@ -46,6 +46,7 @@ import * as URI from "uri-js";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
import type { IMessenger, Message } from "./protocol/messenger";
import { localPathToUri } from "./util/pathToUri";
import { clipboardCache } from "./util/clipboardCache";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
@ -280,6 +281,10 @@ export class Core {
return this.configHandler.listProfiles();
});
on("config/addContextProvider", async (msg) => {
addContextProvider(msg.data);
});
// Context providers
on("context/addDocs", async (msg) => {
void this.docsService.indexAndAdd(msg.data);
@ -290,10 +295,11 @@ export class Core {
});
on("context/indexDocs", async (msg) => {
await this.docsService.syncOrReindexAllDocsWithPrompt(msg.data.reIndex);
await this.docsService.syncDocsWithPrompt(msg.data.reIndex);
});
on("context/loadSubmenuItems", async (msg) => {
console.log("Load SUMBENU ITEMS", msg);
const config = await this.config();
if (!config) {
return [];
@ -377,6 +383,12 @@ export class Core {
};
});
on("clipboardCache/add", (msg) => {
console.log("ADD TO CLIPBOARD", msg);
clipboardCache.add(uuidv4(), msg.data.content);
this.messenger.send("refreshSubmenuItems", undefined);
});
async function* llmStreamChat(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
@ -417,7 +429,6 @@ export class Core {
const chunk = next.value;
// @ts-ignore
yield { content: chunk };
next = await gen.next();
}
@ -818,7 +829,7 @@ export class Core {
});
on("indexing/setPaused", async (msg) => {
if (msg.data.type === "docs") {
// this.docsService.setPaused(msg.data.id, msg.data.paused);
// this.docsService.setPaused(msg.data.id, msg.data.paused); // not supported yet
}
});
on("docs/getSuggestedDocs", async (msg) => {

View file

@ -172,7 +172,7 @@ export async function deterministicApplyLazyEdit(
oldText.slice(endIndex);
} else {
console.warn("No matching node found for lazy block");
return [];
return undefined;
}
}
}

2
core/index.d.ts vendored
View file

@ -751,6 +751,7 @@ export type ContextProviderName =
| "issue"
| "repo-map"
| "url"
| "clipboard"
| string;
export type TemplateType =
@ -940,6 +941,7 @@ export interface StdioOptions {
type: "stdio";
command: string;
args: string[];
env?: Record<string, string>;
}
export interface WebSocketOptions {

View file

@ -18,7 +18,6 @@ import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbed
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { IMessenger } from "../../protocol/messenger";
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
import { GlobalContext } from "../../util/GlobalContext";
import {
editConfigJson,
getDocsSqlitePath,
@ -88,7 +87,6 @@ export default class DocsService {
public isSyncing: boolean = false;
private docsIndexingQueue = new Set<string>();
private globalContext = new GlobalContext();
private lanceTableNamesSet = new Set<string>();
private config!: ContinueConfig;
@ -145,7 +143,7 @@ export default class DocsService {
this.config.docs?.forEach((doc) => {
if (!doc.startUrl) {
console.error("Invalid config docs entry, no start");
console.error("Invalid config docs entry, no start url", doc.title);
return;
}
@ -184,20 +182,37 @@ export default class DocsService {
}
abort(startUrl: string) {
const status = this.statuses.get(startUrl);
if (status) {
if (this.docsIndexingQueue.has(startUrl)) {
const status = this.statuses.get(startUrl);
if (status) {
this.handleStatusUpdate({
...status,
status: "aborted",
progress: 0,
description: "Canceled",
});
}
this.docsIndexingQueue.delete(startUrl);
this.handleStatusUpdate({
...status,
status: "aborted",
progress: 0,
description: "Canceled",
});
}
}
isAborted(startUrl: string) {
return this.statuses.get(startUrl)?.status === "aborted";
shouldCancel(startUrl: string, startedWithEmbedder: string) {
// Check if aborted
const isAborted = this.statuses.get(startUrl)?.status === "aborted";
if (isAborted) {
return true;
}
// Handle indexing disabled change mid-indexing
if (this.config.disableIndexing) {
this.abort(startUrl);
return true;
}
// Handle embeddings provider change mid-indexing
if (this.config.embeddingsProvider.embeddingId !== startedWithEmbedder) {
this.abort(startUrl);
return true;
}
return false;
}
// NOTE Pausing not supported for docs yet
@ -255,93 +270,79 @@ export default class DocsService {
this.docsCrawler = new DocsCrawler(this.ide, newConfig);
if (this.config.disableIndexing) {
return;
}
// No point in indexing if no docs context provider
const hasDocsContextProvider = this.hasDocsContextProvider();
if (!hasDocsContextProvider) {
return;
}
// Skip docs indexing if not supported
// No warning message here because would show on ANY config update
const unsupported =
await this.isUsingUnsupportedPreIndexedEmbeddingsProvider();
if (unsupported) {
return;
}
await this.syncOrReindexAllDocs(newConfig, oldConfig);
await this.syncDocs(oldConfig, newConfig, false);
}
}
private async syncOrReindexAllDocs(
newConfig: ContinueConfig,
oldConfig?: ContinueConfig,
) {
// On embeddings provider change, reindex all non-preindexed docs
// change = doesn't match last successful embeddings provider
const curEmbeddingsProviderId = this.globalContext.get(
"curEmbeddingsProviderId",
);
if (
!curEmbeddingsProviderId ||
curEmbeddingsProviderId !== newConfig.embeddingsProvider.embeddingId
) {
// If not set, we're initializing
const currentDocs = await this.listMetadata();
if (currentDocs.length > 0) {
await this.reindexDocsOnNewEmbeddingsProvider();
return;
}
}
await this.syncDocsOnConfigUpdate(oldConfig, newConfig);
}
async syncOrReindexAllDocsWithPrompt(reIndex: boolean = false) {
async syncDocsWithPrompt(reIndex: boolean = false) {
if (!this.hasDocsContextProvider()) {
const didAddDocsContextProvider =
await this.showAddDocsContextProviderToast();
const actionMsg = "Add 'docs' context provider";
const res = await this.ide.showToast(
"info",
"Starting docs indexing",
actionMsg,
);
if (!didAddDocsContextProvider) {
if (res === actionMsg) {
addContextProvider({
name: DocsContextProvider.description.title,
params: {},
});
void this.ide.showToast(
"info",
"Successfuly added docs context provider",
);
} else {
return;
}
}
await this.syncOrReindexAllDocs(this.config);
await this.syncDocs(undefined, this.config, reIndex);
void this.ide.showToast("info", "Docs indexing completed");
}
// Returns true if startUrl has been indexed with current embeddingsProvider
async hasMetadata(startUrl: string): Promise<Promise<boolean>> {
const db = await this.getOrCreateSqliteDb();
const title = await db.get(
`SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
`SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
);
return !!title;
}
async showAddDocsContextProviderToast() {
const actionMsg = "Add 'docs' context provider";
const res = await this.ide.showToast(
"info",
"Starting docs indexing",
actionMsg,
);
if (res === actionMsg) {
addContextProvider({
name: DocsContextProvider.description.title,
params: {},
});
void this.ide.showToast(
"info",
"Successfuly added docs context provider",
);
}
return res === actionMsg;
}
async listMetadata() {
const embeddingsProvider = this.config.embeddingsProvider;
if (!embeddingsProvider) {
return [];
}
const db = await this.getOrCreateSqliteDb();
const docs = await db.all<SqliteDocsRow[]>(
`SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}`,
`SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}
WHERE embeddingsProviderId = ?`,
embeddingsProvider.embeddingId,
);
return docs;
@ -360,17 +361,29 @@ export default class DocsService {
siteIndexingConfig: SiteIndexingConfig,
reIndex: boolean = false,
): Promise<void> {
if (this.config.disableIndexing) {
console.warn("Attempting to add/index docs when indexing is disabled");
return;
}
const { startUrl } = siteIndexingConfig;
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
if (canUsePreindexedDocs) {
const preIndexedDoc = preIndexedDocs[startUrl];
const isPreIndexedDoc = !!preIndexedDoc;
if (isPreIndexedDoc) {
console.warn("Can not override pre-indexed start urls");
return;
}
}
// Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs
if (this.docsIndexingQueue.has(startUrl)) {
return;
}
const embeddingsProvider = await this.getEmbeddingsProvider();
this.docsIndexingQueue.add(startUrl);
const startedWithEmbedder = this.config.embeddingsProvider.embeddingId;
const indexExists = await this.hasMetadata(startUrl);
// Build status update - most of it is fixed values
@ -404,13 +417,11 @@ export default class DocsService {
}
}
// If not preindexed
const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl];
if (!isPreIndexedDoc) {
this.addToConfig(siteIndexingConfig);
}
try {
this.docsIndexingQueue.add(startUrl);
this.addToConfig(siteIndexingConfig);
this.handleStatusUpdate({
...fixedStatus,
status: "indexing",
@ -427,7 +438,7 @@ export default class DocsService {
estimatedProgress += 1 / 2 ** (processedPages + 1);
// NOTE - during "indexing" phase, check if aborted before each status update
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -465,7 +476,7 @@ export default class DocsService {
for (let i = 0; i < articles.length; i++) {
const article = articles[i];
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -502,7 +513,7 @@ export default class DocsService {
`No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`,
);
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -520,7 +531,7 @@ export default class DocsService {
// Add docs to databases
console.log(`Adding ${embeddings.length} embeddings to db`);
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -538,7 +549,7 @@ export default class DocsService {
const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl));
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -557,7 +568,7 @@ export default class DocsService {
this.docsIndexingQueue.delete(startUrl);
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -576,7 +587,7 @@ export default class DocsService {
console.error("Error indexing docs", e);
this.handleStatusUpdate({
...fixedStatus,
description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`,
description: `Error getting docs from: ${siteIndexingConfig.startUrl}`,
status: "failed",
progress: 1,
});
@ -649,13 +660,18 @@ export default class DocsService {
return await this.retrieveChunks(startUrl, vector, nRetrieve);
}
// This is split into its own function so that it can be recursive
// in the case of fetching preindexed docs from s3
async retrieveChunks(
startUrl: string,
vector: number[],
nRetrieve: number,
isRetry: boolean = false,
): Promise<Chunk[]> {
const isPreIndexedDoc = !!preIndexedDocs[startUrl];
const preIndexedDoc = preIndexedDocs[startUrl];
const isPreIndexedDoc = !!preIndexedDoc;
// Lance doesn't have an embeddingsprovider column, instead it includes it in the table name
const table = await this.getOrCreateLanceTable({
initializationVector: vector,
isPreIndexedDoc,
@ -672,19 +688,21 @@ export default class DocsService {
console.warn("Error retrieving chunks from LanceDB", e);
}
const hasIndexedDoc = await this.hasMetadata(startUrl);
if (!hasIndexedDoc && docs.length === 0) {
const preIndexedDoc = preIndexedDocs[startUrl];
if (isRetry || !preIndexedDoc) {
// No docs are found for preindexed? try fetching once
if (docs.length === 0 && isPreIndexedDoc) {
if (isRetry) {
return [];
}
await this.fetchAndAddPreIndexedDocEmbeddings(preIndexedDoc.title);
return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
}
if (isPreIndexedDoc) {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDoc["title"],
});
}
return docs.map((doc) => ({
digest: doc.path,
filepath: doc.path,
@ -709,12 +727,13 @@ export default class DocsService {
await db.exec("PRAGMA busy_timeout = 3000;");
await runSqliteMigrations(db);
// First create the table if it doesn't exist
await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title STRING NOT NULL,
startUrl STRING NOT NULL UNIQUE,
favicon STRING
startUrl STRING NOT NULL,
favicon STRING,
embeddingsProviderId STRING
)`);
this.sqliteDb = db;
@ -724,10 +743,17 @@ export default class DocsService {
}
async getFavicon(startUrl: string) {
if (!this.config.embeddingsProvider) {
console.warn(
"Attempting to get favicon without embeddings provider specified",
);
return;
}
const db = await this.getOrCreateSqliteDb();
const result = await db.get(
`SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
`SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
);
if (!result) {
@ -740,9 +766,10 @@ export default class DocsService {
Sync with no embeddings provider change
Ignores pre-indexed docs
*/
private async syncDocsOnConfigUpdate(
private async syncDocs(
oldConfig: ContinueConfig | undefined,
newConfig: ContinueConfig,
reindex: boolean,
) {
try {
this.isSyncing = true;
@ -752,6 +779,7 @@ export default class DocsService {
const newConfigDocs = newConfig.docs || [];
const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl);
// NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here
const currentlyIndexedDocs = await this.listMetadata();
const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
@ -774,7 +802,9 @@ export default class DocsService {
const oldConfigDoc = oldConfigDocs.find(
(d) => d.startUrl === doc.startUrl,
);
// const currentStatus = this.statuses.get(doc.startUrl);
if (
// currentStatus?.status === "complete" &&
oldConfigDoc &&
(oldConfigDoc.maxDepth !== doc.maxDepth ||
oldConfigDoc.title !== doc.title ||
@ -862,9 +892,7 @@ export default class DocsService {
return name.replace(/[^a-zA-Z0-9_.-]/g, "_");
}
private async getLanceTableNameFromEmbeddingsProvider(
isPreIndexedDoc: boolean,
) {
private async getLanceTableName(isPreIndexedDoc: boolean) {
const embeddingsProvider =
await this.getEmbeddingsProvider(isPreIndexedDoc);
@ -885,7 +913,7 @@ export default class DocsService {
const conn = await lancedb.connect(getLanceDbPath());
const tableNames = await conn.tableNames();
const tableNameFromEmbeddingsProvider =
await this.getLanceTableNameFromEmbeddingsProvider(!!isPreIndexedDoc);
await this.getLanceTableName(!!isPreIndexedDoc);
if (!tableNames.includes(tableNameFromEmbeddingsProvider)) {
if (initializationVector) {
@ -942,24 +970,35 @@ export default class DocsService {
}: AddParams) {
const db = await this.getOrCreateSqliteDb();
await db.run(
`INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon) VALUES (?, ?, ?)`,
`INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`,
title,
startUrl,
favicon,
this.config.embeddingsProvider.embeddingId,
);
}
private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
// Handles the case where a user has manually added the doc to config.json
// so it already exists in the file
const doesDocExist = this.config.docs?.some(
(doc) => doc.startUrl === siteIndexingConfig.startUrl,
const doesEquivalentDocExist = this.config.docs?.some(
(doc) =>
doc.startUrl === siteIndexingConfig.startUrl &&
doc.faviconUrl === siteIndexingConfig.faviconUrl &&
siteIndexingConfig.title === doc.title,
// siteIndexingConfig.maxDepth === doc.maxDepth &&
// doc.rootUrl === siteIndexingConfig.rootUrl,
);
if (!doesDocExist) {
if (!doesEquivalentDocExist) {
editConfigJson((config) => ({
...config,
docs: [...(config.docs ?? []), siteIndexingConfig],
docs: [
...(config.docs?.filter(
(doc) => doc.startUrl !== siteIndexingConfig.startUrl,
) ?? []),
siteIndexingConfig,
],
}));
}
}
@ -979,10 +1018,18 @@ export default class DocsService {
}
private async deleteMetadataFromSqlite(startUrl: string) {
if (!this.config.embeddingsProvider) {
console.warn(
`Attempting to delete metadata for ${startUrl} without embeddings provider specified`,
);
return;
}
const db = await this.getOrCreateSqliteDb();
await db.run(
`DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
`DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
);
}
@ -1010,34 +1057,4 @@ export default class DocsService {
this.deleteFromConfig(startUrl);
this.messenger?.send("refreshSubmenuItems", undefined);
}
/**
* Currently this deletes re-crawls + re-indexes all docs.
* A more optimal solution in the future will be to create
* a per-embeddings-provider table for docs.
*/
private async reindexDocsOnNewEmbeddingsProvider() {
// We use config as our source of truth here since it contains additional information
// needed for re-crawling such as `faviconUrl` and `maxDepth`.
const { docs, embeddingsProvider } = this.config;
if (!docs || docs.length === 0) {
return;
}
console.log(
`Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.embeddingId}`,
);
await Promise.allSettled(docs.map((doc) => this.indexAndAdd(doc)));
// Important that this only is invoked after we have successfully
// cleared and reindex the docs so that the table cannot end up in an
// invalid state.
this.globalContext.update(
"curEmbeddingsProviderId",
embeddingsProvider.embeddingId,
);
console.log("Completed reindexing of all non-preindexed docs");
}
}

View file

@ -27,41 +27,65 @@ export async function runLanceMigrations(table: Table) {
export async function runSqliteMigrations(db: Database) {
await new Promise((resolve) => {
migrate(
void migrate(
"sqlite_modify_docs_columns_and_copy_to_config",
async () => {
try {
const pragma = await db.all(
`PRAGMA table_info(${DocsService.sqlitebTableName})`,
`PRAGMA table_info(${DocsService.sqlitebTableName});`,
);
const hasFaviconCol = pragma.some(
(pragma) => pragma.name === "favicon",
);
if (!hasFaviconCol) {
await db.exec(
`ALTER TABLE ${DocsService.sqlitebTableName} ADD COLUMN favicon BLOB;`,
);
}
const hasBaseUrlCol = pragma.some(
(pragma) => pragma.name === "baseUrl",
);
if (!hasFaviconCol) {
await db.exec(
`ALTER TABLE ${DocsService.sqlitebTableName} ADD COLUMN favicon BLOB`,
);
}
if (hasBaseUrlCol) {
await db.exec(
`ALTER TABLE ${DocsService.sqlitebTableName} RENAME COLUMN baseUrl TO startUrl`,
`ALTER TABLE ${DocsService.sqlitebTableName} RENAME COLUMN baseUrl TO startUrl;`,
);
}
const sqliteDocs = await db.all<
Array<Pick<SqliteDocsRow, "title" | "startUrl">>
>(`SELECT title, startUrl FROM ${DocsService.sqlitebTableName}`);
const needsToUpdateConfig = !hasFaviconCol || hasBaseUrlCol;
if (needsToUpdateConfig) {
const sqliteDocs = await db.all<
Array<Pick<SqliteDocsRow, "title" | "startUrl">>
>(`SELECT title, startUrl FROM ${DocsService.sqlitebTableName}`);
editConfigJson((config) => ({
...config,
docs: [...(config.docs || []), ...sqliteDocs],
}));
}
} finally {
resolve(undefined);
}
},
() => resolve(undefined),
);
});
editConfigJson((config) => ({
...config,
docs: [...(config.docs || []), ...sqliteDocs],
}));
await new Promise((resolve) => {
void migrate(
"sqlite_delete_docs_with_no_embeddingsProviderId",
async () => {
try {
const pragma = await db.all(
`PRAGMA table_info(${DocsService.sqlitebTableName});`,
);
const hasEmbeddingsProviderColumn = pragma.some(
(pragma) => pragma.name === "embeddingsProviderId",
);
if (!hasEmbeddingsProviderColumn) {
// gotta just delete in this case since old docs will be unusable anyway
await db.exec(`DROP TABLE ${DocsService.sqlitebTableName};`);
}
} finally {
resolve(undefined);
}

View file

@ -41,6 +41,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
"openai",
"ollama",
"together",
"novita",
"msty",
"anthropic",
"bedrock",
@ -130,6 +131,7 @@ const PARALLEL_PROVIDERS: string[] = [
"free-trial",
"replicate",
"together",
"novita",
"sambanova",
"nebius",
"vertexai",

View file

@ -10,7 +10,7 @@ class Anthropic extends BaseLLM {
contextLength: 200_000,
completionOptions: {
model: "claude-3-5-sonnet-latest",
maxTokens: 4096,
maxTokens: 8192,
},
apiBase: "https://api.anthropic.com/v1/",
};

44
core/llm/llms/Novita.ts Normal file
View file

@ -0,0 +1,44 @@
import OpenAI from "./OpenAI.js";
import type { CompletionOptions, LLMOptions } from "../../index.js";
class Novita extends OpenAI {
static providerName = "novita";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.novita.ai/v3/openai/",
};
private static MODEL_IDS: { [name: string]: string } = {
"llama3-8b": "meta-llama/llama-3-8b-instruct",
"llama3-70b": "meta-llama/llama-3-70b-instruct",
"llama3.1-8b": "meta-llama/llama-3.1-8b-instruct",
"llama3.1-70b": "meta-llama/llama-3.1-70b-instruct",
"llama3.1-405b": "meta-llama/llama-3.1-405b-instruct",
"llama3.2-1b": "meta-llama/llama-3.2-1b-instruct",
"llama3.2-3b": "meta-llama/llama-3.2-3b-instruct",
"llama3.2-11b": "meta-llama/llama-3.2-11b-vision-instruct",
"llama3.3-70b": "meta-llama/llama-3.3-70b-instruct",
"mistral-nemo": "mistralai/mistral-nemo",
"mistral-7b": "mistralai/mistral-7b-instruct",
};
protected _convertModelName(model: string) {
return Novita.MODEL_IDS[model] || this.model;
}
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const chunk of this._legacystreamComplete(
prompt,
signal,
options,
)) {
yield chunk;
}
}
}
export default Novita;

View file

@ -48,6 +48,7 @@ import ContinueProxy from "./stubs/ContinueProxy";
import TestLLM from "./Test";
import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
import Novita from "./Novita";
import VertexAI from "./VertexAI";
import Vllm from "./Vllm";
import WatsonX from "./WatsonX";
@ -65,6 +66,7 @@ export const LLMClasses = [
Replicate,
TextGenWebUI,
Together,
Novita,
HuggingFaceTGI,
HuggingFaceInferenceAPI,
Kindo,

View file

@ -6,6 +6,7 @@ import type {
ChatMessage,
ContextItem,
ContextItemWithId,
ContextProviderWithParams,
ContextSubmenuItem,
DiffLine,
FileSymbolMap,
@ -22,10 +23,26 @@ import type {
} from "../";
import { ConfigResult } from "../config/load";
export type ProtocolGeneratorType<T> = AsyncGenerator<{
export type ProtocolGeneratorYield<T> = {
done?: boolean;
content: T;
}>;
};
export type ProtocolGeneratorType<Y> = AsyncGenerator<
ProtocolGeneratorYield<Y>
>;
export type AsyncGeneratorYieldType<T> =
T extends AsyncGenerator<infer Y, any, any>
? Y extends ProtocolGeneratorYield<infer PR>
? PR
: never
: never;
// export type AsyncGeneratorReturnType<T> =
// T extends AsyncGenerator<any, infer R, any>
// ? R extends ProtocolGeneratorYield<infer PR>
// ? PR
// : never
// : never;
export type OnboardingModes =
| "Local"
@ -70,6 +87,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
];
"config/deleteModel": [{ title: string }, void];
"config/addContextProvider": [ContextProviderWithParams, void];
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
"config/listProfiles": [undefined, ProfileDescription[]];
"config/openProfile": [{ profileId: string | undefined }, void];
@ -193,4 +211,5 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{ toolCall: ToolCall; selectedModelTitle: string },
{ contextItems: ContextItem[] },
];
"clipboardCache/add": [{ content: string }, void];
};

View file

@ -43,7 +43,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
vscMediaUrl: string;
},
];
"jetbrains/getColors": [undefined, void];
"jetbrains/getColors": [undefined, Record<string, string>];
"vscode/openMoveRightMarkdown": [undefined, void];
setGitHubAuthToken: [{ token: string }, void];
acceptDiff: [{ filepath: string; streamId?: string }, void];

View file

@ -16,6 +16,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"history/save",
"devdata/log",
"config/addModel",
"config/addContextProvider",
"config/newPromptFile",
"config/ideSettingsUpdate",
"config/getSerializedProfileInfo",
@ -60,6 +61,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
];
// Message types to pass through from core to webview
// Note: If updating these values, make a corresponding update in
// extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt
export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
[
"configUpdate",

View file

@ -3,13 +3,13 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils";
import { ToolImpl } from ".";
export const createNewFileImpl: ToolImpl = async (args, extras) => {
const resolvedFilepath = await inferResolvedUriFromRelativePath(
const resolvedFileUri = await inferResolvedUriFromRelativePath(
args.filepath,
extras.ide,
);
if (resolvedFilepath) {
await extras.ide.writeFile(resolvedFilepath, args.contents);
await extras.ide.openFile(resolvedFilepath);
if (resolvedFileUri) {
await extras.ide.writeFile(resolvedFileUri, args.contents);
await extras.ide.openFile(resolvedFileUri);
}
return [];
};

View file

@ -75,7 +75,7 @@ describe("GlobalContext", () => {
const value = globalContext.get("indexingPaused");
expect(value).toBeUndefined();
expect(consoleWarnMock).toHaveBeenCalledWith(
expect.stringContaining("Error parsing global context")
expect.stringContaining("Error parsing global context"),
);
// Clean up
@ -99,7 +99,7 @@ describe("GlobalContext", () => {
expect(value).toBeUndefined();
expect(consoleWarnMock).toHaveBeenCalledWith(
expect.stringContaining("Error updating global context")
expect.stringContaining("Error updating global context"),
);
// Clean up
@ -113,10 +113,10 @@ describe("GlobalContext", () => {
expect(globalContext.get("indexingPaused")).toBe(true);
expect(globalContext.get("selectedTabAutocompleteModel")).toBe(
"test-model"
"test-model",
);
expect(globalContext.get("hasDismissedConfigTsNoticeJetBrains")).toBe(
false
false,
);
});
@ -125,16 +125,7 @@ describe("GlobalContext", () => {
expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(true);
});
it("should handle curEmbeddingsProviderId correctly", () => {
globalContext.update("curEmbeddingsProviderId", "test-provider-id");
expect(globalContext.get("curEmbeddingsProviderId")).toBe(
"test-provider-id"
);
});
it("should not crash or throw when getting a key that hasn't been set", () => {
expect(
globalContext.get("hasAlreadyCreatedAPromptFile")
).toBeUndefined();
expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBeUndefined();
});
});
});

View file

@ -12,7 +12,6 @@ export type GlobalContextType = {
*
* For VS Code users, it is unnecessary since we use transformers.js by default.
*/
curEmbeddingsProviderId: string;
hasDismissedConfigTsNoticeJetBrains: boolean;
hasAlreadyCreatedAPromptFile: boolean;
showConfigUpdateToast: boolean;

View file

@ -0,0 +1,54 @@
class ClipboardCache {
private cache: Map<string, string>;
private order: string[];
private readonly maxSize = 30;
constructor() {
this.cache = new Map();
this.order = [];
}
add(id: string, content: string): void {
if (!content) {
return;
}
if (this.order.length >= this.maxSize) {
const oldest = this.order.pop();
if (oldest) {
this.cache.delete(oldest);
}
}
this.cache.set(id, content);
this.order.unshift(id);
}
getNItems(count: number): {
id: string;
content: string;
}[] {
return this.order.slice(0, count).map((id) => ({
id,
content: this.cache.get(id) || "",
}));
}
get(id: string): string | undefined {
return this.cache.get(id);
}
select(id: string): void {
const index = this.order.indexOf(id);
if (index > -1) {
this.order.splice(index, 1);
this.order.unshift(id);
}
}
clear(): void {
this.cache.clear();
this.order = [];
}
}
export const clipboardCache = new ClipboardCache();

View file

@ -1,6 +1,10 @@
import { IDE } from "..";
import { joinPathsToUri, pathToUriPathSegment } from "./uri";
import {
joinEncodedUriPathSegmentToUri,
joinPathsToUri,
pathToUriPathSegment,
} from "./uri";
/*
This function takes a relative (to workspace) filepath
@ -30,7 +34,7 @@ export async function resolveRelativePathInDir(
If no meaninful path match just concatenates to first dir's uri
*/
export async function inferResolvedUriFromRelativePath(
path: string,
relativePath: string,
ide: IDE,
dirCandidates?: string[],
): Promise<string> {
@ -40,7 +44,7 @@ export async function inferResolvedUriFromRelativePath(
throw new Error("inferResolvedUriFromRelativePath: no dirs provided");
}
const segments = pathToUriPathSegment(path).split("/");
const segments = pathToUriPathSegment(relativePath).split("/");
// Generate all possible suffixes from shortest to longest
const suffixes: string[] = [];
for (let i = segments.length - 1; i >= 0; i--) {
@ -51,7 +55,7 @@ export async function inferResolvedUriFromRelativePath(
for (const suffix of suffixes) {
const uris = dirs.map((dir) => ({
dir,
partialUri: joinPathsToUri(dir, suffix),
partialUri: joinEncodedUriPathSegmentToUri(dir, suffix),
}));
const promises = uris.map(async ({ partialUri, dir }) => {
const exists = await ide.fileExists(partialUri);
@ -67,15 +71,13 @@ export async function inferResolvedUriFromRelativePath(
// If exactly one directory matches, use it
if (existingUris.length === 1) {
return joinPathsToUri(existingUris[0].dir, segments.join("/"));
return joinEncodedUriPathSegmentToUri(
existingUris[0].dir,
segments.join("/"),
);
}
}
// If no unique match found, use the first directory
return joinPathsToUri(dirs[0], path);
}
interface ResolveResult {
resolvedUri: string;
matchedDir: string;
return joinPathsToUri(dirs[0], relativePath);
}

View file

@ -1,9 +1,7 @@
// Generated by continue
import * as URI from "uri-js";
import {
pathToUriPathSegment,
findUriInDirs,
relativePathOrUriToUri,
getUriPathBasename,
getUriFileExtension,
getFileExtensionFromBasename,
@ -141,26 +139,6 @@ describe("uri utils", () => {
});
});
describe("relativePathOrUriToUri", () => {
const consoleSpy = jest.spyOn(console, "trace").mockImplementation();
afterEach(() => {
consoleSpy.mockClear();
});
it("should return original URI if scheme exists", () => {
const uri = "file:///path/to/file.txt";
expect(relativePathOrUriToUri(uri, "file:///base")).toBe(uri);
});
it("should convert relative path to URI", () => {
expect(relativePathOrUriToUri("path/to/file.txt", "file:///base")).toBe(
"file:///base/path/to/file.txt",
);
expect(consoleSpy).toHaveBeenCalledWith("Received path with no scheme");
});
});
describe("getLastNUriRelativePathParts", () => {
it("should get last N parts of URI relative path", () => {
const dirUris = ["file:///workspace/project1"];

View file

@ -5,23 +5,21 @@ import * as URI from "uri-js";
\this\is\afile.ts -> this/is/afile.ts
is/already/clean -> is/already/clean
**/
export function pathToUriPathSegment(path: string) {
let clean = path.replace(/[\\]/g, "/"); // backslashes -> forward slashes
clean = clean.replace(/^\//, ""); // remove start slash
clean = clean.replace(/\/$/, ""); // remove end slash
return clean
.split("/")
.map((segment) => encodeURIComponent(segment))
.map((part) => encodeURIComponent(part))
.join("/");
}
export function getCleanUriPath(uri: string) {
const path = URI.parse(uri).path;
if (!path) {
return "";
}
return pathToUriPathSegment(path);
const path = URI.parse(uri).path ?? "";
let clean = path.replace(/^\//, ""); // remove start slash
clean = clean.replace(/\/$/, ""); // remove end slash
return clean;
}
export function findUriInDirs(
@ -36,6 +34,7 @@ export function findUriInDirs(
if (!uriComps.scheme) {
throw new Error(`Invalid uri: ${uri}`);
}
const uriPathParts = getCleanUriPath(uri).split("/");
for (const dir of dirUriCandidates) {
const dirComps = URI.parse(dir);
@ -51,14 +50,7 @@ export function findUriInDirs(
// file:///folder/file is not within file:///fold
// At this point we break the path up and check if each dir path part matches
const dirPathParts = (dirComps.path ?? "")
.replace(/^\//, "")
.split("/")
.map((part) => encodeURIComponent(part));
const uriPathParts = (uriComps.path ?? "")
.replace(/^\//, "")
.split("/")
.map((part) => encodeURIComponent(part));
const dirPathParts = getCleanUriPath(dir).split("/");
if (uriPathParts.length < dirPathParts.length) {
continue;
@ -70,7 +62,10 @@ export function findUriInDirs(
}
}
if (allDirPartsMatch) {
const relativePath = uriPathParts.slice(dirPathParts.length).join("/");
const relativePath = uriPathParts
.slice(dirPathParts.length)
.map(decodeURIComponent)
.join("/");
return {
uri,
relativePathOrBasename: relativePath,
@ -86,28 +81,13 @@ export function findUriInDirs(
};
}
/*
To smooth out the transition from path to URI will use this function to warn when path is used
This will NOT work consistently with full OS paths like c:\blah\blah or ~/Users/etc
*/
export function relativePathOrUriToUri(
relativePathOrUri: string,
defaultDirUri: string,
): string {
const out = URI.parse(relativePathOrUri);
if (out.scheme) {
return relativePathOrUri;
}
console.trace("Received path with no scheme");
return joinPathsToUri(defaultDirUri, out.path ?? "");
}
/*
Returns just the file or folder name of a URI
*/
export function getUriPathBasename(uri: string): string {
const cleanPath = getCleanUriPath(uri);
return cleanPath.split("/")?.pop() || "";
const path = getCleanUriPath(uri);
const basename = path.split("/").pop() || "";
return decodeURIComponent(basename);
}
export function getFileExtensionFromBasename(basename: string) {
@ -142,6 +122,15 @@ export function joinPathsToUri(uri: string, ...pathSegments: string[]) {
return URI.serialize(components);
}
export function joinEncodedUriPathSegmentToUri(
uri: string,
pathSegment: string,
) {
const components = URI.parse(uri);
components.path = `${components.path}/${pathSegment}`;
return URI.serialize(components);
}
export function getShortestUniqueRelativeUriPaths(
uris: string[],
dirUriCandidates: string[],
@ -153,8 +142,7 @@ export function getShortestUniqueRelativeUriPaths(
const segmentCombinationsMap = new Map<string, number>();
const segmentsInfo = uris.map((uri) => {
const { relativePathOrBasename } = findUriInDirs(uri, dirUriCandidates);
const cleanPath = pathToUriPathSegment(relativePathOrBasename);
const segments = cleanPath.split("/");
const segments = relativePathOrBasename.split("/");
const suffixes: string[] = [];
// Generate all possible suffix combinations, starting from the shortest (basename)
@ -168,18 +156,19 @@ export function getShortestUniqueRelativeUriPaths(
);
}
return { uri, segments, suffixes, cleanPath };
return { uri, segments, suffixes, relativePathOrBasename };
});
// Find shortest unique path for each URI
return segmentsInfo.map(({ uri, suffixes, cleanPath }) => {
return segmentsInfo.map(({ uri, suffixes, relativePathOrBasename }) => {
// Since suffixes are now ordered from shortest to longest,
// the first unique one we find will be the shortest
const uniqueCleanPath =
const uniquePath =
suffixes.find((suffix) => segmentCombinationsMap.get(suffix) === 1) ??
cleanPath; // fallback to full path if no unique suffix found
return { uri, uniquePath: decodeURIComponent(uniqueCleanPath) };
relativePathOrBasename; // fallback to full path if no unique suffix found
return { uri, uniquePath };
});
}
// Only used when working with system paths and relative paths
// Since doesn't account for URI segements before workspace
export function getLastNPathParts(filepath: string, n: number): string {

View file

@ -5,6 +5,10 @@ keywords: [model, autocomplete]
sidebar_position: 2
---
:::info
This page recommends models and providers for Autocomplete. Read more about how to set up your `config.json` [here](../reference.md).
:::
## Best overall experience
For the best Autocomplete experience, we recommend using Codestral through the [Mistral API](https://console.mistral.ai/). This model offers high-quality completions with an excellent understanding of code context:
@ -26,26 +30,39 @@ The API keys for Codestral and the general Mistral APIs are different. If you ar
## Local, offline / self-hosted experience
For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users:
For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users (e.g. using [Ollama](../customize/model-providers/top-level/ollama.md) or [LM Studio](../customize/model-providers/more/lmstudio.md)).
```json title="config.json""
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"model": "qwen2.5-coder:1.5b",
"model": "qwen2.5-coder:1.5b-base",
"provider": "ollama"
}
}
```
Have more compute? Use `qwen2.5-coder:7b` for potentially higher-quality suggestions.
Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality suggestions.
:::note
For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/wen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration.
For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration.
:::
### Using a remote instance
When using a remote instance you need to set the `"apiBase"` value in the configuration:
```json title="config.json""
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"model": "qwen2.5-coder:1.5b-base",
"provider": "ollama"
"apiBase": "http://<my endpoint>:11434"
}
}
```
## Other experiences
There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md).
There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md). You can also see more examples of Autocomplete configuration [here](../customize/deep-dives/autocomplete.md)

View file

@ -15,7 +15,7 @@ The highlighted code you’ve selected by pressing <kbd>cmd/ctrl</kbd> + <kbd>L<
## Active file
You can include the currently open file as context by pressing <kbd>cmd</kbd> + <kbd>opt</kbd> + <kbd>enter</kbd> (Mac) or <kbd>ctrl</kbd> + <kbd>alt</kbd> + <kbd>enter</kbd> (Windows) when you send your request.
You can include the currently open file as context by pressing <kbd>opt</kbd> + <kbd>enter</kbd> (Mac) or <kbd>alt</kbd> + <kbd>enter</kbd> (Windows) when you send your request at Chat window(Prompt can't be empty).
## Specific file

View file

@ -82,18 +82,6 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your
]
```
</TabItem>
<TabItem value="Nebius">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 405B",
"provider": "nebius",
"model": "llama3.1-405b",
"apiKey": "[NEBIUS_API_KEY]"
}
]
```
</TabItem>
</Tabs>
### GPT-4o from OpenAI

View file

@ -576,6 +576,20 @@ The response 200 OK should be a JSON object with the following structure:
}
```
### `@Clipboard`
Reference recent clipboard items
```json title="config.json"
{
"contextProviders": [
{
"name": "clipboard"
}
]
}
```
### Requesting Context Providers
Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider.

View file

@ -23,7 +23,7 @@ If you want to have the best autocomplete experience, we recommend using Codestr
If you'd like to run your autocomplete model locally, we recommend using Ollama. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model:
```bash
ollama run qwen2.5-coder:1.5b
ollama run qwen2.5-coder:1.5b-base
```
Once it has been downloaded, you should begin to see completions in VS Code.
@ -37,7 +37,7 @@ All of the configuration options available for chat models are available to use
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
},
...
@ -76,7 +76,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
},
"tabAutocompleteOptions": {
@ -99,7 +99,7 @@ Follow these steps to ensure that everything is set up correctly:
1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar, and in JetBrains by going to Settings -> Tools -> Continue).
2. Make sure you have downloaded Ollama.
3. Run `ollama run qwen2.5-coder:1.5b` to verify that the model is downloaded.
3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded.
4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere.
5. Check the output of the logs to find any potential errors: <kbd>cmd/ctrl</kbd> + <kbd>shift</kbd> + <kbd>P</kbd> -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains.
6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use <kbd>cmd/ctrl</kbd> + <kbd>,</kbd> then search for this and check the box)

View file

@ -46,7 +46,7 @@ We recommend configuring **rerank-english-v3.0** as your reranking model.
```json title="config.json"
{
"reranker": {
"provider": "cohere",
"name": "cohere",
"params": {
"model": "rerank-english-v3.0",
"apiKey": "<COHERE_API_KEY>"

View file

@ -1,6 +1,6 @@
# Kindo
Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create your API key on the [API keys page](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the [plugins tab](https://app.kindo.ai/plugins).
Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create an API key in [Settings > API > API Keys](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the "Available Models" tab or copy and paste the config in [Plugins > Your Configuration](https://app.kindo.ai/plugins).
## Config Example
@ -10,7 +10,7 @@ Kindo offers centralized control over your organization's AI operations, ensurin
{
"title": "Claude 3.5 Sonnet",
"provider": "kindo",
"model": "claude-3-5-sonnet-20240620",
"model": "claude-3-5-sonnet",
"apiKey": "<KINDO_API_KEY>"
}
]
@ -26,13 +26,8 @@ Kindo offers centralized control over your organization's AI operations, ensurin
"title": "WhiteRabbitNeo",
"provider": "kindo",
"model": "/models/WhiteRabbitNeo-33B-DeepSeekCoder",
"apiKey": "<KINDO_API_KEY>"
},
{
"title": "DeepSeek",
"provider": "kindo",
"model": "deepseek-ai/deepseek-coder-33b-instruct",
"apiKey": "<KINDO_API_KEY>"
"apiKey": "<KINDO_API_KEY>",
"template": "none"
}
]
}

View file

@ -0,0 +1,18 @@
# Novita
[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) offers an affordable, reliable, and simple inference platform with scalable [LLM API](https://novita.ai/docs/model-api/reference/introduction.html), empowering developers to build AI applications. Try the [Novita AI Llama 3 API Demo](https://novita.ai/model-api/product/llm-api/playground/meta-llama-llama-3.1-70b-instruct?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) today!. You can sign up [here](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), copy your API key on the [Key Management](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), and then hit the play button on any model from the [Novita AI Models list](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link). Change `~/.continue/config.json` to look like this:
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 8B",
"provider": "novita",
"model": "meta-llama/llama-3.1-8b-instruct",
"apiKey": "YOUR_API_KEY"
}
]
}
```
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Novita.ts)

View file

@ -1,22 +1,59 @@
# vLLM
Run the OpenAI-compatible server by vLLM using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/models/engine_args.html).
vLLM is an open-source library for fast LLM inference which typically is used to serve multiple users at the same. It can also be used to run a large model on multiple GPU:s (e.g. when it doesn´t fit in a single GPU). Run their OpenAI-compatible server using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/usage/engine_args.html).
```shell
vllm serve NousResearch/Meta-Llama-3-8B-Instruct --max-model-len 1024
vllm serve meta-llama/Meta-Llama-3.1-8B-Instruct
```
## Chat model
The continue implementation uses [OpenAI](../top-level/openai.md) under the hood and automatically selects the available model. You only need to set the `apiBase` like this:
We recommend configuring **Llama3.1 8B** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "My vLLM OpenAI-compatible server",
"apiBase": "http://localhost:8000/v1"
"title": "Llama3.1 8B Instruct",
"provider": "vllm",
"model": "meta-llama/Meta-Llama-3.1-8B-Instruct"
"apiBase": "http://<vllm chat endpoint>/v1"
}
]
}
```
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts)
## Autocomplete model
We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model.
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"provider": "vllm",
"model": "Qwen/Qwen2.5-Coder-1.5B"
"apiBase": "http://<vllm autocomplete endpoint>/v1"
}
}
```
## Embeddings model
We recommend configuring **Nomic Embed Text** as your embeddings model.
```json title="config.json"
{
"embeddingsProvider": {
"provider": "vllm",
"model": "nomic-ai/nomic-embed-text-v1"
"apiBase": "http://<vllm embed endpoint>/v1"
}
}
```
## Reranking model
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
The continue implementation uses [OpenAI](../top-level/openai.md) under the hood. [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts)

View file

@ -22,6 +22,22 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model.
]
}
```
> If you run into the following error when connecting to the new Claude 3.5 Sonnet 2 models from AWS - `400 Invocation of model ID anthropic.claude-3-5-sonnet-20241022-v2:0 with on-demand throughput isn’t supported. Retry your request with the ID or ARN of an inference profile that contains this model.`
> You can fix this using the following config.json
```json title="config.json"
{
"models": [
{
"title": "Claude 3.5 Sonnet",
"provider": "bedrock",
"model": "us.anthropic.claude-3-5-sonnet-20241022-v2:0",
"region": "us-east-1",
"profile": "bedrock"
}
]
}
```
## Autocomplete model

View file

@ -30,7 +30,7 @@ We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model.
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b"
"model": "qwen2.5-coder:1.5b-base"
}
}
```
@ -53,3 +53,20 @@ We recommend configuring **Nomic Embed Text** as your embeddings model.
Ollama currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
## Using a remote instance
To configure a remote instance of Ollama, add the `"apiBase"` property to your model in config.json:
```json title="config.json"
{
"models": [
{
"title": "Llama3.1 8B",
"provider": "ollama",
"model": "llama3.1:8b"
"apiBase": "http://<my endpoint>:11434"
}
]
}
```

View file

@ -1,7 +1,7 @@
---
title: Using Llama 3.1 with Continue
description: How to use Llama 3.1 with Continue
keywords: [llama, meta, togetherai, ollama, replicate]
keywords: [llama, meta, togetherai, novita, ollama, replicate]
---
Continue makes it easy to code with the latest open-source models, including the entire Llama 3.1 family of models. Llama 3.2 models are also supported but not recommended for chat, because they are specifically designed to be small or multi-modal.

View file

@ -18,7 +18,7 @@ If you have any problems, see the [troubleshooting guide](troubleshooting.md) or
## JetBrains
1. Open your JetBrains IDE and open **Settings** using <kbd>Ctrl</kbd> + <kbd>+Alt</kbd> + <kbd>S</kbd>
1. Open your JetBrains IDE and open **Settings** using <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>S</kbd>
2. Select **Plugins** on the sidebar and search for "Continue" in the marketplace
3. Click `Install`, which will cause the Continue logo to show up on the right toolbar

View file

@ -88,7 +88,7 @@ Specifies options for tab autocompletion behavior.
- `debounceDelay`: Delay (in ms) before triggering autocomplete.
- `maxSuffixPercentage`: Maximum percentage of prompt for suffix.
- `prefixPercentage`: Percentage of input for prefix.
- `template`: Template string for autocomplete, using Mustache templating.
- `template`: Template string for autocomplete, using Mustache templating. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables.
- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`).
- `useCache`: If `true`, caches completions.
- `onlyMyCode`: If `true`, only includes code within the repository.

View file

@ -388,7 +388,11 @@ const config = {
},
{
to: "/customize/model-providers/more/together",
from: "/reference/Model Providers/togetherllm",
from: "/reference/Model Providers/together",
},
{
to: "/customize/model-providers/more/novita",
from: "/reference/Model Providers/novita",
},
{
to: "/customize/model-providers/more/vllm",

View file

@ -33,7 +33,7 @@ import TabItem from "@theme/TabItem";
### 来自 Meta 的 Llama 3.1 405B
如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md) 或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。
如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md)或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。
<Tabs groupId="providers">
<TabItem value="Together">
@ -48,6 +48,18 @@ import TabItem from "@theme/TabItem";
]
```
</TabItem>
<TabItem value="Novita">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 405B",
"provider": "novita",
"model": "meta-llama/llama-3.1-405b-instruct",
"apiKey": "[NOVITA_API_KEY]"
}
]
```
</TabItem>
<TabItem value="Groq">
```json title="config.json"
"models": [

View file

@ -0,0 +1,18 @@
# Novita
[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) 提供了一个经济实惠、可靠且简单的推理平台。你可以在 [这里](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) 注册,在 [Key Management](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)复制你的 API key ,然后在 [Novita 模型列表](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) 的任何模型上点击 Try it now 按钮。修改 `~/.continue/config.json` 像这样:
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 8b",
"provider": "Novita",
"model": "meta-llama/llama-3.1-8b-instruct",
"apiKey": "YOUR_API_KEY"
}
]
}
```
[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/Novita.ts)

View file

@ -1,7 +1,7 @@
---
title: Continue 使用 Llama 3.1
description: Continue 如何使用 Llama 3.1
keywords: [llama, meta, togetherai, ollama, replicate]
keywords: [llama, meta, togetherai, novita, ollama, replicate]
---
Continue 让使用最新的开元模型编码变得简单,包括整个 Llama 3.1 家族模型。

View file

@ -3,4 +3,6 @@ src/main/resources/webview
src/main/resources/bin
src/main/resources/config_schema.json
src/main/resources/continue_rc_schema.json
video
video
src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/*
!src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json

View file

@ -1,25 +0,0 @@
<!--<component name="ProjectRunConfigurationManager">-->
<!-- <configuration default="false" name="Run IDE for UI Tests" type="GradleRunConfiguration" factoryName="Gradle">-->
<!-- <log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />-->
<!-- <ExternalSystemSettings>-->
<!-- <option name="executionName" />-->
<!-- <option name="externalProjectPath" value="$PROJECT_DIR$" />-->
<!-- <option name="externalSystemIdString" value="GRADLE" />-->
<!-- <option name="scriptParameters" value="" />-->
<!-- <option name="taskDescriptions">-->
<!-- <list />-->
<!-- </option>-->
<!-- <option name="taskNames">-->
<!-- <list>-->
<!-- <option value="runIdeForUiTests" />-->
<!-- </list>-->
<!-- </option>-->
<!-- <option name="vmOptions" />-->
<!-- </ExternalSystemSettings>-->
<!-- <ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>-->
<!-- <ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>-->
<!-- <DebugAllEnabled>false</DebugAllEnabled>-->
<!-- <RunAsTest>false</RunAsTest>-->
<!-- <method v="2" />-->
<!-- </configuration>-->
<!--</component>-->

View file

@ -0,0 +1,27 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Test IDE" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName"/>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij"/>
<option name="externalSystemIdString" value="GRADLE"/>
<option name="scriptParameters" value=""/>
<option name="taskDescriptions">
<list/>
</option>
<option name="taskNames">
<list>
<option value="runIdeForUiTests"/>
</list>
</option>
<option name="vmOptions"/>
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2">
<option name="Gradle.BeforeRunTask" enabled="true" tasks="clean"
externalProjectPath="$PROJECT_DIR$/extensions/intellij" vmOptions="" scriptParameters=""/>
</method>
</configuration>
</component>

View file

@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Tests" type="GradleRunConfiguration" factoryName="Gradle" focusToolWindowBeforeRun="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="test" />
</list>
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>

View file

@ -0,0 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run e2e tests" type="CompoundRunConfigurationType">
<toRun name="Run Test IDE" type="GradleRunConfiguration" />
<toRun name="Run Tests" type="GradleRunConfiguration" />
<method v="2" />
</configuration>
</component>

View file

@ -101,7 +101,9 @@ toolbar.
_Run | Debugging Actions | Reload Changed Classes`_
- This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension
- `gui`: Changes will be reloaded automatically
- `core`: Run `npm run build` from the `binary` directory (requires restarting the `Start Core Dev Server` task)
- `core`: Run `npm run build -- --os [darwin | linux | win32]` from the `binary` directory (requires
restarting the
`Start Core Dev Server` task)
### Setting breakpoints

View file

@ -130,7 +130,10 @@ tasks {
// Configure UI tests plugin
// Read more: https://github.com/JetBrains/intellij-ui-test-robot
runIdeForUiTests {
environment("CONTINUE_GLOBAL_DIR", "src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue")
environment(
"CONTINUE_GLOBAL_DIR",
"${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue"
)
systemProperty("robot-server.port", "8082")
systemProperty("ide.mac.message.dialogs.as.sheets", "false")
systemProperty("jb.privacy.policy.text", "<!--999.999-->")
@ -141,6 +144,7 @@ tasks {
systemProperty("idea.trust.all.projects", "true")
systemProperty("ide.show.tips.on.startup.default.value", "false")
systemProperty("ide.browser.jcef.jsQueryPoolSize", "10000")
systemProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
// This is to ensure we load the GUI with OSR enabled. We have logic that
// renders with OSR disabled below a particular IDE version.
@ -180,6 +184,5 @@ tasks {
test {
useJUnitPlatform()
environment("CONTINUE_GLOBAL_DIR", "src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue")
}
}

View file

@ -10,7 +10,7 @@ import com.github.continuedev.continueintellijextension.listeners.ContinuePlugin
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.services.SettingsListener
import com.intellij.openapi.Disposable
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
@ -162,7 +162,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
override fun after(events: List<VFileEvent>) {
// Collect all relevant URIs for deletions
val deletedURIs = events.filterIsInstance<VFileDeleteEvent>()
.map { event -> event.file.url }
.mapNotNull { event -> event.file.toUriOrNull() }
// Send "files/deleted" message if there are any deletions
if (deletedURIs.isNotEmpty()) {
@ -172,7 +172,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
// Collect all relevant URIs for content changes
val changedURIs = events.filterIsInstance<VFileContentChangeEvent>()
.map { event -> event.file.url }
.mapNotNull { event -> event.file.toUriOrNull() }
// Send "files/changed" message if there are any content changes
if (changedURIs.isNotEmpty()) {
@ -220,7 +220,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
// Reload the WebView
continuePluginService?.let { pluginService ->
val allModulePaths = ModuleManager.getInstance(project).modules
.flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.map { it.url } }
.flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } }
val topLevelModulePaths = allModulePaths
.filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } }

View file

@ -22,4 +22,4 @@ class AcceptAutocompleteAction : EditorAction(object : EditorActionHandler() {
&& autocompleteService.pendingCompletion?.text != null
return enabled
}
}) {}
})

View file

@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.autocomplete
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.github.continuedev.continueintellijextension.utils.uuid
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.application.*
@ -10,8 +11,10 @@ import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.InlayProperties
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.wm.WindowManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
@ -32,9 +35,24 @@ fun PsiElement.isInjectedText(): Boolean {
return false
}
fun Editor.addInlayElement(
lines: List<String>,
offset: Int,
properties: InlayProperties
) {
if (this is EditorImpl) {
if (lines[0].isNotEmpty()) {
inlayModel.addInlineElement(offset, properties, ContinueInlayRenderer(listOf(lines[0])))
}
if (lines.size > 1) {
inlayModel.addBlockElement(offset, properties, ContinueInlayRenderer(lines.drop(1)))
}
}
}
@Service(Service.Level.PROJECT)
class AutocompleteService(private val project: Project) {
var pendingCompletion: PendingCompletion? = null;
var pendingCompletion: PendingCompletion? = null
private val autocompleteLookupListener = project.service<AutocompleteLookupListener>()
private var widget: AutocompleteSpinnerWidget? = null
@ -66,12 +84,16 @@ class AutocompleteService(private val project: Project) {
// Request a completion from the core
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
val uri = virtualFile?.toUriOrNull() ?: return
val line = editor.caretModel.primaryCaret.logicalPosition.line
val column = editor.caretModel.primaryCaret.logicalPosition.column
val input = mapOf(
"completionId" to completionId,
"filepath" to virtualFile?.url,
"filepath" to uri,
"pos" to mapOf(
"line" to editor.caretModel.primaryCaret.logicalPosition.line,
"line" to line,
"character" to column
),
"recentlyEditedFiles" to emptyList<String>(),
@ -79,10 +101,6 @@ class AutocompleteService(private val project: Project) {
"clipboardText" to ""
)
val lineStart = editor.document.getLineStartOffset(editor.caretModel.primaryCaret.logicalPosition.line)
val lineEnd = editor.document.getLineEndOffset(editor.caretModel.primaryCaret.logicalPosition.line)
val lineLength = lineEnd - lineStart
project.service<ContinuePluginService>().coreMessenger?.request(
"autocomplete/complete",
input,
@ -95,9 +113,8 @@ class AutocompleteService(private val project: Project) {
val completion = completions[0].toString()
val finalTextToInsert = deduplicateCompletion(editor, offset, completion)
if (shouldRenderCompletion(finalTextToInsert, column, lineLength, editor)) {
if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) {
renderCompletion(editor, offset, finalTextToInsert)
pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert)
// Hide auto-popup
// AutoPopupController.getInstance(project).cancelAllRequests()
}
@ -106,13 +123,19 @@ class AutocompleteService(private val project: Project) {
)
}
private fun shouldRenderCompletion(completion: String, column: Int, lineLength: Int, editor: Editor): Boolean {
if (completion.isEmpty()) {
private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean {
if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) {
return false
}
if (completion.lines().size == 1) {
return true
}
val endOffset = editor.document.getLineEndOffset(line)
// Do not render if completion is multi-line and caret is in middle of line
return !(completion.lines().size > 1 && column < lineLength)
return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank()
}
private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String {
@ -120,13 +143,20 @@ class AutocompleteService(private val project: Project) {
return ApplicationManager.getApplication().runReadAction<String> {
val document = editor.document
val caretOffset = editor.caretModel.offset
// Don't care about it if it's at the end of the document
if (caretOffset == document.textLength) return@runReadAction completion
val N = 10
var textAfterCursor = if (caretOffset + N <= document.textLength) {
document.getText(com.intellij.openapi.util.TextRange(caretOffset, caretOffset + N))
document.getText(TextRange(caretOffset, caretOffset + N))
} else {
document.getText(com.intellij.openapi.util.TextRange(caretOffset, document.textLength))
document.getText(TextRange(caretOffset, document.textLength))
}
// Avoid truncating the completion text when the text after the cursor is blank
if (textAfterCursor.isBlank()) return@runReadAction completion
// Determine the index of a newline character within the text following the cursor.
val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n')
// If a newline character is found and the current line is not empty, truncate the text at that point.
@ -164,19 +194,9 @@ class AutocompleteService(private val project: Project) {
properties.relatesToPrecedingText(true)
properties.disableSoftWrapping(true)
if (completion.lines().size > 1) {
editor.inlayModel.addBlockElement(
offset,
properties,
ContinueMultilineCustomElementRenderer(editor, completion)
)
} else {
editor.inlayModel.addInlineElement(
offset,
properties,
ContinueCustomElementRenderer(editor, completion)
)
}
val lines = completion.lines()
pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n"))
editor.addInlayElement(lines, offset, properties)
// val attributes = TextAttributes().apply {
// backgroundColor = JBColor.GREEN
@ -204,7 +224,7 @@ class AutocompleteService(private val project: Project) {
({})
)
invokeLater {
clearCompletions(editor)
clearCompletions(editor, completion)
}
}
@ -267,44 +287,40 @@ class AutocompleteService(private val project: Project) {
project.service<ContinuePluginService>().coreMessenger?.request("autocomplete/cancel", null, null, ({}))
}
fun clearCompletions(editor: Editor) {
fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) {
if (isInjectedFile(editor)) return
if (pendingCompletion != null) {
cancelCompletion(pendingCompletion!!)
pendingCompletion = null
}
editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach {
if (it.renderer is ContinueCustomElementRenderer) {
it.dispose()
}
}
editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach {
if (it.renderer is ContinueMultilineCustomElementRenderer) {
it.dispose()
}
if (completion != null) {
cancelCompletion(completion)
if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null
}
disposeInlayRenderer(editor)
}
private fun isInjectedFile(editor: Editor): Boolean {
val psiFile = runReadAction { PsiDocumentManager.getInstance(project).getPsiFile(editor.document) }
if (psiFile == null) {
return false
}
val response = runReadAction { psiFile.isInjectedText() }
return response
return ApplicationManager.getApplication().executeOnPooledThread<Boolean> {
ApplicationManager.getApplication().runReadAction<Boolean> {
val psiFile =
PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return@runReadAction false
return@runReadAction psiFile.isInjectedText()
}
}.get()
}
fun hideCompletions(editor: Editor) {
if (isInjectedFile(editor)) return
disposeInlayRenderer(editor)
}
private fun disposeInlayRenderer(editor: Editor) {
editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach {
if (it.renderer is ContinueCustomElementRenderer) {
if (it.renderer is ContinueInlayRenderer) {
it.dispose()
}
}
editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach {
if (it.renderer is ContinueMultilineCustomElementRenderer) {
if (it.renderer is ContinueInlayRenderer) {
it.dispose()
}
}

View file

@ -1,45 +0,0 @@
package com.github.continuedev.continueintellijextension.autocomplete
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorCustomElementRenderer
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.impl.FontInfo
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.ui.JBColor
import com.intellij.util.ui.UIUtil
import java.awt.Font
import java.awt.Graphics
import java.awt.Rectangle
import kotlin.math.ceil
class ContinueCustomElementRenderer(
val editor: Editor,
val text: String,
) : EditorCustomElementRenderer {
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
val width = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(this.text)
return width
}
private fun font(editor: Editor): Font {
val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN)
return UIUtil.getFontWithFallbackIfNeeded(editorFont, text).deriveFont(editor.colorsScheme.editorFontSize)
}
private fun offsetY(editor: Editor): Int {
val metrics =
FontInfo.getFontMetrics(font(editor), FontInfo.getFontRenderContext(editor.contentComponent))
val fontHeight =
font(editor).createGlyphVector(metrics.fontRenderContext, text).visualBounds.height
val height = (editor.lineHeight + fontHeight) / 2
return ceil(height).toInt()
}
override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) {
g.color = JBColor.GRAY
g.font = font(inlay.editor)
g.drawString(this.text, targetRegion.x, targetRegion.y + inlay.editor.ascent)
}
}

View file

@ -0,0 +1,58 @@
package com.github.continuedev.continueintellijextension.autocomplete
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorCustomElementRenderer
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.ui.JBColor
import com.intellij.util.ui.UIUtil
import java.awt.Font
import java.awt.Graphics
import java.awt.Rectangle
/**
* The `ContinueInlayRenderer` class is responsible for rendering custom inlay elements within an editor.
* It implements the [EditorCustomElementRenderer] interface to provide custom rendering logic for inlays.
*
* This renderer is designed to display a list of text lines (`lines`) within the editor, calculating the
* necessary width and height based on the content and rendering each line with appropriate font and color.
*
* @author lk
*/
class ContinueInlayRenderer(val lines: List<String>) : EditorCustomElementRenderer {
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
var maxLen = 0;
for (line in lines) {
val len = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(line)
if (len > maxLen) {
maxLen = len
}
}
return maxLen
}
override fun calcHeightInPixels(inlay: Inlay<*>): Int {
return (inlay.editor as EditorImpl).lineHeight * lines.size
}
private fun font(editor: Editor): Font {
val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN)
return UIUtil.getFontWithFallbackIfNeeded(editorFont, lines.joinToString("\n"))
.deriveFont(editor.colorsScheme.editorFontSize)
}
override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) {
val editor = inlay.editor
g.color = JBColor.GRAY
g.font = font(editor)
var additionalYOffset = 0
val ascent = editor.ascent
val lineHeight = editor.lineHeight
for (line in lines) {
g.drawString(line, targetRegion.x, targetRegion.y + ascent + additionalYOffset)
additionalYOffset += lineHeight
}
}
}

View file

@ -1,81 +0,0 @@
package com.github.continuedev.continueintellijextension.autocomplete
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorCustomElementRenderer
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.impl.FontInfo
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.ui.JBColor
import com.intellij.util.ui.UIUtil
import java.awt.Font
import java.awt.Graphics
import java.awt.Rectangle
import kotlin.math.ceil
import kotlin.math.max
class ContinueMultilineCustomElementRenderer(
val editor: Editor,
val text: String,
) : EditorCustomElementRenderer {
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
val lines = text.lines()
var maxLen = 0;
for (line in lines) {
val len = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(line)
if (len > maxLen) {
maxLen = len
}
}
return maxLen
}
override fun calcHeightInPixels(inlay: Inlay<*>): Int {
return (inlay.editor as EditorImpl).lineHeight * text.lines().size
}
protected val font: Font
get() {
val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN)
return UIUtil.getFontWithFallbackIfNeeded(editorFont, text).deriveFont(editor.colorsScheme.editorFontSize)
}
private fun offsetY(): Int {
val metrics =
FontInfo.getFontMetrics(font, FontInfo.getFontRenderContext(editor.contentComponent))
val fontHeight =
font.createGlyphVector(metrics.fontRenderContext, text).visualBounds.height
val height = (editor.lineHeight + fontHeight) / 2
return ceil(height).toInt()
}
private fun offsetX(): Int {
val currentLine = editor.caretModel.primaryCaret.logicalPosition.line
val currentColumn = editor.caretModel.primaryCaret.logicalPosition.column
val metrics =
FontInfo.getFontMetrics(font, FontInfo.getFontRenderContext(editor.contentComponent))
val fontWidth =
font.createGlyphVector(metrics.fontRenderContext, text).visualBounds.width
val widthBeforeCaret = (editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(
text.substring(0, minOf(currentColumn, text.length))
)
return max(0, widthBeforeCaret - (editor as EditorImpl).scrollingModel.horizontalScrollOffset)
}
override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) {
g.color = JBColor.GRAY
g.font = font
var additionalYOffset = -editor.lineHeight;
var isFirstLine = true
for (line in text.lines()) {
g.drawString(
line,
if (isFirstLine) targetRegion.x + offsetX() else targetRegion.x,
targetRegion.y + inlay.editor.ascent + additionalYOffset
)
additionalYOffset += editor.lineHeight
isFirstLine = false
}
}
}

View file

@ -50,13 +50,78 @@ class MessageTypes {
"showToast",
)
// Note: If updating these values, make a corresponding update in
// core/protocol/passThrough.ts
val PASS_THROUGH_TO_WEBVIEW = listOf(
"configUpdate",
"getDefaultModelTitle",
"indexProgress",
"indexProgress", // Codebase
"indexing/statusUpdate", // Docs, etc.
"addContextItem",
"refreshSubmenuItems",
"isContinueInputFocused",
"didChangeAvailableProfiles",
"addContextItem"
"setTTSActive",
"getWebviewHistoryLength",
"getCurrentSessionId",
"signInToControlPlane",
"openDialogMessage",
"docs/suggestions",
)
// Note: If updating these values, make a corresponding update in
// core/protocol/passThrough.ts
val PASS_THROUGH_TO_CORE = listOf(
"abort",
"history/list",
"history/delete",
"history/load",
"history/save",
"devdata/log",
"config/addModel",
"config/addContextProvider",
"config/newPromptFile",
"config/ideSettingsUpdate",
"config/getSerializedProfileInfo",
"config/deleteModel",
"config/listProfiles",
"config/openProfile",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
"context/addDocs",
"context/removeDocs",
"context/indexDocs",
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"command/run",
"tts/kill",
"llm/complete",
"llm/streamComplete",
"llm/streamChat",
"llm/listModels",
"streamDiffLines",
"chatDescriber/describe",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase
"index/setPaused",
"index/forceReIndex",
"index/forceReIndexFiles",
"index/indexingProgressBarInitialized",
// Docs, etc.
"indexing/reindex",
"indexing/abort",
"indexing/setPaused",
"docs/getSuggestedDocs",
"docs/initStatuses",
//
"completeOnboarding",
"addAutocompleteModel",
"profiles/switch",
"didChangeSelectedProfile",
"tools/call",
)
}
}

View file

@ -469,6 +469,10 @@ class IdeProtocolClient(
}
val diffStreamService = project.service<DiffStreamService>()
// Clear all diff blocks before running the diff stream
diffStreamService.reject(editor)
val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: ""
val prompt =
@ -501,7 +505,6 @@ class IdeProtocolClient(
rif?.range?.end?.line ?: (editor.document.lineCount - 1),
{}, {})
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.register(diffStreamHandler, editor)
diffStreamHandler.streamDiffLinesToEditor(
@ -546,12 +549,14 @@ class IdeProtocolClient(
val startChar = startOffset - document.getLineStartOffset(startLine)
val endChar = endOffset - document.getLineStartOffset(endLine)
return@runReadAction RangeInFileWithContents(
virtualFile.url, Range(
Position(startLine, startChar),
Position(endLine, endChar)
), selectedText
)
return@runReadAction virtualFile.toUriOrNull()?.let {
RangeInFileWithContents(
it, Range(
Position(startLine, startChar),
Position(endLine, endChar)
), selectedText
)
}
}
return result

View file

@ -5,6 +5,7 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
import com.github.continuedev.continueintellijextension.utils.OS
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
import com.github.continuedev.continueintellijextension.utils.getOS
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
@ -180,7 +181,7 @@ class IntelliJIDE(
for (workspaceDir in workspaceDirs) {
val dir = VirtualFileManager.getInstance().findFileByUrl(workspaceDir)
if (dir != null) {
val contents = dir.children.map { it.url }
val contents = dir.children.mapNotNull { it.toUriOrNull() }
// Find any .continuerc.json files
for (file in contents) {
@ -261,7 +262,7 @@ class IntelliJIDE(
content
} else {
val file = File(URI(filepath))
if (!file.exists()) return ""
if (!file.exists() || file.isDirectory) return ""
withContext(Dispatchers.IO) {
FileInputStream(file).use { fis ->
val sizeToRead = minOf(100000, file.length()).toInt()
@ -269,6 +270,8 @@ class IntelliJIDE(
val bytesRead = fis.read(buffer, 0, sizeToRead)
if (bytesRead <= 0) return@use ""
String(buffer, 0, bytesRead, Charset.forName("UTF-8"))
// `\r` takes up unnecessary tokens
.lineSequence().joinToString("\n")
}
}
}
@ -307,16 +310,16 @@ class IntelliJIDE(
override suspend fun getOpenFiles(): List<String> {
val fileEditorManager = FileEditorManager.getInstance(project)
return fileEditorManager.openFiles.map { it.url }.toList()
return fileEditorManager.openFiles.mapNotNull { it.toUriOrNull() }.toList()
}
override suspend fun getCurrentFile(): Map<String, Any>? {
val fileEditorManager = FileEditorManager.getInstance(project)
val editor = fileEditorManager.selectedTextEditor
val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) }
return virtualFile?.let {
return virtualFile?.toUriOrNull()?.let {
mapOf(
"path" to it.url,
"path" to it,
"contents" to editor.document.text,
"isUntitled" to false
)
@ -382,7 +385,7 @@ class IntelliJIDE(
problems.add(
Problem(
filepath = psiFile.virtualFile?.url ?: "",
filepath = psiFile.virtualFile?.toUriOrNull() ?: "",
range = Range(
start = Position(
line = startLineNumber,
@ -513,7 +516,7 @@ class IntelliJIDE(
override suspend fun listDir(dir: String): List<List<Any>> {
val files = File(URI(dir)).listFiles()?.map {
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY else FileType.FILE)
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
} ?: emptyList()
return files
@ -561,6 +564,6 @@ class IntelliJIDE(
return dirs
}
return listOfNotNull(project.guessProjectDir()?.url).toTypedArray()
return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray()
}
}

View file

@ -125,7 +125,9 @@ class DiffStreamHandler(
diffBlocks.remove(diffBlock)
if (!didAccept) {
if (didAccept) {
updatePositionsOnAccept(diffBlock.startLine)
} else {
updatePositionsOnReject(diffBlock.startLine, diffBlock.addedLines.size, diffBlock.deletedLines.size)
}
@ -186,10 +188,16 @@ class DiffStreamHandler(
}
}
private fun updatePositionsOnAccept(startLine: Int) {
updatePositions(startLine, 0)
}
private fun updatePositionsOnReject(startLine: Int, numAdditions: Int, numDeletions: Int) {
val offset = -numAdditions + numDeletions
updatePositions(startLine, offset)
}
private fun updatePositions(startLine: Int, offset: Int) {
diffBlocks.forEach { block ->
if (block.startLine > startLine) {
block.updatePosition(block.startLine + offset)

View file

@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.utils.getAltKeyLabel
import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LogicalPosition
@ -11,6 +12,7 @@ import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.ui.JBColor
import com.intellij.util.application
import java.awt.*
import javax.swing.BorderFactory
import javax.swing.JButton
@ -41,7 +43,14 @@ class VerticalDiffBlock(
}
fun clearEditorUI() {
deletionInlay?.dispose()
deletionInlay?.let {
// Ensure that dispose is executed on EDT
if (application.isDispatchThread) {
it.dispose()
} else {
invokeLater { it.dispose() }
}
}
removeGreenHighlighters()
removeButtons()
}

View file

@ -28,6 +28,10 @@ class ContinuePluginSelectionListener(
private var lastActiveEditor: Editor? = null
override fun selectionChanged(e: SelectionEvent) {
if (e.editor.isDisposed || e.editor.project?.isDisposed == true) {
return
}
debouncer.debounce { handleSelection(e) }
}
@ -106,6 +110,19 @@ class ContinuePluginSelectionListener(
ApplicationManager.getApplication().invokeLater {
val document = editor.document
val (startLine, endLine, isFullLineSelection) = getSelectionInfo(model, document)
// Check if entire file is selected
val isEntireFileSelected = model.selectionStart == 0 &&
model.selectionEnd == document.textLength
// Scroll to top if entire file selected so that the user can see the input
if (isEntireFileSelected) {
editor.scrollingModel.scrollTo(
LogicalPosition(0, 0),
com.intellij.openapi.editor.ScrollType.CENTER
)
}
val selectionTopY = calculateSelectionTopY(editor, startLine, endLine, isFullLineSelection)
val tooltipX = calculateTooltipX(editor, document, startLine, endLine, isFullLineSelection)

View file

@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable
import com.github.continuedev.continueintellijextension.constants.MessageTypes
import com.github.continuedev.continueintellijextension.constants.MessageTypes.Companion.PASS_THROUGH_TO_CORE
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
@ -18,57 +19,6 @@ import org.cef.browser.CefBrowser
import org.cef.handler.CefLoadHandlerAdapter
class ContinueBrowser(val project: Project, url: String) {
private val PASS_THROUGH_TO_CORE = listOf(
"abort",
"history/list",
"history/delete",
"history/load",
"history/save",
"devdata/log",
"config/addModel",
"config/newPromptFile",
"config/ideSettingsUpdate",
"config/getSerializedProfileInfo",
"config/deleteModel",
"config/listProfiles",
"config/openProfile",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
"context/addDocs",
"context/removeDocs",
"context/indexDocs",
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"command/run",
"tts/kill",
"llm/complete",
"llm/streamComplete",
"llm/streamChat",
"llm/listModels",
"streamDiffLines",
"chatDescriber/describe",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase
"index/setPaused",
"index/forceReIndex",
"index/indexingProgressBarInitialized",
// Docs, etc.
"indexing/reindex",
"indexing/abort",
"indexing/setPaused",
"docs/getSuggestedDocs",
"docs/initStatuses",
//
"completeOnboarding",
"addAutocompleteModel",
"profiles/switch",
"didChangeSelectedProfile",
"tools/call",
)
private fun registerAppSchemeHandler() {
CefApp.getInstance().registerSchemeHandlerFactory(
"http",
@ -81,14 +31,9 @@ class ContinueBrowser(val project: Project, url: String) {
init {
val isOSREnabled = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build()
browser.jbCefClient.setProperty(
JBCefClient.Properties.JS_QUERY_POOL_SIZE,
JS_QUERY_POOL_SIZE
)
registerAppSchemeHandler()
browser.loadURL(url);
Disposer.register(ContinuePluginDisposable.getInstance(project), browser)

View file

@ -1,5 +1,6 @@
package com.github.continuedev.continueintellijextension.utils
import com.intellij.openapi.vfs.VirtualFile
import java.net.NetworkInterface
import java.util.*
import java.awt.event.KeyEvent.*
@ -77,4 +78,6 @@ fun getMachineUniqueID(): String {
fun uuid(): String {
return UUID.randomUUID().toString()
}
}
fun VirtualFile.toUriOrNull(): String? = fileSystem.getNioPath(this)?.toUri()?.toString()?.removeSuffix("/")

View file

@ -0,0 +1,73 @@
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.fixtures.dialog
import com.github.continuedev.continueintellijextension.fixtures.idea
import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.utils.keyboard
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class Autocomplete {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
@Video
fun displayCompletion(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
).isNotEmpty()
}
idea {
with(textEditor()) {
val userMsg = "TEST_USER_MESSAGE_0"
editor.insertTextAtLine(0, 0, userMsg)
editor.clickOnOffset(userMsg.length)
keyboard {
enterText(" ")
}
waitFor(ofSeconds(10)) {
editor.hasText("TEST_LLM_RESPONSE_0")
}
}
}
}
}

View file

@ -0,0 +1,96 @@
/**
* Currently we can't test any actions in the GUI that involve clicks.
* See this open issue for details: https://github.com/JetBrains/intellij-ui-test-robot/issues/491
*/
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.fixtures.*
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.github.continuedev.continueintellijextension.utils.getMetaKey
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.stepsProcessing.step
import com.intellij.remoterobot.utils.keyboard
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.awt.event.KeyEvent.*
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class GUI {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
@Video
fun highlightCode(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
// If we don't wait for this, clicking on the GUI may fail because a popup displays
// while the `continue_tutorial.java` is loading.
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
).isNotEmpty()
}
idea {
step("Manually open the webview") {
// Manually open the webview
find<ComponentFixture>(byXpath("//div[@text='Continue']"), ofSeconds((10))).click()
waitFor(ofSeconds(10)) {
browser().isShowing
}
// Arbitrary timeout due to a bug where the webview will refresh
// and clear the editor state on first load
Thread.sleep(5000)
}
step("Verify we can highlight code and add to webview") {
val textToInsert = "Hello world!"
with(textEditor()) {
editor.insertTextAtLine(0, 0, textToInsert)
editor.selectText(textToInsert)
keyboard {
hotKey(getMetaKey(), VK_J)
}
}
waitFor(ofSeconds(10)) {
browser().findElementByContainsText(textToInsert).html.isNotEmpty()
}
}
}
}
}

View file

@ -0,0 +1,85 @@
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.fixtures.dialog
import com.github.continuedev.continueintellijextension.fixtures.idea
import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.stepsProcessing.step
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class Onboarding {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
@Video
fun onboarding(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
idea {
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
// So we need to wait for that to occur, and then focus on "continue_tutorial.java.ft"
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
).isNotEmpty()
}
// TODO: Need a good way to ensure this is the first test ran in the entire suite
// step("Verify Continue tutorial file is loaded") {
// find<ComponentFixture>(byXpath("//div[@visible_text='continue_tutorial.java']"))
// }
step("Manually open the webview") {
// Manually open the webview
find<ComponentFixture>(byXpath("//div[@text='Continue']"), ofSeconds((10))).click()
waitFor(ofSeconds(10)) {
browser().isShowing
}
}
step("Verify the onboarding card is present") {
waitFor(ofSeconds(30)) {
try {
browser().findElement("//*[@data-testid='onboarding-card']").html.isNotEmpty()
} catch (e: Exception) {
false
}
}
}
}
}
}

View file

@ -1,94 +0,0 @@
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.pages.dialog
import com.github.continuedev.continueintellijextension.pages.idea
import com.github.continuedev.continueintellijextension.pages.welcomeFrame
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.github.continuedev.continueintellijextension.utils.getMetaKey
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.fixtures.JCefBrowserFixture
import com.intellij.remoterobot.search.locators.Locator
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.utils.keyboard
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.awt.event.KeyEvent.*
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class TutorialTest {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
@Test
@Video
fun completeTutorial(remoteRobot: RemoteRobot) = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java" tab loads first, but then "Main.java" takes focus.
// So we need to wait for that to occur, and then focus on "continue_tutorial.java"
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
).isNotEmpty()
}
val tutorialEditorTabLocator: Locator =
byXpath("//div[@accessiblename='continue_tutorial.java' and @class='EditorTabLabel']")
val tutorialEditorTab: ComponentFixture =
remoteRobot.find(ComponentFixture::class.java, tutorialEditorTabLocator)
tutorialEditorTab.click()
// Manually open the webview
find<ComponentFixture>(byXpath("//div[@text='Continue']")).click()
// Arbitrary sleep while we wait for the webview to load
Thread.sleep(10000)
val textToInsert = "Hello world!"
idea {
with(textEditor()) {
editor.insertTextAtLine(0, 0, textToInsert)
editor.selectText(textToInsert)
keyboard {
hotKey(getMetaKey(), VK_J)
}
}
}
// TODO: locator needs to be OS aware
// https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/remote-fixtures/src/main/kotlin/com/intellij/remoterobot/fixtures/CommonContainerFixture.kt#L203
val jcefBrowser = find<JCefBrowserFixture>(JCefBrowserFixture.macLocator)
assert(jcefBrowser.getDom().isNotEmpty()) { "JCEF browser not found or empty" }
val codeSnippetText = jcefBrowser.findElementByContainsText(textToInsert)
assert(codeSnippetText.html.isNotEmpty()) { "Failed to find code snippet in webview" }
}
}

View file

@ -0,0 +1,43 @@
{
"ui": {
"displayRawMarkdown": false
},
"models": [
{
"title": "TEST LLM",
"provider": "test",
"model": "this field is not used"
},
{
"title": "Mock",
"provider": "mock",
"model": "this field is not used"
}
],
"analytics": {
"provider": "continue-proxy"
},
"tabAutocompleteModel": {
"title": "TEST LLM",
"provider": "test",
"model": "this field is not used"
},
"tabAutocompleteOptions": {
"useCache": false
},
"contextProviders": [
{
"name": "docs"
},
{
"name": "diff"
},
{
"name": "url"
},
{
"name": "folder"
}
],
"docs": []
}

View file

@ -1,4 +1,4 @@
package com.github.continuedev.continueintellijextension.pages
package com.github.continuedev.continueintellijextension.fixtures
/*
* Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/DialogFixture.kt

View file

@ -1,4 +1,4 @@
package com.github.continuedev.continueintellijextension.pages
package com.github.continuedev.continueintellijextension.fixtures
/*
* Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/IdeaFrame.kt

View file

@ -1,4 +1,4 @@
package com.github.continuedev.continueintellijextension.pages
package com.github.continuedev.continueintellijextension.fixtures
/*
* Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/WelcomeFrame.kt

View file

@ -180,6 +180,7 @@
"bedrockimport",
"sagemaker",
"together",
"novita",
"ollama",
"huggingface-tgi",
"huggingface-inference-api",
@ -222,6 +223,7 @@
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)",
"### Novita AI\n[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) offers an affordable, reliable, and simple inference platform with scalable [LLM APIs](https://novita.ai/docs/model-api/reference/introduction.html), empowering developers to build AI applications. To get started with Novita AI:\n1. Obtain an API key from [here](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/novita)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)",
"### Huggingface Inference API\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfaceinferenceapi)",
@ -262,7 +264,7 @@
},
"apiKey": {
"title": "Api Key",
"description": "OpenAI, Anthropic, Cohere, Together, or other API key",
"description": "OpenAI, Anthropic, Cohere, Together, Novita AI, or other API key",
"type": "string"
},
"apiBase": {
@ -475,6 +477,7 @@
"huggingface-inference-api",
"replicate",
"together",
"novita",
"cloudflare",
"sambanova",
"nebius",
@ -980,6 +983,44 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["novita"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"llama3-8b",
"llama3-70b",
"llama3.1-8b",
"llama3.1-70b",
"llama3.1-405b",
"llama3.2-1b",
"llama3.2-3b",
"llama3.2-11b",
"llama3.3-70b",
"mistral-nemo",
"mistral-7b"
]
},
{
"type": "string"
}
],
"markdownDescription": "Select a pre-defined option, or find an exact model string from Novita AI [here](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link).",
"x-intellij-html-description": "Select a pre-defined option, or find an exact model string from Novita AI <a href='https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link'>here</a>."
}
}
}
},
{
"if": {
"properties": {
@ -1864,7 +1905,8 @@
"os",
"repo-map",
"greptile",
"web"
"web",
"clipboard"
],
"markdownEnumDescriptions": [
"Reference the contents of the current changes as given by `git diff`",
@ -2805,10 +2847,7 @@
"type": "object",
"properties": {
"model": {
"enum": [
"cohere.rerank-v3-5:0",
"amazon.rerank-v1:0"
]
"enum": ["cohere.rerank-v3-5:0", "amazon.rerank-v1:0"]
}
},
"required": ["model"]
@ -3132,62 +3171,72 @@
"description": "Allow tool use. Currently only supported with Claude 3.5 Sonnet",
"default": true
},
"modelContextProtocolServer": {
"type": "object",
"properties": {
"transport": {
"oneOf": [
{
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["stdio"]
},
"command": {
"type": "string"
},
"args": {
"type": "array",
"items": {
"modelContextProtocolServers": {
"type": "array",
"items": {
"type": "object",
"properties": {
"transport": {
"oneOf": [
{
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["stdio"]
},
"command": {
"type": "string"
},
"args": {
"type": "array",
"items": {
"type": "string"
}
},
"env": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"description": "Environment variables to pass to the command"
}
}
},
"required": ["type", "command", "args"]
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["websocket"]
},
"url": {
"type": "string",
"format": "uri"
}
"required": ["type", "command", "args"]
},
"required": ["type", "url"]
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["sse"]
{
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["websocket"]
},
"url": {
"type": "string",
"format": "uri"
}
},
"url": {
"type": "string",
"format": "uri"
}
"required": ["type", "url"]
},
"required": ["type", "url"]
}
]
}
},
"required": ["transport"]
{
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["sse"]
},
"url": {
"type": "string",
"format": "uri"
}
},
"required": ["type", "url"]
}
]
}
},
"required": ["transport"]
}
}
}
}

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.248",
"version": "0.9.250",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.248",
"version": "0.9.250",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/fetch": "^1.0.3",
@ -48,6 +48,7 @@
"request": "^2.88.2",
"socket.io-client": "^4.7.2",
"strip-ansi": "^7.1.0",
"svg-builder": "^2.0.0",
"systeminformation": "^5.22.10",
"tailwindcss": "^3.3.2",
"undici": "^6.2.0",
@ -12122,6 +12123,11 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/svg-builder": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/svg-builder/-/svg-builder-2.0.0.tgz",
"integrity": "sha512-v89FptvyrOy1Gf9KPkIo2jxroCLEZLiGBRTSutL3pzqZe2xnCFltkCLnEjV8QOEJ99PzBa9NGPGEDP9l8MWIrw=="
},
"node_modules/symbol-tree": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.248",
"version": "0.9.250",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -57,12 +57,6 @@
],
"main": "./out/extension.js",
"contributes": {
"authentication": [
{
"id": "continue",
"label": "Continue"
}
],
"languages": [
{
"filenames": [
@ -107,6 +101,11 @@
"default": true,
"description": "Show inline suggestion to use the Continue keyboard shortcuts (e.g. \"Cmd/Ctrl L to select code, Cmd/Ctrl I to edit\")."
},
"continue.disableQuickFix": {
"type": "boolean",
"default": false,
"description": "Disable the quick fix feature."
},
"continue.enableQuickActions": {
"type": "boolean",
"default": false,
@ -703,6 +702,7 @@
"request": "^2.88.2",
"socket.io-client": "^4.7.2",
"strip-ansi": "^7.1.0",
"svg-builder": "^2.0.0",
"systeminformation": "^5.22.10",
"tailwindcss": "^3.3.2",
"undici": "^6.2.0",

View file

@ -0,0 +1,427 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { EXTENSION_NAME } from "core/control-plane/env";
// @ts-ignore
import svgBuilder from "svg-builder";
import * as vscode from "vscode";
import { getTheme } from "../util/getTheme";
import { getMetaKeyLabel, getMetaKeyName } from "../util/util";
const SVG_CONFIG = {
stroke: "#999998",
strokeWidth: 1,
shortcutColor: "#999998",
filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))",
radius: 4,
leftMargin: 40,
debounceDelay: 500,
chatLabel: "Chat",
chatShortcut: `${getMetaKeyLabel()}L`,
editLabel: "Edit",
editShortcut: `${getMetaKeyLabel()}I`,
get fontSize() {
return Math.ceil(
(vscode.workspace.getConfiguration("editor").get<number>("fontSize") ??
14) * 0.8,
);
},
get fontFamily() {
return (
vscode.workspace.getConfiguration("editor").get<string>("fontFamily") ||
"helvetica"
);
},
get paddingY() {
return Math.ceil(this.fontSize * 0.4);
},
get paddingX() {
return Math.ceil(this.fontSize * 0.8);
},
get gap() {
return this.fontSize * 2.5;
},
get tipWidth() {
return (
this.editShortcutX +
this.getEstimatedTextWidth(this.editShortcut) +
this.paddingX
);
},
get tipHeight() {
return this.fontSize + this.paddingY * 2;
},
get textY() {
return this.tipHeight / 2 + this.fontSize * 0.35;
},
get chatLabelX() {
return this.paddingX;
},
get chatShortcutX() {
return this.chatLabelX + this.getEstimatedTextWidth(this.chatLabel) + 4;
},
get editLabelX() {
return this.chatShortcutX + this.gap;
},
get editShortcutX() {
return this.editLabelX + this.getEstimatedTextWidth(this.editLabel) + 4;
},
getEstimatedTextWidth(text: string): number {
return text.length * this.fontSize * 0.6;
},
} as const;
export class InlineTipManager {
private static instance: InlineTipManager;
private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"];
private readonly hideCommand = "continue.hideInlineTip";
private svgTooltip: vscode.Uri | undefined = undefined;
private debounceTimer: NodeJS.Timeout | undefined;
private lastActiveEditor?: vscode.TextEditor;
private theme = getTheme();
private svgTooltipDecoration = this.createSvgTooltipDecoration();
private emptyFileTooltipDecoration = this.createEmptyFileTooltipDecoration();
public static getInstance(): InlineTipManager {
if (!InlineTipManager.instance) {
InlineTipManager.instance = new InlineTipManager();
}
return InlineTipManager.instance;
}
private constructor() {
this.createSvgTooltip();
this.setupSvgTipListeners();
}
public setupInlineTips(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.window.onDidChangeTextEditorSelection((e) => {
this.handleSelectionChange(e);
}),
);
this.setupEmptyFileTips(context);
context.subscriptions.push(this);
}
public handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
const selection = e.selections[0];
const editor = e.textEditor;
if (selection.isEmpty || !this.shouldRenderTip(editor.document.uri)) {
editor.setDecorations(this.svgTooltipDecoration, []);
return;
}
this.debouncedSelectionChange(editor, selection);
}
public dispose() {
this.svgTooltipDecoration.dispose();
this.emptyFileTooltipDecoration.dispose();
if (this.debounceTimer) {
clearTimeout(this.debounceTimer);
}
}
private debouncedSelectionChange(
editor: vscode.TextEditor,
selection: vscode.Selection,
) {
if (this.debounceTimer) {
clearTimeout(this.debounceTimer);
}
this.debounceTimer = setTimeout(() => {
// Clear decoration from previous editor
if (this.lastActiveEditor && this.lastActiveEditor !== editor) {
this.lastActiveEditor.setDecorations(this.svgTooltipDecoration, []);
}
this.lastActiveEditor = editor;
this.updateTooltipPosition(editor, selection);
}, SVG_CONFIG.debounceDelay);
}
private setupSvgTipListeners() {
vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration("workbench.colorTheme")) {
this.theme = getTheme();
this.createSvgTooltip();
}
});
vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration("editor.fontSize")) {
this.createSvgTooltip();
}
});
}
private shouldRenderTip(uri: vscode.Uri): boolean {
const isAllowedUri =
!this.excludedURIPrefixes.some((prefix) =>
uri.toString().startsWith(prefix),
) && uri.scheme !== "comment";
const isEnabled =
!!vscode.workspace
.getConfiguration(EXTENSION_NAME)
.get<boolean>("showInlineTip") === true;
return isAllowedUri && isEnabled;
}
private setupEmptyFileTips(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor((editor) => {
if (
editor?.document.getText() === "" &&
this.shouldRenderTip(editor.document.uri)
) {
editor.setDecorations(this.emptyFileTooltipDecoration, [
{
range: new vscode.Range(
new vscode.Position(0, Number.MAX_VALUE),
new vscode.Position(0, Number.MAX_VALUE),
),
},
]);
}
}),
);
context.subscriptions.push(
vscode.workspace.onDidChangeTextDocument((e) => {
if (
e.document.getText() === "" &&
this.shouldRenderTip(e.document.uri)
) {
vscode.window.visibleTextEditors.forEach((editor) => {
editor.setDecorations(this.emptyFileTooltipDecoration, [
{
range: new vscode.Range(
new vscode.Position(0, Number.MAX_VALUE),
new vscode.Position(0, Number.MAX_VALUE),
),
},
]);
});
} else {
vscode.window.visibleTextEditors.forEach((editor) => {
editor.setDecorations(this.emptyFileTooltipDecoration, []);
});
}
}),
);
}
private createEmptyFileTooltipDecoration() {
return vscode.window.createTextEditorDecorationType({
after: {
contentText: `Use ${getMetaKeyName()} + I to generate code`,
color: "#888",
margin: "2em 0 0 0",
fontStyle: "italic",
},
});
}
private createSvgTooltipDecoration() {
return vscode.window.createTextEditorDecorationType({
after: {
contentIconPath: this.svgTooltip,
margin: `-5px 0 0 ${SVG_CONFIG.leftMargin}px`,
width: `${SVG_CONFIG.tipWidth}px`,
},
});
}
private createSvgTooltip() {
const baseTextConfig = {
y: SVG_CONFIG.textY,
"font-family": SVG_CONFIG.fontFamily,
"font-size": SVG_CONFIG.fontSize,
};
if (!this.theme) {
return;
}
try {
const svgContent = svgBuilder
.width(SVG_CONFIG.tipWidth)
.height(SVG_CONFIG.tipHeight)
// Main rectangle
.rect({
x: 0,
y: 0,
width: SVG_CONFIG.tipWidth,
height: SVG_CONFIG.tipHeight,
rx: SVG_CONFIG.radius,
ry: SVG_CONFIG.radius,
fill: this.theme.colors["editor.background"],
stroke: SVG_CONFIG.stroke,
"stroke-width": SVG_CONFIG.strokeWidth,
filter: SVG_CONFIG.filter,
})
// Chat
.text(
{
...baseTextConfig,
x: SVG_CONFIG.chatLabelX,
fill: this.theme.colors["editor.foreground"],
},
SVG_CONFIG.chatLabel,
)
.text(
{
...baseTextConfig,
x: SVG_CONFIG.chatShortcutX,
fill: SVG_CONFIG.shortcutColor,
},
SVG_CONFIG.chatShortcut,
)
// Edit
.text(
{
...baseTextConfig,
x: SVG_CONFIG.editLabelX,
fill: this.theme.colors["editor.foreground"],
},
SVG_CONFIG.editLabel,
)
.text(
{
...baseTextConfig,
x: SVG_CONFIG.editShortcutX,
fill: SVG_CONFIG.shortcutColor,
},
SVG_CONFIG.editShortcut,
)
.render();
const dataUri = `data:image/svg+xml;base64,${Buffer.from(svgContent).toString("base64")}`;
this.svgTooltip = vscode.Uri.parse(dataUri);
this.svgTooltipDecoration.dispose();
this.svgTooltipDecoration = this.createSvgTooltipDecoration();
} catch (error) {
console.error("Error creating SVG for inline tip:", error);
}
}
private buildHideTooltipHoverMsg() {
const hoverMarkdown = new vscode.MarkdownString(
`[Disable](command:${this.hideCommand})`,
);
hoverMarkdown.isTrusted = true;
hoverMarkdown.supportHtml = true;
return hoverMarkdown;
}
/**
* Calculates tooltip position using these rules:
* 1. For single-line selection: Place after the line's content
* 2. For multi-line selection: Place after the longer line between:
* - The first non-empty selected line
* - The line above the selection
* Returns null if selection is empty or contains only empty lines
*/
private calculateTooltipPosition(
editor: vscode.TextEditor,
selection: vscode.Selection,
): vscode.Position | null {
const document = editor.document;
// Get selection info
const startLine = selection.start.line;
const endLine = selection.end.line;
const isFullLineSelection =
selection.start.character === 0 &&
(selection.end.line > selection.start.line
? selection.end.character === 0
: selection.end.character ===
document.lineAt(selection.end.line).text.length);
// Helper functions
const isLineEmpty = (lineNumber: number): boolean => {
return document.lineAt(lineNumber).text.trim().length === 0;
};
const getLineEndChar = (lineNumber: number): number => {
return document.lineAt(lineNumber).text.trimEnd().length;
};
// If single empty line selected and not full line selection, return null
if (
startLine === endLine &&
isLineEmpty(startLine) &&
!isFullLineSelection
) {
return null;
}
// Find topmost non-empty line
let topNonEmptyLine = startLine;
while (topNonEmptyLine <= endLine && isLineEmpty(topNonEmptyLine)) {
topNonEmptyLine++;
}
// If all lines empty, return null
if (topNonEmptyLine > endLine) {
return null;
}
const OFFSET = 4; // Characters to offset from end of line
// Single line or full line selection
if (isFullLineSelection || startLine === endLine) {
return new vscode.Position(
topNonEmptyLine,
getLineEndChar(topNonEmptyLine) + OFFSET,
);
}
// Check line above selection
const lineAboveSelection = Math.max(0, startLine - 1);
// Get end positions
const topNonEmptyEndChar = getLineEndChar(topNonEmptyLine);
const lineAboveEndChar = getLineEndChar(lineAboveSelection);
const baseEndChar = Math.max(topNonEmptyEndChar, lineAboveEndChar);
return new vscode.Position(topNonEmptyLine, baseEndChar + OFFSET);
}
private updateTooltipPosition(
editor: vscode.TextEditor,
selection: vscode.Selection,
) {
const position = this.calculateTooltipPosition(editor, selection);
if (!position) {
editor.setDecorations(this.svgTooltipDecoration, []);
return;
}
editor.setDecorations(this.svgTooltipDecoration, [
{
range: new vscode.Range(position, position),
hoverMessage: [this.buildHideTooltipHoverMsg()],
},
]);
}
}
export default function setupInlineTips(context: vscode.ExtensionContext) {
InlineTipManager.getInstance().setupInlineTips(context);
}

View file

@ -7,7 +7,7 @@ import registerQuickFixProvider from "../lang-server/codeActions";
import { getExtensionVersion } from "../util/util";
import { VsCodeContinueApi } from "./api";
import { setupInlineTips } from "./inlineTips";
import setupInlineTips from "./InlineTipManager";
export async function activateExtension(context: vscode.ExtensionContext) {
// Add necessary files

View file

@ -1,122 +0,0 @@
import { EXTENSION_NAME } from "core/control-plane/env";
import * as vscode from "vscode";
import { getMetaKeyName } from "../util/util";
const inlineTipDecoration = vscode.window.createTextEditorDecorationType({
after: {
contentText: `Add to chat (${getMetaKeyName()}+L) | Edit highlighted code (${getMetaKeyName()}+I).`,
color: "#888",
margin: "0 0 0 6em",
fontWeight: "bold",
},
});
function showInlineTip() {
return vscode.workspace
.getConfiguration(EXTENSION_NAME)
.get<boolean>("showInlineTip");
}
function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
const selection = e.selections[0];
const editor = e.textEditor;
if (editor.document.uri.toString().startsWith("output:")) {
return;
}
if (selection.isEmpty || showInlineTip() === false) {
editor.setDecorations(inlineTipDecoration, []);
return;
}
const line = Math.max(0, selection.start.line - 1);
const hoverMarkdown = new vscode.MarkdownString(
`Click [here](command:continue.hideInlineTip) to hide these suggestions`,
);
hoverMarkdown.isTrusted = true;
hoverMarkdown.supportHtml = true;
editor.setDecorations(inlineTipDecoration, [
{
range: new vscode.Range(
new vscode.Position(line, Number.MAX_VALUE),
new vscode.Position(line, Number.MAX_VALUE),
),
hoverMessage: [hoverMarkdown],
},
]);
}
const emptyFileTooltipDecoration = vscode.window.createTextEditorDecorationType(
{
after: {
contentText: `Use ${getMetaKeyName()}+I to generate code`,
color: "#888",
margin: "2em 0 0 0",
fontStyle: "italic",
},
},
);
let selectionChangeDebounceTimer: NodeJS.Timeout | undefined;
export function setupInlineTips(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.window.onDidChangeTextEditorSelection((e) => {
if (selectionChangeDebounceTimer) {
clearTimeout(selectionChangeDebounceTimer);
}
selectionChangeDebounceTimer = setTimeout(() => {
handleSelectionChange(e);
}, 200);
}),
);
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor((editor) => {
if (editor?.document.getText() === "" && showInlineTip() === true) {
if (
editor.document.uri.toString().startsWith("output:") ||
editor.document.uri.scheme === "comment"
) {
return;
}
editor.setDecorations(emptyFileTooltipDecoration, [
{
range: new vscode.Range(
new vscode.Position(0, Number.MAX_VALUE),
new vscode.Position(0, Number.MAX_VALUE),
),
},
]);
}
}),
);
context.subscriptions.push(
vscode.workspace.onDidChangeTextDocument((e) => {
if (e.document.uri.toString().startsWith("vscode://inline-chat")) {
return;
}
if (e.document.getText() === "" && showInlineTip() === true) {
vscode.window.visibleTextEditors.forEach((editor) => {
editor.setDecorations(emptyFileTooltipDecoration, [
{
range: new vscode.Range(
new vscode.Position(0, Number.MAX_VALUE),
new vscode.Position(0, Number.MAX_VALUE),
),
},
]);
});
} else {
vscode.window.visibleTextEditors.forEach((editor) => {
editor.setDecorations(emptyFileTooltipDecoration, []);
});
}
}),
);
}

View file

@ -739,10 +739,12 @@ const getCommandsMap: (
if (fullScreenTab && fullScreenPanel) {
// Full screen open, but not focused - focus it
fullScreenPanel.reveal();
vscode.commands.executeCommand("continue.focusContinueInput");
return;
}
// Clear the sidebar to prevent overwriting changes made in fullscreen
vscode.commands.executeCommand("continue.newSession")
// Full screen not open - open it
captureCommandTelemetry("openFullScreen");
@ -767,7 +769,7 @@ const getCommandsMap: (
true,
);
panel.onDidChangeViewState(() => {
const sessionLoader = panel.onDidChangeViewState(() => {
vscode.commands.executeCommand("continue.newSession");
if (sessionId) {
vscode.commands.executeCommand(
@ -775,6 +777,7 @@ const getCommandsMap: (
sessionId,
);
}
sessionLoader.dispose()
});
// When panel closes, reset the webview and focus
@ -1001,7 +1004,10 @@ const getCommandsMap: (
};
};
const registerCopyBufferSpy = (context: vscode.ExtensionContext) => {
const registerCopyBufferSpy = (
context: vscode.ExtensionContext,
core: Core,
) => {
const typeDisposable = vscode.commands.registerCommand(
"editor.action.clipboardCopyAction",
async (arg) => doCopy(typeDisposable),
@ -1014,6 +1020,12 @@ const registerCopyBufferSpy = (context: vscode.ExtensionContext) => {
const clipboardText = await vscode.env.clipboard.readText();
if (clipboardText) {
core.invoke("clipboardCache/add", {
content: clipboardText,
});
}
await context.workspaceState.update("continue.copyBuffer", {
text: clipboardText,
copiedAt: new Date().toISOString(),
@ -1043,7 +1055,7 @@ export function registerAllCommands(
core: Core,
editDecorationManager: EditDecorationManager,
) {
registerCopyBufferSpy(context);
registerCopyBufferSpy(context, core);
for (const [command, callback] of Object.entries(
getCommandsMap(

View file

@ -343,6 +343,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
async run(diffLineGenerator: AsyncGenerator<DiffLine>) {
let diffLines = [];
try {
// As an indicator of loading
this.updateIndexLineDecorations();
@ -358,7 +359,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
// Clear deletion buffer
await this.insertDeletionBuffer();
this.reapplyWithMeyersDiff(diffLines);
await this.reapplyWithMeyersDiff(diffLines);
this.options.onStatusUpdate(
"done",
@ -385,6 +386,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
startLine: number,
numGreen: number,
numRed: number,
skipStatusUpdate?: boolean,
) {
if (numGreen > 0) {
// Delete the editor decoration
@ -414,15 +416,18 @@ export class VerticalDiffHandler implements vscode.Disposable {
// Shift the codelens objects
this.shiftCodeLensObjects(startLine, offset);
const numDiffs =
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0;
if (!skipStatusUpdate) {
const numDiffs =
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0;
const status = numDiffs === 0 ? "closed" : undefined;
this.options.onStatusUpdate(
status,
numDiffs,
this.editor.document.getText(),
);
const status = numDiffs === 0 ? "closed" : undefined;
this.options.onStatusUpdate(
status,
numDiffs,
this.editor.document.getText(),
);
}
}
private shiftCodeLensObjects(startLine: number, offset: number) {
@ -481,9 +486,21 @@ export class VerticalDiffHandler implements vscode.Disposable {
* we have received all of the diff lines.
*/
async reapplyWithMeyersDiff(diffLines: DiffLine[]) {
// First, we reset the original diff by rejecting all pending diff blocks
for (const block of this.editorToVerticalDiffCodeLens.get(this.fileUri) ??
[]) {
await this.acceptRejectBlock(
false,
block.start,
block.numGreen,
block.numRed,
true,
);
}
this.clearDecorations();
// First, get our old/new file content based on the diff lines
// Then, get our old/new file content based on the original lines
const oldFileContent = diffLines
.filter((line) => line.type === "same" || line.type === "old")
.map((line) => line.line)
@ -498,59 +515,48 @@ export class VerticalDiffHandler implements vscode.Disposable {
const meyersDiffLines = diffs.map((diff) => diff.line).join("\n");
// Then, we overwrite the potentially miscalcualted diff blocks with our Meyers Diff
const fullRange = new vscode.Range(
this.editor.document.positionAt(0),
this.editor.document.positionAt(this.editor.document.getText().length),
);
await this.editor.edit(
(editBuilder) => {
editBuilder.replace(fullRange, meyersDiffLines);
},
{
undoStopAfter: false,
undoStopBefore: false,
},
);
let currentBlock = {
start: 0,
numRed: 0,
numGreen: 0,
};
const blocks: VerticalDiffCodeLens[] = [];
// Then, we insert our diff lines
await this.editor.edit((editBuilder) => {
editBuilder.replace(this.range, meyersDiffLines),
{
undoStopAfter: false,
undoStopBefore: false,
};
});
// Lastly, we apply decorations
let numRed = 0;
let numGreen = 0;
const codeLensBlocks: VerticalDiffCodeLens[] = [];
diffs.forEach((diff, index) => {
if (diff.type === "old") {
this.redDecorationManager.addLine(index);
currentBlock.numRed++;
this.redDecorationManager.addLine(this.startLine + index);
numRed++;
} else if (diff.type === "new") {
this.greenDecorationManager.addLine(index);
currentBlock.numGreen++;
} else if (
diff.type === "same" &&
(currentBlock.numRed > 0 || currentBlock.numGreen > 0)
) {
blocks.push({
...currentBlock,
start: index - currentBlock.numRed - currentBlock.numGreen,
this.greenDecorationManager.addLine(this.startLine + index);
numGreen++;
} else if (diff.type === "same" && (numRed > 0 || numGreen > 0)) {
codeLensBlocks.push({
numRed,
numGreen,
start: this.startLine + index - numRed - numGreen,
});
currentBlock = {
start: index + 1,
numRed: 0,
numGreen: 0,
};
numRed = 0;
numGreen = 0;
}
});
if (currentBlock.numRed > 0 || currentBlock.numGreen > 0) {
blocks.push(currentBlock);
if (numRed > 0 || numGreen > 0) {
codeLensBlocks.push({
numGreen,
numRed,
start: this.startLine + diffs.length - numRed - numGreen,
});
}
this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks);
this.refreshCodeLens();
}
}

View file

@ -3,13 +3,13 @@ import { ConfigHandler } from "core/config/ConfigHandler";
import { streamDiffLines } from "core/edit/streamDiffLines";
import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
import { getMarkdownLanguageTagForFile } from "core/util";
import * as URI from "uri-js";
import * as vscode from "vscode";
import EditDecorationManager from "../../quickEdit/EditDecorationManager";
import { VsCodeWebviewProtocol } from "../../webviewProtocol";
import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler";
import * as URI from "uri-js";
export interface VerticalDiffCodeLens {
start: number;

View file

@ -1,3 +1,4 @@
import { EXTENSION_NAME } from "core/control-plane/env";
import * as vscode from "vscode";
class ContinueQuickFixProvider implements vscode.CodeActionProvider {
@ -42,6 +43,15 @@ class ContinueQuickFixProvider implements vscode.CodeActionProvider {
}
export default function registerQuickFixProvider() {
const isDisabled =
!!vscode.workspace
.getConfiguration(EXTENSION_NAME)
.get<boolean>("disableQuickFix") === true;
if (isDisabled) {
return;
}
// In your extension's activate function:
vscode.languages.registerCodeActionsProvider(
{ language: "*" },

View file

@ -53,15 +53,6 @@ export class VerticalDiffCodeLensProvider implements vscode.CodeLensProvider {
arguments: [uri, i],
}),
);
if (codeLenses.length === 2) {
codeLenses.push(
new vscode.CodeLens(range, {
title: `${getMetaKeyLabel()}I to add instructions`,
command: "",
}),
);
}
}
return codeLenses;

View file

@ -1,7 +1,7 @@
import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
import { Message } from "core/protocol/messenger";
import { WebviewMessengerResult } from "core/protocol/util";
import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
import { Message } from "core/protocol/messenger";
import { Telemetry } from "core/util/posthog";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
@ -140,25 +140,6 @@ export class VsCodeWebviewProtocol
},
false,
);
vscode.window
.showErrorMessage(
message.split("\n\n")[0],
"Show Logs",
"Troubleshooting",
)
.then((selection) => {
if (selection === "Show Logs") {
vscode.commands.executeCommand(
"workbench.action.toggleDevTools",
);
} else if (selection === "Troubleshooting") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://docs.continue.dev/troubleshooting",
),
);
}
});
}
}
}

View file

@ -1,23 +1,16 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint",
"strict-null-checks",
"eslint-plugin-react"
],
"plugins": ["@typescript-eslint", "eslint-plugin-react"],
"parserOptions": {
"project": "gui/tsconfig.strictNullChecks.json"
},
// "extends": [
// "eslint:recommended",
// "plugin:@typescript-eslint/recommended",
// "plugin:@typescript-eslint/recommended-requiring-type-checking"
// "plugin:react/recommended"
// ],
"rules": {
"strict-null-checks/all": "warn"
"project": "gui/tsconfig.json"
},
"extends": [
// "eslint:recommended",
// "plugin:@typescript-eslint/recommended",
// "plugin:@typescript-eslint/recommended-requiring-type-checking"
// "plugin:react/recommended"
],
"overrides": [
{
"files": ["src/**/*.{js,ts,jsx,tsx}"]

372
gui/package-lock.json generated
View file

@ -24,6 +24,7 @@
"@tiptap/react": "^2.1.13",
"@tiptap/starter-kit": "^2.1.13",
"@tiptap/suggestion": "^2.1.13",
"@types/uuid": "^10.0.0",
"@types/vscode-webview": "^1.57.1",
"core": "file:../core",
"dompurify": "^3.0.6",
@ -70,6 +71,7 @@
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^16.0.1",
"@testing-library/user-event": "^14.5.2",
"@types/dompurify": "^3.2.0",
"@types/lodash": "^4.17.6",
"@types/mustache": "^4.2.5",
"@types/node": "^20.5.6",
@ -85,7 +87,6 @@
"autoprefixer": "^10.4.13",
"eslint": "^8",
"eslint-plugin-react": "^7.37.2",
"eslint-plugin-strict-null-checks": "^0.1.3",
"jsdom": "^25.0.1",
"postcss": "^8.4.21",
"tailwindcss": "^3.2.7",
@ -2894,6 +2895,16 @@
"@types/ms": "*"
}
},
"node_modules/@types/dompurify": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/@types/dompurify/-/dompurify-3.2.0.tgz",
"integrity": "sha512-Fgg31wv9QbLDA0SpTOXO3MaxySc4DKGLi8sna4/Utjo4r3ZRPdCt4UQee8BWr+Q5z21yifghREPJGYaEOEIACg==",
"deprecated": "This is a stub types definition. dompurify provides its own type definitions, so you do not need this installed.",
"dev": true,
"dependencies": {
"dompurify": "*"
}
},
"node_modules/@types/estree": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz",
@ -2936,12 +2947,6 @@
"integrity": "sha512-1m0bIFVc7eJWyve9S0RnuRgcQqF/Xd5QsUZAZeQFr1Q3/p9JWoQQEqmVy+DPTNpGXwhgIetAoYF8JSc33q29QA==",
"dev": true
},
"node_modules/@types/json-schema": {
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
"integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
"dev": true
},
"node_modules/@types/katex": {
"version": "0.16.7",
"resolved": "https://registry.npmjs.org/@types/katex/-/katex-0.16.7.tgz",
@ -3062,12 +3067,6 @@
"@types/node": "*"
}
},
"node_modules/@types/semver": {
"version": "7.5.8",
"resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz",
"integrity": "sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==",
"dev": true
},
"node_modules/@types/styled-components": {
"version": "5.1.34",
"resolved": "https://registry.npmjs.org/@types/styled-components/-/styled-components-5.1.34.tgz",
@ -3089,6 +3088,11 @@
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg=="
},
"node_modules/@types/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ=="
},
"node_modules/@types/vscode-webview": {
"version": "1.57.5",
"resolved": "https://registry.npmjs.org/@types/vscode-webview/-/vscode-webview-1.57.5.tgz",
@ -3602,15 +3606,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/array-union": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz",
"integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==",
"dev": true,
"engines": {
"node": ">=8"
}
},
"node_modules/array.prototype.findlast": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz",
@ -4671,18 +4666,6 @@
"integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==",
"dev": true
},
"node_modules/dir-glob": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz",
"integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==",
"dev": true,
"dependencies": {
"path-type": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/direction": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/direction/-/direction-1.0.4.tgz",
@ -5151,262 +5134,6 @@
"semver": "bin/semver.js"
}
},
"node_modules/eslint-plugin-strict-null-checks": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/eslint-plugin-strict-null-checks/-/eslint-plugin-strict-null-checks-0.1.3.tgz",
"integrity": "sha512-c0bByePJytPXxZF9jBH17UQO41aCK08zThIXcAO3EnkdLhqUqIr+LVMfPstrN/9dLNzh4YKIbkbRPhRXRnNfNQ==",
"dev": true,
"dependencies": {
"@typescript-eslint/eslint-plugin": "^5.13.0",
"@typescript-eslint/experimental-utils": "^5.13.0",
"@typescript-eslint/parser": "^5.13.0",
"requireindex": "^1.2.0"
},
"peerDependencies": {
"typescript": ">=3.9.4"
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/@typescript-eslint/eslint-plugin": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz",
"integrity": "sha512-TiZzBSJja/LbhNPvk6yc0JrX9XqhQ0hdh6M2svYfsHGejaKFIAGd9MQ+ERIMzLGlN/kZoYIgdxFV0PuljTKXag==",
"dev": true,
"dependencies": {
"@eslint-community/regexpp": "^4.4.0",
"@typescript-eslint/scope-manager": "5.62.0",
"@typescript-eslint/type-utils": "5.62.0",
"@typescript-eslint/utils": "5.62.0",
"debug": "^4.3.4",
"graphemer": "^1.4.0",
"ignore": "^5.2.0",
"natural-compare-lite": "^1.4.0",
"semver": "^7.3.7",
"tsutils": "^3.21.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/@typescript-eslint/experimental-utils": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-5.62.0.tgz",
"integrity": "sha512-RTXpeB3eMkpoclG3ZHft6vG/Z30azNHuqY6wKPBHlVMZFuEvrtlEDe8gMqDb+SO+9hjC/pLekeSCryf9vMZlCw==",
"dev": true,
"dependencies": {
"@typescript-eslint/utils": "5.62.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/@typescript-eslint/parser": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz",
"integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==",
"dev": true,
"dependencies": {
"@typescript-eslint/scope-manager": "5.62.0",
"@typescript-eslint/types": "5.62.0",
"@typescript-eslint/typescript-estree": "5.62.0",
"debug": "^4.3.4"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/@typescript-eslint/scope-manager": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz",
"integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==",
"dev": true,
"dependencies": {
"@typescript-eslint/types": "5.62.0",
"@typescript-eslint/visitor-keys": "5.62.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/@typescript-eslint/type-utils": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.62.0.tgz",
"integrity": "sha512-xsSQreu+VnfbqQpW5vnCJdq1Z3Q0U31qiWmRhr98ONQmcp/yhiPJFPq8MXiJVLiksmOKSjIldZzkebzHuCGzew==",
"dev": true,
"dependencies": {
"@typescript-eslint/typescript-estree": "5.62.0",
"@typescript-eslint/utils": "5.62.0",
"debug": "^4.3.4",
"tsutils": "^3.21.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "*"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/@typescript-eslint/types": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz",
"integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==",
"dev": true,
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/@typescript-eslint/typescript-estree": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz",
"integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==",
"dev": true,
"dependencies": {
"@typescript-eslint/types": "5.62.0",
"@typescript-eslint/visitor-keys": "5.62.0",
"debug": "^4.3.4",
"globby": "^11.1.0",
"is-glob": "^4.0.3",
"semver": "^7.3.7",
"tsutils": "^3.21.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/@typescript-eslint/utils": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.62.0.tgz",
"integrity": "sha512-n8oxjeb5aIbPFEtmQxQYOLI0i9n5ySBEY/ZEHHZqKQSFnxio1rv6dthascc9dLuwrL0RC5mPCxB7vnAVGAYWAQ==",
"dev": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@types/json-schema": "^7.0.9",
"@types/semver": "^7.3.12",
"@typescript-eslint/scope-manager": "5.62.0",
"@typescript-eslint/types": "5.62.0",
"@typescript-eslint/typescript-estree": "5.62.0",
"eslint-scope": "^5.1.1",
"semver": "^7.3.7"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/@typescript-eslint/visitor-keys": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz",
"integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==",
"dev": true,
"dependencies": {
"@typescript-eslint/types": "5.62.0",
"eslint-visitor-keys": "^3.3.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/eslint-scope": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz",
"integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==",
"dev": true,
"dependencies": {
"esrecurse": "^4.3.0",
"estraverse": "^4.1.1"
},
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/eslint-scope/node_modules/estraverse": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz",
"integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==",
"dev": true,
"engines": {
"node": ">=4.0"
}
},
"node_modules/eslint-plugin-strict-null-checks/node_modules/eslint-visitor-keys": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",
"integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",
"dev": true,
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"url": "https://opencollective.com/eslint"
}
},
"node_modules/eslint-scope": {
"version": "7.2.2",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz",
@ -6303,26 +6030,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/globby": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz",
"integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==",
"dev": true,
"dependencies": {
"array-union": "^2.1.0",
"dir-glob": "^3.0.1",
"fast-glob": "^3.2.9",
"ignore": "^5.2.0",
"merge2": "^1.4.1",
"slash": "^3.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/gopd": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz",
@ -8916,12 +8623,6 @@
"integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",
"dev": true
},
"node_modules/natural-compare-lite": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/natural-compare-lite/-/natural-compare-lite-1.4.0.tgz",
"integrity": "sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==",
"dev": true
},
"node_modules/node-releases": {
"version": "2.0.18",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz",
@ -9331,15 +9032,6 @@
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
"dev": true
},
"node_modules/path-type": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz",
"integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==",
"dev": true,
"engines": {
"node": ">=8"
}
},
"node_modules/pathe": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
@ -10875,15 +10567,6 @@
"node": ">=0.10.0"
}
},
"node_modules/requireindex": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/requireindex/-/requireindex-1.2.0.tgz",
"integrity": "sha512-L9jEkOi3ASd9PYit2cwRfyppc9NoABujTP8/5gFcbERmo5jUoAKovIC3fsF17pkTnGsrByysqX+Kxd2OTNI1ww==",
"dev": true,
"engines": {
"node": ">=0.10.5"
}
},
"node_modules/reselect": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz",
@ -12094,27 +11777,6 @@
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz",
"integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA=="
},
"node_modules/tsutils": {
"version": "3.21.0",
"resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz",
"integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==",
"dev": true,
"dependencies": {
"tslib": "^1.8.1"
},
"engines": {
"node": ">= 6"
},
"peerDependencies": {
"typescript": ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta"
}
},
"node_modules/tsutils/node_modules/tslib": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
"dev": true
},
"node_modules/type-check": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",

View file

@ -32,6 +32,7 @@
"@tiptap/react": "^2.1.13",
"@tiptap/starter-kit": "^2.1.13",
"@tiptap/suggestion": "^2.1.13",
"@types/uuid": "^10.0.0",
"@types/vscode-webview": "^1.57.1",
"core": "file:../core",
"dompurify": "^3.0.6",
@ -78,6 +79,7 @@
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^16.0.1",
"@testing-library/user-event": "^14.5.2",
"@types/dompurify": "^3.2.0",
"@types/lodash": "^4.17.6",
"@types/mustache": "^4.2.5",
"@types/node": "^20.5.6",
@ -93,7 +95,6 @@
"autoprefixer": "^10.4.13",
"eslint": "^8",
"eslint-plugin-react": "^7.37.2",
"eslint-plugin-strict-null-checks": "^0.1.3",
"jsdom": "^25.0.1",
"postcss": "^8.4.21",
"tailwindcss": "^3.2.7",

BIN
gui/public/logos/novita.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

View file

@ -1,4 +1,3 @@
import { useState } from "react";
import styled from "styled-components";
import { defaultBorderRadius, vscBackground, vscForeground } from ".";
import { CheckIcon } from "@heroicons/react/24/outline";

View file

@ -8,8 +8,8 @@ import FileIcon from "../FileIcon";
import { useAppSelector } from "../../redux/hooks";
export interface AddFileComboboxProps {
onSelect: (filepaths: string[]) => void;
onEscape: () => void;
onSelect: (filepaths: string[]) => void | Promise<void>;
onEscape: () => void | Promise<void>;
}
export default function AddFileCombobox({
@ -50,7 +50,7 @@ export default function AddFileCombobox({
value={selectedFiles}
onChange={(files) => {
setSelectedFiles(files);
onSelect(files.map((file) => file.id));
void onSelect(files.map((file) => file.id));
buttonRef.current?.click();
}}
>
@ -72,7 +72,7 @@ export default function AddFileCombobox({
placeholder="Type to search files..."
onKeyDown={(e) => {
if (e.key === "Escape" && !open) {
onEscape();
void onEscape();
}
}}
/>

View file

@ -2,7 +2,7 @@ import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import CodeToEditListItem from "./CodeToEditListItem";
import type { CodeToEdit, RangeInFileWithContents } from "core";
import type { CodeToEdit } from "core";
import AddFileButton from "./AddFileButton";
import AddFileCombobox from "./AddFileCombobox";
import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline";
@ -25,19 +25,19 @@ export default function CodeToEditCard() {
? "Code to edit (1 item)"
: `Code to edit (${codeToEdit.length} items)`;
function onDelete(rif: RangeInFileWithContents) {
function onDelete(rif: CodeToEdit) {
dispatch(removeCodeToEdit(rif));
}
function onClickFilename(code: CodeToEdit) {
async function onClickFilename(code: CodeToEdit) {
if ("range" in code) {
ideMessenger.ide.showLines(
await ideMessenger.ide.showLines(
code.filepath,
code.range.start.line,
code.range.end.line,
);
} else {
ideMessenger.ide.openFile(code.filepath);
await ideMessenger.ide.openFile(code.filepath);
}
}
@ -93,10 +93,10 @@ export default function CodeToEditCard() {
/>
</div>
<XMarkIcon
onClick={(e) => {
onClick={() => {
setShowAddFileCombobox(false);
}}
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground mb-2 h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 hover:bg-opacity-20"
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground mb-2 h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20"
/>
</div>
)}

View file

@ -16,8 +16,8 @@ import {
export interface CodeToEditListItemProps {
code: CodeToEdit;
onDelete: (codeToEdit: CodeToEdit) => void;
onClickFilename: (codeToEdit: CodeToEdit) => void;
onDelete: (codeToEdit: CodeToEdit) => void | Promise<void>;
onClickFilename: (codeToEdit: CodeToEdit) => void | Promise<void>;
}
const NoPaddingWrapper = styled.div`
@ -87,7 +87,7 @@ export default function CodeToEditListItem({
className="flex-shrink-0 text-xs hover:underline"
onClick={(e) => {
e.stopPropagation();
onClickFilename(code);
void onClickFilename(code);
}}
>
{title}
@ -98,7 +98,7 @@ export default function CodeToEditListItem({
</div>
</div>
<div className="invisible flex items-center gap-1.5 group-hover:visible">
<div className="invisible flex items-center group-hover:visible">
<div className={`flex items-center ${isInsertion ? "hidden" : ""}`}>
{showCodeSnippet ? (
<ChevronDownIcon
@ -122,7 +122,7 @@ export default function CodeToEditListItem({
<XMarkIcon
onClick={(e) => {
e.stopPropagation();
onDelete(code);
void onDelete(code);
}}
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20"
/>

View file

@ -1,3 +1,4 @@
// @ts-ignore
import DOMPurify from "dompurify";
import { useMemo } from "react";
import { themeIcons } from "seti-file-icons";

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