From 2483abdc7b498d02d6c0405662f7c70890a4f33b Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Fri, 14 Feb 2025 09:43:32 -0500 Subject: [PATCH 001/709] Reliably trigger VSCode extension rebuild The code to trigger a rebuild on missing extension.js added in https://github.com/continuedev/continue/pull/3276 turns out not to be entirely reliable because esbuild sometimes falls back to full-contents comparison rather than using the modtime. To fix this, include a buildTimestamp file in the input, and rewrite that when we want to trigger a rebuild. --- extensions/vscode/.gitignore | 1 + extensions/vscode/scripts/esbuild.js | 11 +++++++---- extensions/vscode/scripts/prepackage.js | 5 ++++- extensions/vscode/scripts/utils.js | 15 +++++++++++++++ extensions/vscode/src/extension.ts | 1 + 5 files changed, 28 insertions(+), 5 deletions(-) diff --git a/extensions/vscode/.gitignore b/extensions/vscode/.gitignore index 29ad0b023..aa99f752c 100644 --- a/extensions/vscode/.gitignore +++ b/extensions/vscode/.gitignore @@ -3,6 +3,7 @@ node_modules/ out/ .vscode-test/ data/ +src/.buildTimestamp.ts src/client .continue diff --git a/extensions/vscode/scripts/esbuild.js b/extensions/vscode/scripts/esbuild.js index e44fc60af..c46efc427 100644 --- a/extensions/vscode/scripts/esbuild.js +++ b/extensions/vscode/scripts/esbuild.js @@ -1,5 +1,6 @@ const esbuild = require("esbuild"); const fs = require("fs"); +const { writeBuildTimestamp } = require("./utils"); const flags = process.argv.slice(2); @@ -48,6 +49,8 @@ const esbuildConfig = { }; (async () => { + // Create .buildTimestamp.js before starting the first build + writeBuildTimestamp(); // Bundles the extension into one file if (flags.includes("--watch")) { const ctx = await esbuild.context(esbuildConfig); @@ -59,9 +62,9 @@ const esbuildConfig = { // The watcher automatically notices changes to source files // so the only thing it needs to be notified about is if the // output file gets removed. - if (fs.existsSync (outFile)) { - console.log("VS Code Extension esbuild up to date"); - return; + if (fs.existsSync(outFile)) { + console.log("VS Code Extension esbuild up to date"); + return; } fs.watchFile(outFile, (current, previous) => { @@ -73,7 +76,7 @@ const esbuildConfig = { }); console.log("Triggering VS Code Extension esbuild rebuild..."); - fs.utimesSync(inFile, new Date(), new Date()); + writeBuildTimestamp(); } else { await esbuild.build(esbuildConfig); } diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index aeab677ca..fbec94f6c 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -10,7 +10,7 @@ const { autodetectPlatformAndArch, } = require("../../../scripts/util/index"); -const { copyConfigSchema } = require("./utils"); +const { copyConfigSchema, writeBuildTimestamp } = require("./utils"); // Clear folders that will be packaged to ensure clean slate rimrafSync(path.join(__dirname, "..", "bin")); @@ -71,6 +71,9 @@ const isMacTarget = target?.startsWith("darwin"); process.chdir("extensions/vscode"); } + // Make sure we have an initial timestamp file + writeBuildTimestamp(); + // Install node_modules // execCmdSync("npm install"); console.log("[info] npm install in extensions/vscode completed"); diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index c4d392cfa..8a144731f 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -511,6 +511,20 @@ async function copyScripts() { console.log("[info] Copied script files"); } +// We can't simply touch one of our files to trigger a rebuild, because +// esbuild doesn't always use modifications times to detect changes - +// for example, if it finds a file changed within the last 3 seconds, +// it will fall back to full-contents-comparison for that file +// +// So to facilitate development workflows, we always include a timestamp string +// in the build +function writeBuildTimestamp() { + fs.writeFileSync( + "src/.buildTimestamp.ts", + `export default "${new Date().toISOString()}";\n`, + ); +} + module.exports = { copyConfigSchema, installNodeModules, @@ -526,4 +540,5 @@ module.exports = { downloadRipgrepBinary, copyTokenizers, copyScripts, + writeBuildTimestamp, }; diff --git a/extensions/vscode/src/extension.ts b/extensions/vscode/src/extension.ts index f1aa3f3e4..be2b12487 100644 --- a/extensions/vscode/src/extension.ts +++ b/extensions/vscode/src/extension.ts @@ -8,6 +8,7 @@ import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { getExtensionVersion } from "./util/util"; +export { default as buildTimestamp } from "./.buildTimestamp"; async function dynamicImportAndActivate(context: vscode.ExtensionContext) { await setupCa(); From 36673464768720d42854e4eb04b159c0f144a81f Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Mon, 24 Feb 2025 18:20:27 -0500 Subject: [PATCH 002/709] pr_checks: write build timestamp before running tsc --- .github/workflows/pr_checks.yaml | 1 + extensions/vscode/package.json | 1 + extensions/vscode/scripts/write-build-timestamp.js | 3 +++ 3 files changed, 5 insertions(+) create mode 100644 extensions/vscode/scripts/write-build-timestamp.js diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 7c005de7b..b0c1da5bd 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -250,6 +250,7 @@ jobs: - name: Type check and lint run: | cd extensions/vscode + npm run write-build-timestamp npx tsc --noEmit npm run lint diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index a25aecbd5..4a3cf4272 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -589,6 +589,7 @@ "build-test": "npm run esbuild && node esbuild.test.mjs", "test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", "quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", + "write-build-timestamp": "node scripts/write-build-timestamp.js", "prepackage": "node scripts/prepackage.js", "package": "node scripts/package.js", "package-all": "node scripts/package-all.js", diff --git a/extensions/vscode/scripts/write-build-timestamp.js b/extensions/vscode/scripts/write-build-timestamp.js new file mode 100644 index 000000000..a26f9b8d3 --- /dev/null +++ b/extensions/vscode/scripts/write-build-timestamp.js @@ -0,0 +1,3 @@ +const { writeBuildTimestamp } = require("./utils"); + +writeBuildTimestamp(); From 0156409dac5a445b055ede921c1c07706759ff4e Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 12 Mar 2025 22:28:15 -0700 Subject: [PATCH 003/709] feat: use s3 for global docs cache on all docs --- CONTRIBUTING.md | 5 - core/context/providers/DocsContextProvider.ts | 54 +-- core/index.d.ts | 7 +- core/indexing/docs/DocsService.ts | 213 +++++----- .../docs/{preIndexed.ts => docsCache.ts} | 17 +- core/indexing/docs/preIndexedDocs.ts | 368 ------------------ docs/docs/customize/deep-dives/docs.mdx | 6 - .../current/customize/deep-dives/docs.md | 6 - gui/src/components/dialogs/AddDocsDialog.tsx | 11 +- .../components/indexing/DocsDetailsDialog.tsx | 34 +- gui/src/components/mainInput/MentionList.tsx | 2 +- gui/src/pages/gui/Chat.tsx | 6 - 12 files changed, 153 insertions(+), 576 deletions(-) rename core/indexing/docs/{preIndexed.ts => docsCache.ts} (59%) delete mode 100644 core/indexing/docs/preIndexedDocs.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4f7e1634f..73997880a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,7 +26,6 @@ - [Writing Context Providers](#writing-context-providers) - [Adding an LLM Provider](#adding-an-llm-provider) - [Adding Models](#adding-models) - - [Adding Pre-indexed Documentation](#adding-pre-indexed-documentation) - [📐 Continue Architecture](#-continue-architecture) - [Continue VS Code Extension](#continue-vs-code-extension) - [Continue JetBrains Extension](#continue-jetbrains-extension) @@ -212,10 +211,6 @@ While any model that works with a supported provider can be used with Continue, - LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models). - [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates. -### Adding Pre-indexed Documentation - -Continue's @docs context provider lets you easily reference entire documentation sites and then uses embeddings to add the most relevant pages to context. To make the experience as smooth as possible, we pre-index many of the most popular documentation sites. If you'd like to add new documentation to this list, just add an object to the list in [preIndexedDocs.ts](./core/indexing/docs/preIndexedDocs.ts). `startUrl` is where the crawler will start and `rootUrl` will filter out any pages not on that site and under the path of `rootUrl`. - ## 📐 Continue Architecture Continue consists of 2 parts that are split so that it can be extended to work in other IDEs as easily as possible: diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 3b9fa0cf4..360e68670 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -9,7 +9,6 @@ import { LoadSubmenuItemsArgs, } from "../.."; import DocsService from "../../indexing/docs/DocsService"; -import preIndexedDocs from "../../indexing/docs/preIndexedDocs"; import { INSTRUCTIONS_BASE_ITEM } from "./utils"; @@ -64,23 +63,12 @@ class DocsContextProvider extends BaseContextProvider { return chunksCopy; } - private _sortByPreIndexedDocs( + private _sortAlphabetically( submenuItems: ContextSubmenuItem[], ): ContextSubmenuItem[] { - // Sort submenuItems such that the objects with titles which don't occur in configs occur first, and alphabetized + // Sort submenu items alphabetically by title return submenuItems.sort((a, b) => { - const aTitleInConfigs = a.metadata?.preIndexed ?? false; - const bTitleInConfigs = b.metadata?.preIndexed ?? false; - - // Primary criterion: Items not in configs come first - if (!aTitleInConfigs && bTitleInConfigs) { - return -1; - } else if (aTitleInConfigs && !bTitleInConfigs) { - return 1; - } else { - // Secondary criterion: Alphabetical order when both items are in the same category - return a.title.toString().localeCompare(b.title.toString()); - } + return a.title.toString().localeCompare(b.title.toString()); }); } @@ -165,13 +153,13 @@ class DocsContextProvider extends BaseContextProvider { } await docsService.isInitialized; - // Create map of docs url -> submenu item - const submenuItemsMap = new Map(); + // Create an array to hold submenu items + const submenuItems: ContextSubmenuItem[] = []; - // Add custom docs from config + // Get all indexed docs from the database const docs = (await docsService.listMetadata()) ?? []; for (const { startUrl, title, favicon } of docs) { - submenuItemsMap.set(startUrl, { + submenuItems.push({ title, id: startUrl, description: new URL(startUrl).hostname, @@ -179,32 +167,8 @@ class DocsContextProvider extends BaseContextProvider { }); } - // Add pre-indexed docs if supported - const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); - if (canUsePreindexedDocs) { - for (const { startUrl, title } of Object.values(preIndexedDocs)) { - // Skip if overridden in config - if (docs.find((d) => d.startUrl === startUrl)) { - continue; - } - submenuItemsMap.set(startUrl, { - title, - id: startUrl, - description: new URL(startUrl).hostname, - metadata: { - preIndexed: true, - }, - }); - } - } - - // Create array and sort if pre-indexed is supported - const submenuItems = Array.from(submenuItemsMap.values()); - if (canUsePreindexedDocs) { - return this._sortByPreIndexedDocs(submenuItems); - } - - return submenuItems; + // Sort alphabetically + return this._sortAlphabetically(submenuItems); } } diff --git a/core/index.d.ts b/core/index.d.ts index f9daec503..b85b96545 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -164,7 +164,11 @@ export interface ILLM extends LLMOptions { } export interface ModelInstaller { - installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise; + installModel( + modelName: string, + signal: AbortSignal, + progressReporter?: (task: string, increment: number, total: number) => void, + ): Promise; } export type ContextProviderType = "normal" | "query" | "submenu"; @@ -240,7 +244,6 @@ export interface DocsIndexingDetails { config: SiteIndexingConfig; indexingStatus: IndexingStatus | undefined; chunks: Chunk[]; - isPreIndexedDoc: boolean; } export interface IContextProvider { diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 75f92b145..42f485068 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -39,11 +39,10 @@ import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler"; import { runLanceMigrations, runSqliteMigrations } from "./migrations"; import { downloadFromS3, - getS3Filename, + getS3CacheKey, S3Buckets, SiteIndexingResults, -} from "./preIndexed"; -import preIndexedDocs from "./preIndexedDocs"; +} from "./docsCache"; import type * as LanceType from "vectordb"; @@ -89,7 +88,7 @@ export default class DocsService { static lanceTableName = "docs"; static sqlitebTableName = "docs"; - static preIndexedDocsEmbeddingsProvider = + static defaultEmbeddingsProvider = new TransformersJsEmbeddingsProvider(); public isInitialized: Promise; @@ -250,12 +249,8 @@ export default class DocsService { return false; } - /* - * Currently, we generate and host embeddings for pre-indexed docs using transformers. - * However, we don't ship transformers with the JetBrains extension. - * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. - */ - async canUsePreindexedDocs() { + // Determine if transformers.js embeddings are supported in this environment + async canUseTransformersEmbeddings() { const ideInfo = await this.ideInfoPromise; if (ideInfo.ideType === "jetbrains") { return false; @@ -263,28 +258,26 @@ export default class DocsService { return true; } - // Determines if using preIndexed and returns proper embeddings provider - async getEmbeddingsProvider(startUrl: string) { - // Conditions for using a pre-indexed doc - - // Must be in pre indexed docs file - const preIndexedDoc = preIndexedDocs[startUrl]; - if (preIndexedDoc) { - // Most not be overriden by config - if (!this.config?.docs?.find((doc) => doc.startUrl === startUrl)) { - // Must be supported - const canUsePreindexedDocs = await this.canUsePreindexedDocs(); - if (canUsePreindexedDocs) { - return { - provider: DocsService.preIndexedDocsEmbeddingsProvider, - isPreindexed: true, - }; - } - } + // Get the appropriate embeddings provider + async getEmbeddingsProvider() { + // First check if there's a config selected embeddings provider + if (this.config.selectedModelByRole.embed) { + return { + provider: this.config.selectedModelByRole.embed, + }; } + + // Fall back to transformers if supported + const canUseTransformers = await this.canUseTransformersEmbeddings(); + if (canUseTransformers) { + return { + provider: DocsService.defaultEmbeddingsProvider, + }; + } + + // No provider available return { - provider: this.config.selectedModelByRole.embed, - isPreindexed: false, + provider: undefined, }; } @@ -392,16 +385,39 @@ export default class DocsService { return; } - const { isPreindexed, provider } = - await this.getEmbeddingsProvider(startUrl); - if (isPreindexed) { - console.warn("Attempted to indexAndAdd pre-indexed doc"); - return; - } + const { provider } = await this.getEmbeddingsProvider(); if (!provider) { console.warn("@docs indexAndAdd: no embeddings provider found"); return; } + + // Try to fetch from cache first before crawling + if (!forceReindex) { + try { + const cacheHit = await this.tryFetchFromCache(startUrl, provider.embeddingId); + if (cacheHit) { + console.log(`Successfully loaded cached embeddings for ${startUrl}`); + // Update status to complete + this.handleStatusUpdate({ + type: "docs", + id: startUrl, + embeddingsProviderId: provider.embeddingId, + isReindexing: false, + title: siteIndexingConfig.title, + debugInfo: "Loaded from cache", + icon: siteIndexingConfig.faviconUrl, + url: startUrl, + progress: 1, + description: "Complete", + status: "complete", + }); + return; + } + } catch (e) { + console.log(`Error trying to fetch from cache: ${e}`); + // Continue with regular indexing + } + } const startedWithEmbedder = provider.embeddingId; @@ -705,36 +721,49 @@ export default class DocsService { } } - // When user requests a pre-indexed doc for the first time - // And pre-indexed embeddings are supported - // Fetch pre-indexed embeddings from S3, add to Lance, and then search those - private async fetchAndAddPreIndexedDocEmbeddings(title: string) { - const data = await downloadFromS3( - S3Buckets.continueIndexedDocs, - getS3Filename( - DocsService.preIndexedDocsEmbeddingsProvider.embeddingId, - title, - ), - ); + /** + * Try to fetch embeddings from the S3 cache for any document URL + * @param startUrl The URL of the documentation site + * @param embeddingsProviderId The ID of the embeddings provider + * @returns True if cache hit and successfully loaded, false otherwise + */ + private async tryFetchFromCache( + startUrl: string, + embeddingsProviderId: string + ): Promise { + try { + // Generate a cache key for this URL and embeddings provider + const cacheKey = getS3CacheKey(embeddingsProviderId, startUrl); + + // Attempt to download from S3 cache + const data = await downloadFromS3( + S3Buckets.docsEmbeddingsCache, + cacheKey + ); - const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; - const startUrl = new URL(siteEmbeddings.url).toString(); + // Parse the cached data + const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; + + // Try to get a favicon for the site + const favicon = await fetchFavicon(new URL(startUrl)); - const faviconUrl = preIndexedDocs[startUrl].faviconUrl; - const favicon = - typeof faviconUrl === "string" - ? await getFaviconBase64(faviconUrl) - : undefined; + // Add the cached embeddings to our database + await this.add({ + favicon, + siteIndexingConfig: { + startUrl, + title: siteEmbeddings.title || new URL(startUrl).hostname, + }, + chunks: siteEmbeddings.chunks, + embeddings: siteEmbeddings.chunks.map((c) => c.embedding), + }); - await this.add({ - favicon, - siteIndexingConfig: { - startUrl, - title: siteEmbeddings.title, - }, - chunks: siteEmbeddings.chunks, - embeddings: siteEmbeddings.chunks.map((c) => c.embedding), - }); + return true; + } catch (e) { + // Cache miss or error - silently fail + console.log(`Cache miss for ${startUrl} with provider ${embeddingsProviderId}`); + return false; + } } // Retrieve docs embeds based on user input @@ -743,8 +772,7 @@ export default class DocsService { startUrl: string, nRetrieve: number, ) { - const { isPreindexed, provider } = - await this.getEmbeddingsProvider(startUrl); + const { provider } = await this.getEmbeddingsProvider(); if (!provider) { void this.ide.showToast( @@ -755,15 +783,11 @@ export default class DocsService { return []; } - if (isPreindexed) { - void Telemetry.capture("docs_pre_indexed_doc_used", { - doc: preIndexedDocs[startUrl]!["title"], - }); - } - + // Try to get embeddings for the query const [vector] = await provider.embed([query]); - - return await this.retrieveChunks(startUrl, vector, nRetrieve, isPreindexed); + + // Retrieve chunks using the query vector + return await this.retrieveChunks(startUrl, vector, nRetrieve); } private lanceDBRowToChunk(row: LanceDbDocsRow): Chunk { @@ -783,8 +807,7 @@ export default class DocsService { const db = await this.getOrCreateSqliteDb(); try { - const { isPreindexed, provider } = - await this.getEmbeddingsProvider(startUrl); + const { provider } = await this.getEmbeddingsProvider(); if (!provider) { throw new Error("No embeddings model set"); @@ -819,22 +842,26 @@ export default class DocsService { config: siteIndexingConfig, indexingStatus: this.statuses.get(startUrl), chunks: rows.map(this.lanceDBRowToChunk), - isPreIndexedDoc: isPreindexed, }; } catch (e) { console.warn("Error getting details", e); throw e; } } - // This is split into its own function so that it can be recursive - // in the case of fetching preindexed docs from s3 + // This function attempts to retrieve chunks by vector similarity + // It will also attempt to fetch from cache if no results are found async retrieveChunks( startUrl: string, vector: number[], nRetrieve: number, - isPreindexed: boolean, isRetry: boolean = false, ): Promise { + // Get the appropriate embeddings provider + const { provider } = await this.getEmbeddingsProvider(); + if (!provider) { + return []; + } + // Lance doesn't have an embeddingsprovider column, instead it includes it in the table name const table = await this.getOrCreateLanceTable({ initializationVector: vector, @@ -852,15 +879,19 @@ export default class DocsService { console.warn("Error retrieving chunks from LanceDB", e); } - // No docs are found for preindexed? try fetching once - if (docs.length === 0 && isPreindexed) { - if (isRetry) { - return []; + // If no docs are found and this isn't a retry, try fetching from S3 cache + if (docs.length === 0 && !isRetry) { + try { + // Try to fetch the document from the S3 cache + const cacheHit = await this.tryFetchFromCache(startUrl, provider.embeddingId); + + if (cacheHit) { + // If cache hit, retry the search once + return await this.retrieveChunks(startUrl, vector, nRetrieve, true); + } + } catch (e) { + console.warn("Error trying to fetch from cache:", e); } - await this.fetchAndAddPreIndexedDocEmbeddings( - preIndexedDocs[startUrl]!["title"], - ); - return await this.retrieveChunks(startUrl, vector, nRetrieve, true, true); } return docs.map(this.lanceDBRowToChunk); @@ -933,11 +964,9 @@ export default class DocsService { const currentlyIndexedDocs = await this.listMetadata(); const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); - // Anything found in sqlite but not in new config should be deleted if not preindexed + // Anything found in sqlite but not in new config should be deleted const deletedDocs = currentlyIndexedDocs.filter( - (doc) => - !preIndexedDocs[doc.startUrl] && - !newConfigStartUrls.includes(doc.startUrl), + (doc) => !newConfigStartUrls.includes(doc.startUrl), ); // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed @@ -1063,7 +1092,7 @@ export default class DocsService { const conn = await lance.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); - const { provider } = await this.getEmbeddingsProvider(startUrl); + const { provider } = await this.getEmbeddingsProvider(); if (!provider) { throw new Error( diff --git a/core/indexing/docs/preIndexed.ts b/core/indexing/docs/docsCache.ts similarity index 59% rename from core/indexing/docs/preIndexed.ts rename to core/indexing/docs/docsCache.ts index b66d21e70..6f29b4af8 100644 --- a/core/indexing/docs/preIndexed.ts +++ b/core/indexing/docs/docsCache.ts @@ -2,15 +2,18 @@ import request from "request"; import { Chunk } from "../../"; -export function getS3Filename( - embeddingsProviderId: string, - title: string, -): string { - return `_TransformersJsEmbeddingsProvider::all-MiniLM-L6-v2/${title}`; +/** + * Generate a standardized S3 cache key for any doc URL. + * This creates a predictable cache key format based on the embedding provider and URL. + */ +export function getS3CacheKey(embeddingsProviderId: string, url: string): string { + // URL-encode and normalize the URL to use as cache key + const normalizedUrl = encodeURIComponent(url); + return `${embeddingsProviderId}/${normalizedUrl}`; } export enum S3Buckets { - continueIndexedDocs = "continue-indexed-docs", + docsEmbeddingsCache = "continue-indexed-docs", // Keeping same bucket name for compatibility } const AWS_REGION = "us-west-1"; @@ -27,7 +30,7 @@ export async function downloadFromS3( }); download.on("response", (response: any) => { if (response.statusCode !== 200) { - reject(new Error("There was an error retreiving the pre-indexed doc")); + reject(new Error("There was an error retrieving the cached document")); } }); diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts deleted file mode 100644 index 5342396fd..000000000 --- a/core/indexing/docs/preIndexedDocs.ts +++ /dev/null @@ -1,368 +0,0 @@ -import { SiteIndexingConfig } from "../../"; - -const preIndexedDocs: Record< - SiteIndexingConfig["startUrl"], - SiteIndexingConfig -> = { - "https://jinja.palletsprojects.com/en/3.1.x/": { - title: "Jinja", - startUrl: "https://jinja.palletsprojects.com/en/3.1.x/", - rootUrl: "https://jinja.palletsprojects.com/en/3.1.x/", - faviconUrl: "https://jinja.palletsprojects.com/favicon.ico", - }, - "https://react.dev/reference/": { - title: "React", - startUrl: "https://react.dev/reference/", - rootUrl: "https://react.dev/reference/", - faviconUrl: "https://react.dev/favicon.ico", - }, - "https://posthog.com/docs": { - title: "PostHog", - startUrl: "https://posthog.com/docs", - rootUrl: "https://posthog.com/docs", - faviconUrl: "https://posthog.com/favicon.ico", - }, - "https://expressjs.com/en/5x/api.html": { - title: "Express", - startUrl: "https://expressjs.com/en/5x/api.html", - rootUrl: "https://expressjs.com/en/5x/", - faviconUrl: "https://expressjs.com/favicon.ico", - }, - "https://platform.openai.com/docs/": { - title: "OpenAI", - startUrl: "https://platform.openai.com/docs/", - rootUrl: "https://platform.openai.com/docs/", - faviconUrl: "https://platform.openai.com/favicon.ico", - }, - "https://www.prisma.io/docs": { - title: "Prisma", - startUrl: "https://www.prisma.io/docs", - rootUrl: "https://www.prisma.io/docs", - faviconUrl: "https://www.prisma.io/favicon.ico", - }, - "https://boto3.amazonaws.com/v1/documentation/api/latest/index.html": { - title: "Boto3", - startUrl: - "https://boto3.amazonaws.com/v1/documentation/api/latest/index.html", - rootUrl: "https://boto3.amazonaws.com/v1/documentation/api/latest/", - faviconUrl: "https://boto3.amazonaws.com/favicon.ico", - }, - "https://pytorch.org/docs/stable/": { - title: "Pytorch", - startUrl: "https://pytorch.org/docs/stable/", - rootUrl: "https://pytorch.org/docs/stable/", - faviconUrl: "https://pytorch.org/favicon.ico", - }, - "https://redis.io/docs/": { - title: "Redis", - startUrl: "https://redis.io/docs/", - rootUrl: "https://redis.io/docs/", - faviconUrl: "https://redis.io/favicon.ico", - }, - "https://axios-http.com/docs/intro": { - title: "Axios", - startUrl: "https://axios-http.com/docs/intro", - rootUrl: "https://axios-http.com/docs", - faviconUrl: "https://axios-http.com/favicon.ico", - }, - "https://redwoodjs.com/docs/introduction": { - title: "Redwood JS", - startUrl: "https://redwoodjs.com/docs/introduction", - rootUrl: "https://redwoodjs.com/docs", - faviconUrl: "https://redwoodjs.com/favicon.ico", - }, - "https://graphql.org/learn/": { - title: "GraphQL", - startUrl: "https://graphql.org/learn/", - rootUrl: "https://graphql.org/learn/", - faviconUrl: "https://graphql.org/favicon.ico", - }, - "https://www.typescriptlang.org/docs/": { - title: "Typescript", - startUrl: "https://www.typescriptlang.org/docs/", - rootUrl: "https://www.typescriptlang.org/docs/", - faviconUrl: "https://www.typescriptlang.org/favicon.ico", - }, - "https://jestjs.io/docs/getting-started": { - title: "Jest", - startUrl: "https://jestjs.io/docs/getting-started", - rootUrl: "https://jestjs.io/docs", - faviconUrl: "https://jestjs.io/favicon.ico", - }, - "https://tailwindcss.com/docs/installation": { - title: "Tailwind CSS", - startUrl: "https://tailwindcss.com/docs/installation", - rootUrl: "https://tailwindcss.com/docs", - faviconUrl: "https://tailwindcss.com/favicon.ico", - }, - "https://vuejs.org/guide/introduction.html": { - title: "Vue.js", - startUrl: "https://vuejs.org/guide/introduction.html", - rootUrl: "https://vuejs.org", - faviconUrl: "https://vuejs.org/favicon.ico", - }, - "https://svelte.dev/docs/introduction": { - title: "Svelte", - startUrl: "https://svelte.dev/docs/introduction", - rootUrl: "https://svelte.dev/docs", - faviconUrl: "https://svelte.dev/favicon.ico", - }, - "https://docs.github.com/en/actions": { - title: "GitHub Actions", - startUrl: "https://docs.github.com/en/actions", - rootUrl: "https://docs.github.com/en/actions", - faviconUrl: "https://docs.github.com/favicon.ico", - }, - "https://nodejs.org/docs/latest/api/": { - title: "NodeJS", - startUrl: "https://nodejs.org/docs/latest/api/", - rootUrl: "https://nodejs.org/docs/latest/api/", - faviconUrl: "https://nodejs.org/favicon.ico", - }, - "https://socket.io/docs/v4/": { - title: "Socket.io", - startUrl: "https://socket.io/docs/v4/", - rootUrl: "https://socket.io/docs/v4/", - faviconUrl: "https://socket.io/favicon.ico", - }, - "https://docs.gradle.org/current/userguide/userguide.html": { - title: "Gradle", - startUrl: "https://docs.gradle.org/current/userguide/userguide.html", - rootUrl: "https://docs.gradle.org/current", - faviconUrl: "https://docs.gradle.org/favicon.ico", - }, - "https://redux-toolkit.js.org/introduction/getting-started": { - title: "Redux Toolkit", - startUrl: "https://redux-toolkit.js.org/introduction/getting-started", - rootUrl: "https://redux-toolkit.js.org", - faviconUrl: "https://redux-toolkit.js.org/favicon.ico", - }, - "https://docs.trychroma.com/": { - title: "Chroma", - startUrl: "https://docs.trychroma.com/", - rootUrl: "https://docs.trychroma.com/", - faviconUrl: "https://docs.trychroma.com/favicon.ico", - }, - "https://www.sqlite.org/docs.html": { - title: "SQLite", - startUrl: "https://www.sqlite.org/docs.html", - rootUrl: "https://www.sqlite.org", - faviconUrl: "https://www.sqlite.org/favicon.ico", - }, - "https://redux.js.org/introduction/getting-started": { - title: "Redux", - startUrl: "https://redux.js.org/introduction/getting-started", - rootUrl: "https://redux.js.org", - faviconUrl: "https://redux.js.org/favicon.ico", - }, - "https://prettier.io/docs/en/": { - title: "Prettier", - startUrl: "https://prettier.io/docs/en/", - rootUrl: "https://prettier.io/docs/en/", - faviconUrl: "https://prettier.io/favicon.ico", - }, - "https://code.visualstudio.com/api": { - title: "VS Code Extension API", - startUrl: "https://code.visualstudio.com/api", - rootUrl: "https://code.visualstudio.com/api", - faviconUrl: "https://code.visualstudio.com/favicon.ico", - }, - "https://docs.continue.dev/intro": { - title: "Continue", - startUrl: "https://docs.continue.dev/intro", - rootUrl: "https://docs.continue.dev", - faviconUrl: "https://docs.continue.dev/favicon.ico", - }, - "https://api.jquery.com/": { - title: "jQuery", - startUrl: "https://api.jquery.com/", - rootUrl: "https://api.jquery.com/", - faviconUrl: "https://api.jquery.com/favicon.ico", - }, - "https://docs.python.org/3/": { - title: "Python", - startUrl: "https://docs.python.org/3/", - rootUrl: "https://docs.python.org/3/", - faviconUrl: "https://docs.python.org/favicon.ico", - }, - "https://doc.rust-lang.org/book/": { - title: "Rust", - startUrl: "https://doc.rust-lang.org/book/", - rootUrl: "https://doc.rust-lang.org/book/", - faviconUrl: "https://doc.rust-lang.org/favicon.ico", - }, - "https://plugins.jetbrains.com/docs/intellij/welcome.html": { - title: "IntelliJ Platform SDK", - startUrl: "https://plugins.jetbrains.com/docs/intellij/welcome.html", - rootUrl: "https://plugins.jetbrains.com/docs/intellij", - faviconUrl: "https://plugins.jetbrains.com/favicon.ico", - }, - "https://docs.docker.com/": { - title: "Docker", - startUrl: "https://docs.docker.com/", - rootUrl: "https://docs.docker.com/", - faviconUrl: "https://docs.docker.com/favicon.ico", - }, - "https://docs.npmjs.com/": { - title: "NPM", - startUrl: "https://docs.npmjs.com/", - rootUrl: "https://docs.npmjs.com/", - faviconUrl: "https://docs.npmjs.com/favicon.ico", - }, - "https://tiptap.dev/docs/editor/introduction": { - title: "TipTap", - startUrl: "https://tiptap.dev/docs/editor/introduction", - rootUrl: "https://tiptap.dev/docs", - faviconUrl: "https://tiptap.dev/favicon.ico", - }, - "https://esbuild.github.io/": { - title: "esbuild", - startUrl: "https://esbuild.github.io/", - rootUrl: "https://esbuild.github.io/", - faviconUrl: "https://esbuild.github.io/favicon.ico", - }, - "https://tree-sitter.github.io/tree-sitter/": { - title: "Tree Sitter", - startUrl: "https://tree-sitter.github.io/tree-sitter/", - rootUrl: "https://tree-sitter.github.io/tree-sitter/", - faviconUrl: "https://tree-sitter.github.io/favicon.ico", - }, - "https://docs.netlify.com/": { - title: "Netlify", - startUrl: "https://docs.netlify.com/", - rootUrl: "https://docs.netlify.com/", - faviconUrl: "https://docs.netlify.com/favicon.ico", - }, - "https://replicate.com/docs": { - title: "Replicate", - startUrl: "https://replicate.com/docs", - rootUrl: "https://replicate.com/docs", - faviconUrl: "https://replicate.com/favicon.ico", - }, - "https://www.w3schools.com/html/default.asp": { - title: "HTML", - startUrl: "https://www.w3schools.com/html/default.asp", - rootUrl: "https://www.w3schools.com/html", - faviconUrl: "https://www.w3schools.com/favicon.ico", - }, - "https://www.w3schools.com/css/default.asp": { - title: "CSS", - startUrl: "https://www.w3schools.com/css/default.asp", - rootUrl: "https://www.w3schools.com/css", - faviconUrl: "https://www.w3schools.com/favicon.ico", - }, - "https://python.langchain.com/docs/get_started/introduction": { - title: "Langchain", - startUrl: "https://python.langchain.com/docs/get_started/introduction", - rootUrl: "https://python.langchain.com/docs", - faviconUrl: "https://python.langchain.com/favicon.ico", - }, - "https://developer.woocommerce.com/docs/": { - title: "WooCommerce", - startUrl: "https://developer.woocommerce.com/docs/", - rootUrl: "https://developer.woocommerce.com/docs/", - faviconUrl: "https://developer.woocommerce.com/favicon.ico", - }, - "https://developer.wordpress.org/reference/": { - title: "WordPress", - startUrl: "https://developer.wordpress.org/reference/", - rootUrl: "https://developer.wordpress.org/reference/", - faviconUrl: "https://developer.wordpress.org/favicon.ico", - }, - "https://doc.qt.io/qtforpython-6/quickstart.html": { - title: "PySide6", - startUrl: "https://doc.qt.io/qtforpython-6/quickstart.html", - rootUrl: "https://doc.qt.io/qtforpython-6/api.html", - faviconUrl: "https://doc.qt.io/favicon.ico", - }, - "https://getbootstrap.com/docs/5.3/getting-started/introduction/": { - title: "Bootstrap", - startUrl: "https://getbootstrap.com/docs/5.3/getting-started/introduction/", - rootUrl: "https://getbootstrap.com/docs/5.3/", - faviconUrl: "https://getbootstrap.com/favicon.ico", - }, - "https://alpinejs.dev/start-here": { - title: "Alpine.js", - startUrl: "https://alpinejs.dev/start-here", - rootUrl: "https://alpinejs.dev/", - faviconUrl: "https://alpinejs.dev/favicon.ico", - }, - "https://learn.microsoft.com/en-us/dotnet/csharp/": { - title: "C# Language Reference", - startUrl: "https://learn.microsoft.com/en-us/dotnet/csharp/", - rootUrl: "https://learn.microsoft.com/en-us/dotnet/csharp/", - faviconUrl: "https://learn.microsoft.com/favicon.ico", - }, - "https://docs.godotengine.org/en/latest/": { - title: "Godot", - startUrl: "https://docs.godotengine.org/en/latest/", - rootUrl: "https://docs.godotengine.org/en/latest/", - faviconUrl: "https://godotengine.org/favicon.ico", - }, - "https://docs.amplify.aws/react/start/": { - title: "AWS Amplify (Gen 2)", - startUrl: "https://docs.amplify.aws/react/start/", - rootUrl: "https://docs.amplify.aws/react/", - faviconUrl: "https://docs.amplify.aws/favicon.ico", - }, - "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/": { - title: "AWS SDK for JavaScript v3", - startUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/", - rootUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/", - faviconUrl: "https://docs.aws.amazon.com/favicon.ico", - }, - "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html": { - title: "AWS CDK v2", - startUrl: - "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html", - rootUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/", - faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png", - }, - "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html": { - title: "AWS CLI commands", - startUrl: - "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html", - rootUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/", - faviconUrl: "https://docs.aws.amazon.com/favicon.ico", - }, - "https://llama-stack.readthedocs.io/": { - title: "Llama Stack", - startUrl: "https://llama-stack.readthedocs.io/", - rootUrl: "https://llama-stack.readthedocs.io/", - }, - "https://go.dev/doc": { - title: "Go", - startUrl: "https://go.dev/doc", - rootUrl: "https://go.dev", - faviconUrl: "https://go.dev/favicon.ico", - }, - "https://api.flutter.dev": { - title: "Flutter", - startUrl: "https://api.flutter.dev", - rootUrl: "https://api.flutter.dev", - faviconUrl: "https://api.flutter.dev/flutter/static-assets/favicon.png", - }, - "https://api.dart.dev": { - title: "Dart", - startUrl: "https://api.dart.dev", - rootUrl: "https://api.dart.dev", - faviconUrl: "https://api.dart.dev/static-assets/favicon.png", - }, - "https://docs.asksage.ai/": { - title: "Ask Sage", - startUrl: "https://docs.asksage.ai/", - rootUrl: "https://docs.asksage.ai/", - }, - "https://angular.dev/": { - title: "Angular", - startUrl: "https://angular.dev/", - rootUrl: "https://angular.dev/", - }, - "https://docs.djangoproject.com/": { - title: "Django", - startUrl: "https://docs.djangoproject.com/", - rootUrl: "https://docs.djangoproject.com/", - } -}; - -export default preIndexedDocs; diff --git a/docs/docs/customize/deep-dives/docs.mdx b/docs/docs/customize/deep-dives/docs.mdx index ee806263e..880d7516c 100644 --- a/docs/docs/customize/deep-dives/docs.mdx +++ b/docs/docs/customize/deep-dives/docs.mdx @@ -54,12 +54,6 @@ The `@Docs` context provider works by 3. Storing the embeddings locally on your machine 4. Embedding chat input to include similar documentation chunks as context -## Pre-indexed Documentation Sites - -In VS Code, Continue offers a selection of pre-indexed documentation sites for popular frameworks and libraries. You can view the list of [available pre-indexed sites and request additions here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts). - -Pre-indexed docs are only available in VS Code because the VS Code extension ships with the Transformers.js embedder built in, while Jetbrains currently does not. You can override a pre-indexed doc to index it with your own embeddings provider by adding it to your config (unique by `startUrl`). Otherwise, it will always use Transformers.js for queries. - ## Indexing Your Own Documentation ### Hub `docs` Blocks diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md index e14ac4afc..151eb87e8 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md @@ -31,12 +31,6 @@ toc_max_heading_level: 5 3. 本地保存嵌入在你的机器上 4. 通过 `@Docs` 上下文提供者提供访问索引内容 -## 预先索引文档网站 - -我们提供一个流行的框架和库的预先索引文档网站的选择。你可以 [在这里查看可用的预先索引网站和请求附加内容](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts) 列表。 - -## 索引你自己的文档 - ### 通过 `@Docs` 上下文提供者 为了添加一个单独的文档网站,我们推荐使用 `@Docs` 上下文提供者。 diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index d421d94c4..d79c0a144 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -157,14 +157,9 @@ function AddDocsDialog() { {docsIndexingStatuses.length > 0 && ( <> -
-
- -

- Closing this dialog will not affect indexing progress -

-
-
+

+ Closing this dialog will not affect indexing progress +

)} diff --git a/gui/src/components/indexing/DocsDetailsDialog.tsx b/gui/src/components/indexing/DocsDetailsDialog.tsx index f8d0a54e9..d51ccb00f 100644 --- a/gui/src/components/indexing/DocsDetailsDialog.tsx +++ b/gui/src/components/indexing/DocsDetailsDialog.tsx @@ -1,37 +1,12 @@ -import { - CheckIcon, - InformationCircleIcon, - PencilIcon, - PlusIcon, -} from "@heroicons/react/24/outline"; -import { - DocsIndexingDetails, - IndexingStatus, - PackageDocsResult, - SiteIndexingConfig, -} from "core"; -import preIndexedDocs from "core/indexing/docs/preIndexedDocs"; +import { DocsIndexingDetails } from "core"; import { usePostHog } from "posthog-js/react"; -import { - useCallback, - useContext, - useEffect, - useLayoutEffect, - useMemo, - useRef, - useState, -} from "react"; +import { useCallback, useContext, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; -import { Input, SecondaryButton } from ".."; +import { Tooltip } from "react-tooltip"; +import { SecondaryButton } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppSelector } from "../../redux/hooks"; -import { updateConfig } from "../../redux/slices/configSlice"; -import { updateIndexingStatus } from "../../redux/slices/indexingSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import FileIcon from "../FileIcon"; -import { ToolTip } from "../gui/Tooltip"; -import DocsIndexingPeeks from "../indexing/DocsIndexingPeeks"; -import { Tooltip } from "react-tooltip"; interface DocsDetailsDialogProps { startUrl: string; @@ -89,7 +64,6 @@ function DocsDetailsDialog({ startUrl }: DocsDetailsDialogProps) { comp = (

{`Title: ${data.config.title}`}

-

{`Pre-indexed doc: ${data.isPreIndexedDoc}`}

{!data.chunks?.length ? (
No article chunks
) : ( diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index 94324b75e..e8fe0b30e 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -226,7 +226,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { tr.delete(start, tr.selection.from).scrollIntoView(), ); }, - description: "Add a new documentation source", + description: "", }); } else if (subMenuTitle === ".prompt files") { items.push({ diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 9fe39d41e..49f6d44b2 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -25,7 +25,6 @@ import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog"; import { ExploreHubCard } from "../../components/ExploreHubCard"; import { useFindWidget } from "../../components/find/FindWidget"; import TimelineItem from "../../components/gui/TimelineItem"; -import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; import resolveEditorContent from "../../components/mainInput/resolveInput"; @@ -554,11 +553,6 @@ export function Chat() {
-
- -
); } From 137d4e48fe8acbb269ae85bbedef7d2e4914d0e3 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 14 Mar 2025 14:56:54 -0700 Subject: [PATCH 004/709] Update DocsService.ts --- core/indexing/docs/DocsService.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 42f485068..0b0b5845c 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -688,7 +688,12 @@ export default class DocsService { progress: 1, }); - void this.ide.showToast("info", `Successfully indexed ${startUrl}`); + // Only show notificaitons if the user manually re-indexed, otherwise + // they are too noisy, especially when switching embeddings providers + // and we automatically re-index all docs + if (forceReindex) { + void this.ide.showToast("info", `Successfully indexed ${startUrl}`); + } this.messenger?.send("refreshSubmenuItems", { providers: ["docs"], From fe6c9a1477ab814f3cc4d0973e851701621d2c54 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 17 Mar 2025 12:31:28 -0700 Subject: [PATCH 005/709] feat: update URL replace logic --- core/indexing/docs/docsCache.ts | 7 +++++-- gui/src/components/dialogs/AddDocsDialog.tsx | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/core/indexing/docs/docsCache.ts b/core/indexing/docs/docsCache.ts index 6f29b4af8..38be390fc 100644 --- a/core/indexing/docs/docsCache.ts +++ b/core/indexing/docs/docsCache.ts @@ -6,9 +6,12 @@ import { Chunk } from "../../"; * Generate a standardized S3 cache key for any doc URL. * This creates a predictable cache key format based on the embedding provider and URL. */ -export function getS3CacheKey(embeddingsProviderId: string, url: string): string { +export function getS3CacheKey( + embeddingsProviderId: string, + url: string, +): string { // URL-encode and normalize the URL to use as cache key - const normalizedUrl = encodeURIComponent(url); + const normalizedUrl = encodeURIComponent(url.replace(/\//g, "_")); return `${embeddingsProviderId}/${normalizedUrl}`; } diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index d79c0a144..79ada6343 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -85,7 +85,7 @@ function AddDocsDialog() {

Add documentation

Add docs

- For the @docs context provider + Common documentation sites are cached for faster loading

From 8699786d5a630ddedd02752171b9d750cd6e4c0d Mon Sep 17 00:00:00 2001 From: Gaurav Bhambhani <113461154+GauravVBhambhani@users.noreply.github.com> Date: Thu, 20 Mar 2025 16:15:43 -0400 Subject: [PATCH 006/709] Decorate all active edit ranges If a user selects multiple chunks of code with cmd-I, only the most recent chunk of code is decorated as a selection. This commit addresses that problem by changing setDecorations to addDecorations, and carefully tracking which ranges are currently active in the EditDecorationManager. Additionally, overlapping or adjacent ranges are now merged seamlessly to prevent redundant highlights. --- extensions/vscode/src/commands.ts | 2 +- .../src/quickEdit/EditDecorationManager.ts | 46 +++++++++++++++++-- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index de8f5cd1e..04239ecbf 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -569,7 +569,7 @@ const getCommandsMap: ( const range = args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast); - editDecorationManager.setDecoration(editor, range); + editDecorationManager.addDecorations(editor, [range]); const rangeInFileWithContents = getRangeInFileWithContents(true, range); diff --git a/extensions/vscode/src/quickEdit/EditDecorationManager.ts b/extensions/vscode/src/quickEdit/EditDecorationManager.ts index 544287483..18991ac49 100644 --- a/extensions/vscode/src/quickEdit/EditDecorationManager.ts +++ b/extensions/vscode/src/quickEdit/EditDecorationManager.ts @@ -2,6 +2,7 @@ import vscode from "vscode"; class EditDecorationManager { private _lastEditor: vscode.TextEditor | undefined; private decorationType: vscode.TextEditorDecorationType; + private activeRangesMap: Map = new Map(); // Store unique active ranges constructor(context: vscode.ExtensionContext) { this.decorationType = vscode.window.createTextEditorDecorationType({ @@ -23,18 +24,55 @@ class EditDecorationManager { ); } - setDecoration(editor: vscode.TextEditor, range: vscode.Range) { - if (this._lastEditor) { - this._lastEditor.setDecorations(this.decorationType, []); + // Converts each range to a unique string for storing in the map + private rangeToString(range: vscode.Range): string { + return `(${range.start.line},${range.start.character})-(${range.end.line},${range.end.character})`; + } + + // Checks if two ranges are adjacent or overlapping + private rangesCoincide(range1: vscode.Range, range2: vscode.Range): boolean { + return range1.start.isEqual(range2.start) + || range1.end.isEqual(range2.start) + || range2.end.isEqual(range1.start) + || !!range1.intersection(range2); + } + + // Merges new range with existing ranges in the map + private mergeNewRange(newRange: vscode.Range): void { + let mergedRange = newRange; + const rangesToPrune: string[] = []; + + for (const [key, existingRange] of this.activeRangesMap.entries()) { + if (!this.rangesCoincide(mergedRange, existingRange)) continue; + mergedRange = mergedRange.union(existingRange); + rangesToPrune.push(key); + } + + for (const key of rangesToPrune) this.activeRangesMap.delete(key); + this.activeRangesMap.set(this.rangeToString(mergedRange), mergedRange); + } + + // Adds a new decoration to the editor and merges it with existing ranges + addDecorations(editor: vscode.TextEditor, ranges: vscode.Range[]): void { + if (this._lastEditor?.document !== editor.document) { + this.clear(); // Clear previous decorations if editor has changed } - editor.setDecorations(this.decorationType, [range]); this._lastEditor = editor; + + for (const range of ranges) this.mergeNewRange(range); + + const activeRanges = Array.from(this.activeRangesMap.values()); + if (activeRanges.length === 0) return; // No ranges to highlight + + // Update active ranges and apply decorations + editor.setDecorations(this.decorationType, activeRanges); this.updateInEditMode(true); } clear() { if (this._lastEditor) { this._lastEditor.setDecorations(this.decorationType, []); + this.activeRangesMap.clear(); this._lastEditor = undefined; this.updateInEditMode(false); } From cde405799f7b825b4ab17cbd43fadd5c670dec87 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 20 Mar 2025 19:49:57 -0700 Subject: [PATCH 007/709] organize the input box folder --- gui/src/App.tsx | 10 +-- .../index.tsx} | 30 ++++---- .../components/mainInput/ContinueButton.tsx | 74 ------------------- .../components/mainInput/ContinueInputBox.tsx | 9 +-- .../{ => belowMainInput}/ContextItemsPeek.tsx | 14 ++-- .../{ => belowMainInput}/NewSessionButton.tsx | 4 +- .../ThinkingBlockPeek.tsx | 6 +- .../{ => belowMainInput}/TutorialCard.tsx | 8 +- .../{ => tiptap}/CodeBlockComponent.tsx | 4 +- .../mainInput/{ => tiptap}/TipTapEditor.css | 0 .../mainInput/{ => tiptap}/TipTapEditor.tsx | 52 ++++++------- .../extensions}/AddCodeToEditExtension.ts | 0 .../extensions}/CodeBlockExtension.tsx | 2 +- .../extensions}/CommandsExtension.ts | 0 .../extensions}/FillerExtension.tsx | 0 .../extensions}/MentionExtension.ts | 0 .../mainInput/{ => tiptap}/getSuggestion.ts | 8 +- .../mainInput/{ => tiptap}/resolveInput.ts | 8 +- .../{ => util}/handleMetaKeyIssues.ts | 2 +- .../mainInput/{ => util}/inputModifiers.ts | 0 gui/src/editorInset/EditorInset.tsx | 4 +- gui/src/pages/gui/Chat.tsx | 8 +- gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx | 2 +- gui/src/pages/migration.tsx | 54 -------------- gui/src/redux/thunks/gatherContext.ts | 2 +- 25 files changed, 83 insertions(+), 218 deletions(-) rename gui/src/components/mainInput/{MentionList.tsx => AtMentionDropdown/index.tsx} (94%) delete mode 100644 gui/src/components/mainInput/ContinueButton.tsx rename gui/src/components/mainInput/{ => belowMainInput}/ContextItemsPeek.tsx (93%) rename gui/src/components/mainInput/{ => belowMainInput}/NewSessionButton.tsx (90%) rename gui/src/components/mainInput/{ => belowMainInput}/ThinkingBlockPeek.tsx (97%) rename gui/src/components/mainInput/{ => belowMainInput}/TutorialCard.tsx (93%) rename gui/src/components/mainInput/{ => tiptap}/CodeBlockComponent.tsx (92%) rename gui/src/components/mainInput/{ => tiptap}/TipTapEditor.css (100%) rename gui/src/components/mainInput/{ => tiptap}/TipTapEditor.tsx (95%) rename gui/src/components/mainInput/{ => tiptap/extensions}/AddCodeToEditExtension.ts (100%) rename gui/src/components/mainInput/{ => tiptap/extensions}/CodeBlockExtension.tsx (91%) rename gui/src/components/mainInput/{ => tiptap/extensions}/CommandsExtension.ts (100%) rename gui/src/components/mainInput/{ => tiptap/extensions}/FillerExtension.tsx (100%) rename gui/src/components/mainInput/{ => tiptap/extensions}/MentionExtension.ts (100%) rename gui/src/components/mainInput/{ => tiptap}/getSuggestion.ts (97%) rename gui/src/components/mainInput/{ => tiptap}/resolveInput.ts (98%) rename gui/src/components/mainInput/{ => util}/handleMetaKeyIssues.ts (98%) rename gui/src/components/mainInput/{ => util}/inputModifiers.ts (100%) delete mode 100644 gui/src/pages/migration.tsx diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 73d667292..5f37f7675 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -1,19 +1,17 @@ -import { useDispatch } from "react-redux"; import { RouterProvider, createMemoryRouter } from "react-router-dom"; import Layout from "./components/Layout"; +import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; import { VscThemeProvider } from "./context/VscTheme"; import useSetup from "./hooks/useSetup"; import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel"; +import ConfigPage from "./pages/config"; import ConfigErrorPage from "./pages/config-error"; import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; -import MigrationPage from "./pages/migration"; import MorePage from "./pages/More"; import Stats from "./pages/stats"; import { ROUTES } from "./util/navigation"; -import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; -import ConfigPage from "./pages/config"; const router = createMemoryRouter([ { @@ -57,10 +55,6 @@ const router = createMemoryRouter([ path: ROUTES.CONFIG, element: , }, - { - path: "/migration", - element: , - }, ], }, ]); diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx similarity index 94% rename from gui/src/components/mainInput/MentionList.tsx rename to gui/src/components/mainInput/AtMentionDropdown/index.tsx index 94324b75e..60cbf659a 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -39,18 +39,18 @@ import { vscListActiveBackground, vscListActiveForeground, vscQuickInputBackground, -} from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import FileIcon from "../FileIcon"; -import SafeImg from "../SafeImg"; -import AddDocsDialog from "../dialogs/AddDocsDialog"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { DiscordIcon } from "../svg/DiscordIcon"; -import { GithubIcon } from "../svg/GithubIcon"; -import { GitlabIcon } from "../svg/GitlabIcon"; -import { GoogleIcon } from "../svg/GoogleIcon"; -import { ComboBoxItem, ComboBoxItemType } from "./types"; +} from "../.."; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; +import FileIcon from "../../FileIcon"; +import SafeImg from "../../SafeImg"; +import AddDocsDialog from "../../dialogs/AddDocsDialog"; +import HeaderButtonWithToolTip from "../../gui/HeaderButtonWithToolTip"; +import { DiscordIcon } from "../../svg/DiscordIcon"; +import { GithubIcon } from "../../svg/GithubIcon"; +import { GitlabIcon } from "../../svg/GitlabIcon"; +import { GoogleIcon } from "../../svg/GoogleIcon"; +import { ComboBoxItem, ComboBoxItemType } from "../types"; const ICONS_FOR_DROPDOWN: { [key: string]: any } = { file: FolderIcon, @@ -180,7 +180,7 @@ const QueryInput = styled.textarea` resize: none; `; -interface MentionListProps { +interface AtMentionDropdownProps { items: ComboBoxItem[]; command: (item: any) => void; @@ -189,7 +189,7 @@ interface MentionListProps { onClose: () => void; } -const MentionList = forwardRef((props: MentionListProps, ref) => { +const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); @@ -512,4 +512,4 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { ); }); -export default MentionList; +export default AtMentionDropdown; diff --git a/gui/src/components/mainInput/ContinueButton.tsx b/gui/src/components/mainInput/ContinueButton.tsx deleted file mode 100644 index 23776bbcf..000000000 --- a/gui/src/components/mainInput/ContinueButton.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import { PlayIcon, StopIcon } from "@heroicons/react/24/outline"; -import styled from "styled-components"; -import { Button } from ".."; -import { getFontSize } from "../../util"; - -const StyledButton = styled(Button)<{ - color?: string | null; - isDisabled: boolean; - showStop: boolean; -}>` - margin: auto; - margin-top: 8px; - margin-bottom: 16px; - display: grid; - width: 130px; - grid-template-columns: 22px 1fr; - align-items: center; - background-color: ${(props) => - `${props.color || "#be1b55"}${props.showStop ? "33" : ""}`}; - - opacity: ${(props) => (props.isDisabled ? 0.5 : 1.0)}; - - border: 1px solid - ${(props) => (props.showStop ? props.color || "#be1b55" : "transparent")}; - - cursor: ${(props) => (props.isDisabled ? "default" : "pointer")}; - - &:hover:enabled { - background-color: ${(props) => - `${props.color || "#be1b55"}${props.showStop ? "33" : ""}`}; - ${(props) => - props.isDisabled - ? "cursor: default;" - : ` - opacity: 0.7; - `} - } -`; - -function ContinueButton(props: { - onClick?: () => void; - hidden?: boolean; - disabled: boolean; - showStop: boolean; -}) { - return ( - - ); -} - -export default ContinueButton; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 69264eb35..940584636 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,14 +1,13 @@ import { Editor, JSONContent } from "@tiptap/react"; import { ContextItemWithId, InputModifiers } from "core"; -import { useDispatch } from "react-redux"; +import { useMemo } from "react"; import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; -import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; -import ContextItemsPeek from "./ContextItemsPeek"; -import TipTapEditor from "./TipTapEditor"; import { useAppSelector } from "../../redux/hooks"; +import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; +import ContextItemsPeek from "./belowMainInput/ContextItemsPeek"; import { ToolbarOptions } from "./InputToolbar"; -import { useMemo } from "react"; +import TipTapEditor from "./tiptap/TipTapEditor"; interface ContinueInputBoxProps { isEditMode?: boolean; diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx similarity index 93% rename from gui/src/components/mainInput/ContextItemsPeek.tsx rename to gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index 9e7d34070..0b740142c 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -7,13 +7,13 @@ import { ContextItemWithId } from "core"; import { ctxItemToRifWithContents } from "core/commands/util"; import { getUriPathBasename } from "core/util/uri"; import { useContext, useMemo, useState } from "react"; -import { AnimatedEllipsis, lightGray, vscBackground } from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppSelector } from "../../redux/hooks"; -import { selectIsGatheringContext } from "../../redux/slices/sessionSlice"; -import FileIcon from "../FileIcon"; -import SafeImg from "../SafeImg"; -import { getIconFromDropdownItem } from "./MentionList"; +import { AnimatedEllipsis, lightGray, vscBackground } from "../.."; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useAppSelector } from "../../../redux/hooks"; +import { selectIsGatheringContext } from "../../../redux/slices/sessionSlice"; +import FileIcon from "../../FileIcon"; +import SafeImg from "../../SafeImg"; +import { getIconFromDropdownItem } from "../AtMentionDropdown"; interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; diff --git a/gui/src/components/mainInput/NewSessionButton.tsx b/gui/src/components/mainInput/belowMainInput/NewSessionButton.tsx similarity index 90% rename from gui/src/components/mainInput/NewSessionButton.tsx rename to gui/src/components/mainInput/belowMainInput/NewSessionButton.tsx index 04193450c..d8623af96 100644 --- a/gui/src/components/mainInput/NewSessionButton.tsx +++ b/gui/src/components/mainInput/belowMainInput/NewSessionButton.tsx @@ -1,6 +1,6 @@ import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscForeground } from ".."; -import { getFontSize } from "../../util"; +import { defaultBorderRadius, lightGray, vscForeground } from "../.."; +import { getFontSize } from "../../../util"; export const NewSessionButton = styled.div` width: fit-content; diff --git a/gui/src/components/mainInput/ThinkingBlockPeek.tsx b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx similarity index 97% rename from gui/src/components/mainInput/ThinkingBlockPeek.tsx rename to gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx index 851635230..a89ba2e6a 100644 --- a/gui/src/components/mainInput/ThinkingBlockPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx @@ -4,9 +4,9 @@ import { ChevronUpIcon } from "@heroicons/react/24/solid"; import { ChatHistoryItem } from "core"; import { useEffect, useState } from "react"; import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscBackground } from ".."; -import { getFontSize } from "../../util"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import { defaultBorderRadius, lightGray, vscBackground } from "../.."; +import { getFontSize } from "../../../util"; +import StyledMarkdownPreview from "../../markdown/StyledMarkdownPreview"; const SpoilerButton = styled.div` background-color: ${vscBackground}; diff --git a/gui/src/components/mainInput/TutorialCard.tsx b/gui/src/components/mainInput/belowMainInput/TutorialCard.tsx similarity index 93% rename from gui/src/components/mainInput/TutorialCard.tsx rename to gui/src/components/mainInput/belowMainInput/TutorialCard.tsx index c31c8f4a3..dfebdb6a4 100644 --- a/gui/src/components/mainInput/TutorialCard.tsx +++ b/gui/src/components/mainInput/belowMainInput/TutorialCard.tsx @@ -7,10 +7,10 @@ import { XMarkIcon, } from "@heroicons/react/24/outline"; import { useContext } from "react"; -import { lightGray } from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { isJetBrains } from "../../util"; -import Shortcut from "../gui/Shortcut"; +import { lightGray } from "../.."; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { isJetBrains } from "../../../util"; +import Shortcut from "../../gui/Shortcut"; interface TutorialCardProps { onClose: () => void; diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx similarity index 92% rename from gui/src/components/mainInput/CodeBlockComponent.tsx rename to gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx index 61403a261..e63e273ad 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx @@ -1,7 +1,7 @@ import { NodeViewWrapper, NodeViewWrapperProps } from "@tiptap/react"; import { ContextItemWithId } from "core"; -import { vscBadgeBackground } from ".."; -import CodeSnippetPreview from "../markdown/CodeSnippetPreview"; +import { vscBadgeBackground } from "../.."; +import CodeSnippetPreview from "../../markdown/CodeSnippetPreview"; export const CodeBlockComponent = (props: any) => { const { node, deleteNode, selected, editor, updateAttributes } = props; diff --git a/gui/src/components/mainInput/TipTapEditor.css b/gui/src/components/mainInput/tiptap/TipTapEditor.css similarity index 100% rename from gui/src/components/mainInput/TipTapEditor.css rename to gui/src/components/mainInput/tiptap/TipTapEditor.css diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx similarity index 95% rename from gui/src/components/mainInput/TipTapEditor.tsx rename to gui/src/components/mainInput/tiptap/TipTapEditor.tsx index 046da1021..56ac43096 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx @@ -29,16 +29,16 @@ import { vscForeground, vscInputBackground, vscInputBorderFocus, -} from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders"; -import { useInputHistory } from "../../hooks/useInputHistory"; -import useIsOSREnabled from "../../hooks/useIsOSREnabled"; -import useUpdatingRef from "../../hooks/useUpdatingRef"; -import { useWebviewListener } from "../../hooks/useWebviewListener"; -import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectUseActiveFile } from "../../redux/selectors"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +} from "../.."; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useSubmenuContextProviders } from "../../../context/SubmenuContextProviders"; +import { useInputHistory } from "../../../hooks/useInputHistory"; +import useIsOSREnabled from "../../../hooks/useIsOSREnabled"; +import useUpdatingRef from "../../../hooks/useUpdatingRef"; +import { useWebviewListener } from "../../../hooks/useWebviewListener"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { selectUseActiveFile } from "../../../redux/selectors"; +import { selectDefaultModel } from "../../../redux/slices/configSlice"; import { addCodeToEdit, clearCodeToEdit, @@ -46,34 +46,34 @@ import { selectIsInEditMode, setMainEditorContentTrigger, setNewestCodeblocksForInput, -} from "../../redux/slices/sessionSlice"; -import { exitEditMode } from "../../redux/thunks"; +} from "../../../redux/slices/sessionSlice"; +import { exitEditMode } from "../../../redux/thunks"; import { loadLastSession, loadSession, saveCurrentSession, -} from "../../redux/thunks/session"; +} from "../../../redux/thunks/session"; import { getFontSize, isJetBrains, isMetaEquivalentKeyPressed, -} from "../../util"; -import { AddCodeToEdit } from "./AddCodeToEditExtension"; -import { CodeBlockExtension } from "./CodeBlockExtension"; -import { SlashCommand } from "./CommandsExtension"; -import { MockExtension } from "./FillerExtension"; -import InputToolbar, { ToolbarOptions } from "./InputToolbar"; -import { Mention } from "./MentionExtension"; -import "./TipTapEditor.css"; +} from "../../../util"; +import InputToolbar, { ToolbarOptions } from "../InputToolbar"; +import { ComboBoxItem } from "../types"; +import { + handleJetBrainsOSRMetaKeyIssues, + handleVSCMetaKeyIssues, +} from "../util/handleMetaKeyIssues"; +import { AddCodeToEdit } from "./extensions/AddCodeToEditExtension"; +import { CodeBlockExtension } from "./extensions/CodeBlockExtension"; +import { SlashCommand } from "./extensions/CommandsExtension"; +import { MockExtension } from "./extensions/FillerExtension"; +import { Mention } from "./extensions/MentionExtension"; import { getContextProviderDropdownOptions, getSlashCommandDropdownOptions, } from "./getSuggestion"; -import { - handleJetBrainsOSRMetaKeyIssues, - handleVSCMetaKeyIssues, -} from "./handleMetaKeyIssues"; -import { ComboBoxItem } from "./types"; +import "./TipTapEditor.css"; const InputBoxDiv = styled.div<{}>` resize: none; diff --git a/gui/src/components/mainInput/AddCodeToEditExtension.ts b/gui/src/components/mainInput/tiptap/extensions/AddCodeToEditExtension.ts similarity index 100% rename from gui/src/components/mainInput/AddCodeToEditExtension.ts rename to gui/src/components/mainInput/tiptap/extensions/AddCodeToEditExtension.ts diff --git a/gui/src/components/mainInput/CodeBlockExtension.tsx b/gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx similarity index 91% rename from gui/src/components/mainInput/CodeBlockExtension.tsx rename to gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx index 091694db9..aea6e18af 100644 --- a/gui/src/components/mainInput/CodeBlockExtension.tsx +++ b/gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx @@ -1,6 +1,6 @@ import { mergeAttributes, Node } from "@tiptap/core"; import { ReactNodeViewRenderer } from "@tiptap/react"; -import { CodeBlockComponent } from "./CodeBlockComponent"; +import { CodeBlockComponent } from "../CodeBlockComponent"; export const CodeBlockExtension = Node.create({ name: "codeBlock", diff --git a/gui/src/components/mainInput/CommandsExtension.ts b/gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts similarity index 100% rename from gui/src/components/mainInput/CommandsExtension.ts rename to gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts diff --git a/gui/src/components/mainInput/FillerExtension.tsx b/gui/src/components/mainInput/tiptap/extensions/FillerExtension.tsx similarity index 100% rename from gui/src/components/mainInput/FillerExtension.tsx rename to gui/src/components/mainInput/tiptap/extensions/FillerExtension.tsx diff --git a/gui/src/components/mainInput/MentionExtension.ts b/gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts similarity index 100% rename from gui/src/components/mainInput/MentionExtension.ts rename to gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts diff --git a/gui/src/components/mainInput/getSuggestion.ts b/gui/src/components/mainInput/tiptap/getSuggestion.ts similarity index 97% rename from gui/src/components/mainInput/getSuggestion.ts rename to gui/src/components/mainInput/tiptap/getSuggestion.ts index ecc7b835e..932db4453 100644 --- a/gui/src/components/mainInput/getSuggestion.ts +++ b/gui/src/components/mainInput/tiptap/getSuggestion.ts @@ -6,9 +6,9 @@ import { } from "core"; import { MutableRefObject } from "react"; import tippy from "tippy.js"; -import { IIdeMessenger } from "../../context/IdeMessenger"; -import MentionList from "./MentionList"; -import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "./types"; +import { IIdeMessenger } from "../../../context/IdeMessenger"; +import AtMentionDropdown from "../AtMentionDropdown"; +import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../types"; import { TIPPY_DIV_ID } from "./TipTapEditor"; function getSuggestion( @@ -32,7 +32,7 @@ function getSuggestion( return { onStart: (props: any) => { - component = new ReactRenderer(MentionList, { + component = new ReactRenderer(AtMentionDropdown, { props: { ...props, enterSubmenu, onClose: onExit }, editor: props.editor, }); diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/tiptap/resolveInput.ts similarity index 98% rename from gui/src/components/mainInput/resolveInput.ts rename to gui/src/components/mainInput/tiptap/resolveInput.ts index 1113d2fc3..d9eb47b6c 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/tiptap/resolveInput.ts @@ -1,3 +1,4 @@ +import { Dispatch } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/react"; import { ContextItemWithId, @@ -8,12 +9,11 @@ import { RangeInFile, TextMessagePart, } from "core"; -import { stripImages } from "core/util/messageContent"; -import { IIdeMessenger } from "../../context/IdeMessenger"; -import { Dispatch } from "@reduxjs/toolkit"; -import { setIsGatheringContext } from "../../redux/slices/sessionSlice"; import { ctxItemToRifWithContents } from "core/commands/util"; +import { stripImages } from "core/util/messageContent"; import { getUriFileExtension } from "core/util/uri"; +import { IIdeMessenger } from "../../../context/IdeMessenger"; +import { setIsGatheringContext } from "../../../redux/slices/sessionSlice"; interface MentionAttrs { label: string; diff --git a/gui/src/components/mainInput/handleMetaKeyIssues.ts b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts similarity index 98% rename from gui/src/components/mainInput/handleMetaKeyIssues.ts rename to gui/src/components/mainInput/util/handleMetaKeyIssues.ts index 1adf5593a..9f9078303 100644 --- a/gui/src/components/mainInput/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts @@ -1,6 +1,6 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; -import { getPlatform, isWebEnvironment } from "../../util"; +import { getPlatform, isWebEnvironment } from "../../../util"; const isWebEnv = isWebEnvironment(); diff --git a/gui/src/components/mainInput/inputModifiers.ts b/gui/src/components/mainInput/util/inputModifiers.ts similarity index 100% rename from gui/src/components/mainInput/inputModifiers.ts rename to gui/src/components/mainInput/util/inputModifiers.ts diff --git a/gui/src/editorInset/EditorInset.tsx b/gui/src/editorInset/EditorInset.tsx index 3e90926b1..2f6d10f80 100644 --- a/gui/src/editorInset/EditorInset.tsx +++ b/gui/src/editorInset/EditorInset.tsx @@ -1,10 +1,10 @@ import { useRef } from "react"; import styled from "styled-components"; import { defaultBorderRadius } from "../components"; -import TipTapEditor from "../components/mainInput/TipTapEditor"; +import TipTapEditor from "../components/mainInput/tiptap/TipTapEditor"; import useSetup from "../hooks/useSetup"; -import { selectSlashCommandComboBoxInputs } from "../redux/selectors"; import { useAppSelector } from "../redux/hooks"; +import { selectSlashCommandComboBoxInputs } from "../redux/selectors"; const EditorInsetDiv = styled.div` max-width: 500px; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 0c1b981bb..04a1b9709 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -26,11 +26,11 @@ import { ExploreHubCard } from "../../components/ExploreHubCard"; import { useFindWidget } from "../../components/find/FindWidget"; import TimelineItem from "../../components/gui/TimelineItem"; import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks"; +import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton"; +import ThinkingBlockPeek from "../../components/mainInput/belowMainInput/ThinkingBlockPeek"; +import { TutorialCard } from "../../components/mainInput/belowMainInput/TutorialCard"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; -import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; -import resolveEditorContent from "../../components/mainInput/resolveInput"; -import ThinkingBlockPeek from "../../components/mainInput/ThinkingBlockPeek"; -import { TutorialCard } from "../../components/mainInput/TutorialCard"; +import resolveEditorContent from "../../components/mainInput/tiptap/resolveInput"; import AssistantSelect from "../../components/modelSelection/platform/AssistantSelect"; import { OnboardingCard, diff --git a/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx index 46057e90c..2289be544 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx @@ -1,5 +1,5 @@ import { ContextItemWithId } from "core"; -import ContextItemsPeek from "../../../components/mainInput/ContextItemsPeek"; +import ContextItemsPeek from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; interface ToolOutputProps { contextItems: ContextItemWithId[]; diff --git a/gui/src/pages/migration.tsx b/gui/src/pages/migration.tsx deleted file mode 100644 index b09389c59..000000000 --- a/gui/src/pages/migration.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { useNavigate } from "react-router-dom"; -import ContinueButton from "../components/mainInput/ContinueButton"; - -function MigrationPage() { - const navigate = useNavigate(); - return ( -
-

- Migration to config.json -

- -

- Continue now uses a .json config file. We hope that this takes the - guesswork out of setting up. -

- -

- Your configuration should have been automatically migrated, but we - recommend double-checking that everything looks correct. -

- -

- For a summary of what changed and examples of config.json, - please see the{" "} - - migration walkthrough - - , and if you have any questions please reach out to us on{" "} - - Discord - - . -

- - - Note: If you are running the server manually and have not updated the - server, this message does not apply. - - - { - navigate("/"); - }} - disabled={false} - /> -
- ); -} - -export default MigrationPage; diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 133363978..ebd50e644 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -7,7 +7,7 @@ import { RangeInFile, } from "core"; import * as URI from "uri-js"; -import resolveEditorContent from "../../components/mainInput/resolveInput"; +import resolveEditorContent from "../../components/mainInput/tiptap/resolveInput"; import { selectDefaultModel } from "../slices/configSlice"; import { ThunkApiType } from "../store"; From 03d8982915157515c8f80ad22b0db3644a4f601a Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 20 Mar 2025 23:24:30 -0700 Subject: [PATCH 008/709] organize TipTapEditor.tsx --- .../mainInput/tiptap/DragOverlay.tsx | 40 ++ .../mainInput/tiptap/StyledComponents.ts | 72 +++ .../mainInput/tiptap/TipTapEditor.tsx | 579 +----------------- .../mainInput/tiptap/editorConfig.ts | 409 +++++++++++++ .../components/mainInput/tiptap/imageUtils.ts | 73 +++ 5 files changed, 612 insertions(+), 561 deletions(-) create mode 100644 gui/src/components/mainInput/tiptap/DragOverlay.tsx create mode 100644 gui/src/components/mainInput/tiptap/StyledComponents.ts create mode 100644 gui/src/components/mainInput/tiptap/editorConfig.ts create mode 100644 gui/src/components/mainInput/tiptap/imageUtils.ts diff --git a/gui/src/components/mainInput/tiptap/DragOverlay.tsx b/gui/src/components/mainInput/tiptap/DragOverlay.tsx new file mode 100644 index 000000000..1417a8228 --- /dev/null +++ b/gui/src/components/mainInput/tiptap/DragOverlay.tsx @@ -0,0 +1,40 @@ +import React, { useEffect } from "react"; +import { HoverDiv, HoverTextDiv } from "./StyledComponents"; + +interface DragOverlayProps { + show: boolean; + setShow: (show: boolean) => void; +} + +export const DragOverlay: React.FC = ({ show, setShow }) => { + useEffect(() => { + const overListener = (event: DragEvent) => { + if (event.shiftKey) return; + setShow(true); + }; + window.addEventListener("dragover", overListener); + + const leaveListener = (event: DragEvent) => { + if (event.shiftKey) { + setShow(false); + } else { + setTimeout(() => setShow(false), 2000); + } + }; + window.addEventListener("dragleave", leaveListener); + + return () => { + window.removeEventListener("dragover", overListener); + window.removeEventListener("dragleave", leaveListener); + }; + }, []); + + if (!show) return null; + + return ( + <> + + Hold ⇧ to drop image + + ); +}; diff --git a/gui/src/components/mainInput/tiptap/StyledComponents.ts b/gui/src/components/mainInput/tiptap/StyledComponents.ts new file mode 100644 index 000000000..ab6fceaa3 --- /dev/null +++ b/gui/src/components/mainInput/tiptap/StyledComponents.ts @@ -0,0 +1,72 @@ +import styled from "styled-components"; +import { + defaultBorderRadius, + lightGray, + vscBadgeBackground, + vscCommandCenterActiveBorder, + vscCommandCenterInactiveBorder, + vscForeground, + vscInputBackground, + vscInputBorderFocus, +} from "../.."; +import { getFontSize } from "../../../util"; + +export const InputBoxDiv = styled.div<{}>` + resize: none; + padding-bottom: 4px; + font-family: inherit; + border-radius: ${defaultBorderRadius}; + margin: 0; + height: auto; + width: 100%; + background-color: ${vscInputBackground}; + color: ${vscForeground}; + + border: 1px solid ${vscCommandCenterInactiveBorder}; + transition: border-color 0.15s ease-in-out; + &:focus-within { + border: 1px solid ${vscCommandCenterActiveBorder}; + } + + outline: none; + font-size: ${getFontSize()}px; + + &:focus { + outline: none; + + border: 0.5px solid ${vscInputBorderFocus}; + } + + &::placeholder { + color: ${lightGray}cc; + } + + display: flex; + flex-direction: column; +`; + +export const HoverDiv = styled.div` + position: absolute; + width: 100%; + height: 100%; + top: 0; + left: 0; + opacity: 0.5; + background-color: ${vscBadgeBackground}; + color: ${vscForeground}; + display: flex; + align-items: center; + justify-content: center; +`; + +export const HoverTextDiv = styled.div` + position: absolute; + width: 100%; + height: 100%; + top: 0; + left: 0; + color: ${vscForeground}; + display: flex; + align-items: center; + justify-content: center; +`; diff --git a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx index 56ac43096..d1ae79f47 100644 --- a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx +++ b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx @@ -1,168 +1,42 @@ -import Document from "@tiptap/extension-document"; -import History from "@tiptap/extension-history"; -import Image from "@tiptap/extension-image"; -import Paragraph from "@tiptap/extension-paragraph"; -import Placeholder from "@tiptap/extension-placeholder"; -import Text from "@tiptap/extension-text"; -import { Plugin } from "@tiptap/pm/state"; -import { Editor, EditorContent, JSONContent, useEditor } from "@tiptap/react"; +import { Editor, EditorContent, JSONContent } from "@tiptap/react"; import { ContextProviderDescription, InputModifiers } from "core"; import { rifWithContentsToContextItem } from "core/commands/util"; import { modelSupportsImages } from "core/llm/autodetect"; import { debounce } from "lodash"; -import { usePostHog } from "posthog-js/react"; import { KeyboardEvent, useCallback, useContext, useEffect, - useRef, useState, } from "react"; -import styled from "styled-components"; -import { - defaultBorderRadius, - lightGray, - vscBadgeBackground, - vscCommandCenterActiveBorder, - vscCommandCenterInactiveBorder, - vscForeground, - vscInputBackground, - vscInputBorderFocus, -} from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { useSubmenuContextProviders } from "../../../context/SubmenuContextProviders"; -import { useInputHistory } from "../../../hooks/useInputHistory"; import useIsOSREnabled from "../../../hooks/useIsOSREnabled"; import useUpdatingRef from "../../../hooks/useUpdatingRef"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { selectUseActiveFile } from "../../../redux/selectors"; import { selectDefaultModel } from "../../../redux/slices/configSlice"; import { - addCodeToEdit, clearCodeToEdit, - selectHasCodeToEdit, selectIsInEditMode, setMainEditorContentTrigger, setNewestCodeblocksForInput, } from "../../../redux/slices/sessionSlice"; -import { exitEditMode } from "../../../redux/thunks"; -import { - loadLastSession, - loadSession, - saveCurrentSession, -} from "../../../redux/thunks/session"; -import { - getFontSize, - isJetBrains, - isMetaEquivalentKeyPressed, -} from "../../../util"; +import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; +import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../util"; import InputToolbar, { ToolbarOptions } from "../InputToolbar"; import { ComboBoxItem } from "../types"; import { handleJetBrainsOSRMetaKeyIssues, handleVSCMetaKeyIssues, } from "../util/handleMetaKeyIssues"; -import { AddCodeToEdit } from "./extensions/AddCodeToEditExtension"; -import { CodeBlockExtension } from "./extensions/CodeBlockExtension"; -import { SlashCommand } from "./extensions/CommandsExtension"; -import { MockExtension } from "./extensions/FillerExtension"; -import { Mention } from "./extensions/MentionExtension"; -import { - getContextProviderDropdownOptions, - getSlashCommandDropdownOptions, -} from "./getSuggestion"; +import { DragOverlay } from "./DragOverlay"; +import { createEditorConfig, getPlaceholderText } from "./editorConfig"; +import { handleImageFile } from "./imageUtils"; +import { InputBoxDiv } from "./StyledComponents"; import "./TipTapEditor.css"; -const InputBoxDiv = styled.div<{}>` - resize: none; - padding-bottom: 4px; - font-family: inherit; - border-radius: ${defaultBorderRadius}; - margin: 0; - height: auto; - width: 100%; - background-color: ${vscInputBackground}; - color: ${vscForeground}; - - border: 1px solid ${vscCommandCenterInactiveBorder}; - transition: border-color 0.15s ease-in-out; - &:focus-within { - border: 1px solid ${vscCommandCenterActiveBorder}; - } - - outline: none; - font-size: ${getFontSize()}px; - - &:focus { - outline: none; - - border: 0.5px solid ${vscInputBorderFocus}; - } - - &::placeholder { - color: ${lightGray}cc; - } - - display: flex; - flex-direction: column; -`; - -const HoverDiv = styled.div` - position: absolute; - width: 100%; - height: 100%; - top: 0; - left: 0; - opacity: 0.5; - background-color: ${vscBadgeBackground}; - color: ${vscForeground}; - display: flex; - align-items: center; - justify-content: center; -`; - -const HoverTextDiv = styled.div` - position: absolute; - width: 100%; - height: 100%; - top: 0; - left: 0; - color: ${vscForeground}; - display: flex; - align-items: center; - justify-content: center; -`; - -const IMAGE_RESOLUTION = 1024; -function getDataUrlForFile( - file: File, - img: HTMLImageElement, -): string | undefined { - const targetWidth = IMAGE_RESOLUTION; - const targetHeight = IMAGE_RESOLUTION; - const scaleFactor = Math.min( - targetWidth / img.width, - targetHeight / img.height, - ); - - const canvas = document.createElement("canvas"); - canvas.width = img.width * scaleFactor; - canvas.height = img.height * scaleFactor; - - const ctx = canvas.getContext("2d"); - if (!ctx) { - console.error("Error getting image data url: 2d context not found"); - return; - } - ctx.drawImage(img, 0, 0, canvas.width, canvas.height); - - const downsizedDataUrl = canvas.toDataURL("image/jpeg", 0.7); - return downsizedDataUrl; -} - -interface TipTapEditorProps { +export interface TipTapEditorProps { availableContextProviders: ContextProviderDescription[]; availableSlashCommands: ComboBoxItem[]; isMainInput: boolean; @@ -184,369 +58,18 @@ function TipTapEditor(props: TipTapEditorProps) { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const { getSubmenuContextItems } = useSubmenuContextProviders(); - - const historyLength = useAppSelector((store) => store.session.history.length); - - const useActiveFile = useAppSelector(selectUseActiveFile); - - const posthog = usePostHog(); - - const inSubmenuRef = useRef(undefined); - const inDropdownRef = useRef(false); const isOSREnabled = useIsOSREnabled(); - const enterSubmenu = async (editor: Editor, providerId: string) => { - const contents = editor.getText(); - const indexOfAt = contents.lastIndexOf("@"); - if (indexOfAt === -1) { - return; - } - - // Find the position of the last @ character - // We do this because editor.getText() isn't a correct representation including node views - let startPos = editor.state.selection.anchor; - while ( - startPos > 0 && - editor.state.doc.textBetween(startPos, startPos + 1) !== "@" - ) { - startPos--; - } - startPos++; - - editor.commands.deleteRange({ - from: startPos, - to: editor.state.selection.anchor, - }); - inSubmenuRef.current = providerId; - - // to trigger refresh of suggestions - editor.commands.insertContent(":"); - editor.commands.deleteRange({ - from: editor.state.selection.anchor - 1, - to: editor.state.selection.anchor, - }); - }; - - const onClose = () => { - inSubmenuRef.current = undefined; - inDropdownRef.current = false; - }; - - const onOpen = () => { - inDropdownRef.current = true; - }; - const defaultModel = useAppSelector(selectDefaultModel); - const defaultModelRef = useUpdatingRef(defaultModel); - - const getSubmenuContextItemsRef = useUpdatingRef(getSubmenuContextItems); - const availableContextProvidersRef = useUpdatingRef( - props.availableContextProviders, - ); - - const historyLengthRef = useUpdatingRef(historyLength); - const availableSlashCommandsRef = useUpdatingRef( - props.availableSlashCommands, - ); - const isStreaming = useAppSelector((state) => state.session.isStreaming); - const isStreamingRef = useUpdatingRef(isStreaming); - const isInEditMode = useAppSelector(selectIsInEditMode); - const isInEditModeRef = useUpdatingRef(isInEditMode); - const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); - const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; - async function handleImageFile( - file: File, - ): Promise<[HTMLImageElement, string] | undefined> { - let filesize = file.size / 1024 / 1024; // filesize in MB - // check image type and size - if ( - [ - "image/jpeg", - "image/jpg", - "image/png", - "image/gif", - "image/svg", - "image/webp", - ].includes(file.type) && - filesize < 10 - ) { - // check dimensions - let _URL = window.URL || window.webkitURL; - let img = new window.Image(); - img.src = _URL.createObjectURL(file); + const historyLength = useAppSelector((store) => store.session.history.length); - return await new Promise((resolve) => { - img.onload = function () { - const dataUrl = getDataUrlForFile(file, img); - if (!dataUrl) { - return; - } - - let image = new window.Image(); - image.src = dataUrl; - image.onload = function () { - resolve([image, dataUrl]); - }; - }; - }); - } else { - ideMessenger.post("showToast", [ - "error", - "Images need to be in jpg or png format and less than 10MB in size.", - ]); - } - } - - const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); - - const editor: Editor | null = useEditor({ - extensions: [ - Document, - History, - Image.extend({ - addProseMirrorPlugins() { - const plugin = new Plugin({ - props: { - handleDOMEvents: { - paste(view, event) { - const model = defaultModelRef.current; - if (!model) return; - const items = event.clipboardData?.items; - if (items) { - for (const item of items) { - const file = item.getAsFile(); - file && - modelSupportsImages( - model.provider, - model.model, - model.title, - model.capabilities, - ) && - handleImageFile(file).then((resp) => { - if (!resp) return; - const [img, dataUrl] = resp; - const { schema } = view.state; - const node = schema.nodes.image.create({ - src: dataUrl, - }); - const tr = view.state.tr.insert(0, node); - view.dispatch(tr); - }); - } - } - }, - }, - }, - }); - return [plugin]; - }, - }).configure({ - HTMLAttributes: { - class: "object-contain max-h-[210px] max-w-full mx-1", - }, - }), - Placeholder.configure({ - placeholder: getPlaceholderText( - props.placeholder, - historyLengthRef.current, - ), - }), - Paragraph.extend({ - addKeyboardShortcuts() { - return { - Enter: () => { - if (inDropdownRef.current) { - return false; - } - - onEnterRef.current({ - useCodebase: false, - noContext: !useActiveFile, - }); - return true; - }, - - "Mod-Enter": () => { - onEnterRef.current({ - useCodebase: true, - noContext: !useActiveFile, - }); - return true; - }, - "Alt-Enter": () => { - posthog.capture("gui_use_active_file_enter"); - - onEnterRef.current({ - useCodebase: false, - noContext: !!useActiveFile, - }); - - return true; - }, - "Mod-Backspace": () => { - // If you press cmd+backspace wanting to cancel, - // but are inside of a text box, it shouldn't - // delete the text - if (isStreamingRef.current) { - return true; - } - return false; - }, - "Shift-Enter": () => - this.editor.commands.first(({ commands }) => [ - () => commands.newlineInCode(), - () => commands.createParagraphNear(), - () => commands.liftEmptyBlock(), - () => commands.splitBlock(), - ]), - - ArrowUp: () => { - if (this.editor.state.selection.anchor > 1) { - return false; - } - - const previousInput = prevRef.current( - this.editor.state.toJSON().doc, - ); - if (previousInput) { - this.editor.commands.setContent(previousInput); - setTimeout(() => { - this.editor.commands.blur(); - this.editor.commands.focus("start"); - }, 0); - return true; - } - return false; - }, - Escape: () => { - if (inDropdownRef.current || !isInEditModeRef.current) { - ideMessenger.post("focusEditor", undefined); - return true; - } - (async () => { - await dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); - dispatch(exitEditMode()); - })(); - - return true; - }, - ArrowDown: () => { - if ( - this.editor.state.selection.anchor < - this.editor.state.doc.content.size - 1 - ) { - return false; - } - const nextInput = nextRef.current(); - if (nextInput) { - this.editor.commands.setContent(nextInput); - setTimeout(() => { - this.editor.commands.blur(); - this.editor.commands.focus("end"); - }, 0); - return true; - } - return false; - }, - }; - }, - }).configure({ - HTMLAttributes: { - class: "my-1", - }, - }), - Text, - Mention.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getContextProviderDropdownOptions( - availableContextProvidersRef, - getSubmenuContextItemsRef, - enterSubmenu, - onClose, - onOpen, - inSubmenuRef, - ideMessenger, - ), - renderHTML: (props) => { - return `@${props.node.attrs.label || props.node.attrs.id}`; - }, - }), - - AddCodeToEdit.configure({ - HTMLAttributes: { - class: "add-code-to-edit", - }, - suggestion: { - ...getContextProviderDropdownOptions( - availableContextProvidersRef, - getSubmenuContextItemsRef, - enterSubmenu, - onClose, - onOpen, - inSubmenuRef, - ideMessenger, - ), - allow: () => isInEditModeRef.current, - command: async ({ editor, range, props }) => { - editor.chain().focus().insertContentAt(range, "").run(); - const filepath = props.id; - const contents = await ideMessenger.ide.readFile(filepath); - dispatch( - addCodeToEdit({ - filepath, - contents, - }), - ); - }, - items: async ({ query }) => { - // Only display files in the dropdown - const results = getSubmenuContextItemsRef.current("file", query); - return results.map((result) => ({ - ...result, - label: result.title, - type: "file", - query: result.id, - icon: result.icon, - })); - }, - }, - }), - props.availableSlashCommands.length - ? SlashCommand.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getSlashCommandDropdownOptions( - availableSlashCommandsRef, - onClose, - onOpen, - ideMessenger, - ), - renderText: (props) => { - return props.node.attrs.label; - }, - }) - : MockExtension, - CodeBlockExtension, - ], - editorProps: { - attributes: { - class: "outline-none -mt-1 overflow-hidden", - style: `font-size: ${getFontSize()}px;`, - }, - }, - content: props.editorState, - editable: !isStreaming || props.isMainInput, + const { editor, onEnterRef } = createEditorConfig({ + props, + ideMessenger, + dispatch, }); const [shouldHideToolbar, setShouldHideToolbar] = useState(false); @@ -554,34 +77,18 @@ function TipTapEditor(props: TipTapEditorProps) { setShouldHideToolbar(value); }, 200); - function getPlaceholderText( - placeholder: TipTapEditorProps["placeholder"], - historyLength: number, - ) { - if (placeholder) { - return placeholder; - } - - return historyLength === 0 - ? "Ask anything, '@' to add context" - : "Ask a follow-up"; - } - useEffect(() => { if (!editor) { return; } - const placeholder = getPlaceholderText( - props.placeholder, - historyLengthRef.current, - ); + const placeholder = getPlaceholderText(props.placeholder, historyLength); editor.extensionManager.extensions.filter( (extension) => extension.name === "placeholder", )[0].options["placeholder"] = placeholder; editor.view.dispatch(editor.state.tr); - }, [editor, props.placeholder, historyLengthRef.current]); + }, [editor, props.placeholder, historyLength]); useEffect(() => { if (props.isMainInput) { @@ -644,31 +151,6 @@ function TipTapEditor(props: TipTapEditorProps) { setActiveKey(null); }; - const onEnterRef = useUpdatingRef( - (modifiers: InputModifiers) => { - if (!editor) { - return; - } - if (isStreaming || isEditModeAndNoCodeToEdit) { - return; - } - - const json = editor.getJSON(); - - // Don't do anything if input box is empty - if (!json.content?.some((c) => c.content)) { - return; - } - - if (props.isMainInput) { - addRef.current(json); - } - - props.onEnter(json, modifiers, editor); - }, - [props.onEnter, editor, props.isMainInput], - ); - useEffect(() => { if (props.isMainInput) { /** @@ -885,28 +367,6 @@ function TipTapEditor(props: TipTapEditorProps) { const [showDragOverMsg, setShowDragOverMsg] = useState(false); - useEffect(() => { - const overListener = (event: DragEvent) => { - if (event.shiftKey) return; - setShowDragOverMsg(true); - }; - window.addEventListener("dragover", overListener); - - const leaveListener = (event: DragEvent) => { - if (event.shiftKey) { - setShowDragOverMsg(false); - } else { - setTimeout(() => setShowDragOverMsg(false), 2000); - } - }; - window.addEventListener("dragleave", leaveListener); - - return () => { - window.removeEventListener("dragover", overListener); - window.removeEventListener("dragleave", leaveListener); - }; - }, []); - const [activeKey, setActiveKey] = useState(null); const insertCharacterWithWhitespace = useCallback( @@ -964,7 +424,7 @@ function TipTapEditor(props: TipTapEditorProps) { } setShowDragOverMsg(false); let file = event.dataTransfer.files[0]; - handleImageFile(file).then((result) => { + handleImageFile(ideMessenger, file).then((result) => { if (!editor) { return; } @@ -997,7 +457,7 @@ function TipTapEditor(props: TipTapEditorProps) { onAddSlashCommand={() => insertCharacterWithWhitespace("/")} onEnter={onEnterRef.current} onImageFileSelected={(file) => { - handleImageFile(file).then((result) => { + handleImageFile(ideMessenger, file).then((result) => { if (!editor) { return; } @@ -1023,10 +483,7 @@ function TipTapEditor(props: TipTapEditorProps) { defaultModel?.title, defaultModel?.capabilities, ) && ( - <> - - Hold ⇧ to drop image - + )}
diff --git a/gui/src/components/mainInput/tiptap/editorConfig.ts b/gui/src/components/mainInput/tiptap/editorConfig.ts new file mode 100644 index 000000000..dfc39089d --- /dev/null +++ b/gui/src/components/mainInput/tiptap/editorConfig.ts @@ -0,0 +1,409 @@ +import { Editor } from "@tiptap/core"; +import Document from "@tiptap/extension-document"; +import History from "@tiptap/extension-history"; +import Image from "@tiptap/extension-image"; +import Paragraph from "@tiptap/extension-paragraph"; +import Placeholder from "@tiptap/extension-placeholder"; +import Text from "@tiptap/extension-text"; +import { Plugin } from "@tiptap/pm/state"; +import { useEditor } from "@tiptap/react"; +import { InputModifiers } from "core"; +import { modelSupportsImages } from "core/llm/autodetect"; +import { usePostHog } from "posthog-js/react"; +import { useRef } from "react"; +import { IIdeMessenger } from "../../../context/IdeMessenger"; +import { useSubmenuContextProviders } from "../../../context/SubmenuContextProviders"; +import { useInputHistory } from "../../../hooks/useInputHistory"; +import useUpdatingRef from "../../../hooks/useUpdatingRef"; +import { useAppSelector } from "../../../redux/hooks"; +import { selectUseActiveFile } from "../../../redux/selectors"; +import { selectDefaultModel } from "../../../redux/slices/configSlice"; +import { + addCodeToEdit, + selectHasCodeToEdit, + selectIsInEditMode, +} from "../../../redux/slices/sessionSlice"; +import { AppDispatch } from "../../../redux/store"; +import { exitEditMode } from "../../../redux/thunks"; +import { loadLastSession } from "../../../redux/thunks/session"; +import { getFontSize } from "../../../util"; +import { AddCodeToEdit } from "./extensions/AddCodeToEditExtension"; +import { CodeBlockExtension } from "./extensions/CodeBlockExtension"; +import { SlashCommand } from "./extensions/CommandsExtension"; +import { MockExtension } from "./extensions/FillerExtension"; +import { Mention } from "./extensions/MentionExtension"; +import { + getContextProviderDropdownOptions, + getSlashCommandDropdownOptions, +} from "./getSuggestion"; +import { handleImageFile } from "./imageUtils"; +import { TipTapEditorProps } from "./TipTapEditor"; + +export function getPlaceholderText( + placeholder: TipTapEditorProps["placeholder"], + historyLength: number, +) { + if (placeholder) { + return placeholder; + } + + return historyLength === 0 + ? "Ask anything, '@' to add context" + : "Ask a follow-up"; +} + +/** + * This function is called only once, so we need to use refs to pass in the latest values + */ +export function createEditorConfig(options: { + props: TipTapEditorProps; + ideMessenger: IIdeMessenger; + dispatch: AppDispatch; +}) { + const { props, ideMessenger, dispatch } = options; + + const posthog = usePostHog(); + + // #region Selectors + const { getSubmenuContextItems } = useSubmenuContextProviders(); + const defaultModel = useAppSelector(selectDefaultModel); + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const useActiveFile = useAppSelector(selectUseActiveFile); + const historyLength = useAppSelector((store) => store.session.history.length); + const isInEditMode = useAppSelector(selectIsInEditMode); + const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); + const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; + // #endregion + + // #region Refs + const inSubmenuRef = useRef(undefined); + const inDropdownRef = useRef(false); + const defaultModelRef = useUpdatingRef(defaultModel); + const isStreamingRef = useUpdatingRef(isStreaming); + const isInEditModeRef = useUpdatingRef(isInEditMode); + const getSubmenuContextItemsRef = useUpdatingRef(getSubmenuContextItems); + const availableContextProvidersRef = useUpdatingRef( + props.availableContextProviders, + ); + const historyLengthRef = useUpdatingRef(historyLength); + const availableSlashCommandsRef = useUpdatingRef( + props.availableSlashCommands, + ); + const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); + + // #endregion + + const enterSubmenu = async (editor: Editor, providerId: string) => { + const contents = editor.getText(); + const indexOfAt = contents.lastIndexOf("@"); + if (indexOfAt === -1) { + return; + } + + // Find the position of the last @ character + // We do this because editor.getText() isn't a correct representation including node views + let startPos = editor.state.selection.anchor; + while ( + startPos > 0 && + editor.state.doc.textBetween(startPos, startPos + 1) !== "@" + ) { + startPos--; + } + startPos++; + + editor.commands.deleteRange({ + from: startPos, + to: editor.state.selection.anchor, + }); + inSubmenuRef.current = providerId; + + // to trigger refresh of suggestions + editor.commands.insertContent(":"); + editor.commands.deleteRange({ + from: editor.state.selection.anchor - 1, + to: editor.state.selection.anchor, + }); + }; + + const onClose = () => { + inSubmenuRef.current = undefined; + inDropdownRef.current = false; + }; + + const onOpen = () => { + inDropdownRef.current = true; + }; + + const editor: Editor | null = useEditor({ + extensions: [ + Document, + History, + Image.extend({ + addProseMirrorPlugins() { + const plugin = new Plugin({ + props: { + handleDOMEvents: { + paste(view, event) { + const model = defaultModelRef.current; + if (!model) return; + const items = event.clipboardData?.items; + if (items) { + for (const item of items) { + const file = item.getAsFile(); + file && + modelSupportsImages( + model.provider, + model.model, + model.title, + model.capabilities, + ) && + handleImageFile(ideMessenger, file).then((resp) => { + if (!resp) return; + const [img, dataUrl] = resp; + const { schema } = view.state; + const node = schema.nodes.image.create({ + src: dataUrl, + }); + const tr = view.state.tr.insert(0, node); + view.dispatch(tr); + }); + } + } + }, + }, + }, + }); + return [plugin]; + }, + }).configure({ + HTMLAttributes: { + class: "object-contain max-h-[210px] max-w-full mx-1", + }, + }), + Placeholder.configure({ + placeholder: getPlaceholderText( + props.placeholder, + historyLengthRef.current, + ), + }), + Paragraph.extend({ + addKeyboardShortcuts() { + return { + Enter: () => { + if (inDropdownRef.current) { + return false; + } + + onEnterRef.current({ + useCodebase: false, + noContext: !useActiveFile, + }); + return true; + }, + + "Mod-Enter": () => { + onEnterRef.current({ + useCodebase: true, + noContext: !useActiveFile, + }); + return true; + }, + "Alt-Enter": () => { + posthog.capture("gui_use_active_file_enter"); + + onEnterRef.current({ + useCodebase: false, + noContext: !!useActiveFile, + }); + + return true; + }, + "Mod-Backspace": () => { + // If you press cmd+backspace wanting to cancel, + // but are inside of a text box, it shouldn't + // delete the text + if (isStreamingRef.current) { + return true; + } + return false; + }, + "Shift-Enter": () => + this.editor.commands.first(({ commands }) => [ + () => commands.newlineInCode(), + () => commands.createParagraphNear(), + () => commands.liftEmptyBlock(), + () => commands.splitBlock(), + ]), + + ArrowUp: () => { + if (this.editor.state.selection.anchor > 1) { + return false; + } + + const previousInput = prevRef.current( + this.editor.state.toJSON().doc, + ); + if (previousInput) { + this.editor.commands.setContent(previousInput); + setTimeout(() => { + this.editor.commands.blur(); + this.editor.commands.focus("start"); + }, 0); + return true; + } + return false; + }, + Escape: () => { + if (inDropdownRef.current || !isInEditModeRef.current) { + ideMessenger.post("focusEditor", undefined); + return true; + } + (async () => { + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), + ); + dispatch(exitEditMode()); + })(); + + return true; + }, + ArrowDown: () => { + if ( + this.editor.state.selection.anchor < + this.editor.state.doc.content.size - 1 + ) { + return false; + } + const nextInput = nextRef.current(); + if (nextInput) { + this.editor.commands.setContent(nextInput); + setTimeout(() => { + this.editor.commands.blur(); + this.editor.commands.focus("end"); + }, 0); + return true; + } + return false; + }, + }; + }, + }).configure({ + HTMLAttributes: { + class: "my-1", + }, + }), + Text, + Mention.configure({ + HTMLAttributes: { + class: "mention", + }, + suggestion: getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + renderHTML: (props) => { + return `@${props.node.attrs.label || props.node.attrs.id}`; + }, + }), + + AddCodeToEdit.configure({ + HTMLAttributes: { + class: "add-code-to-edit", + }, + suggestion: { + ...getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + allow: () => isInEditModeRef.current, + command: async ({ editor, range, props }) => { + editor.chain().focus().insertContentAt(range, "").run(); + const filepath = props.id; + const contents = await ideMessenger.ide.readFile(filepath); + dispatch( + addCodeToEdit({ + filepath, + contents, + }), + ); + }, + items: async ({ query }) => { + // Only display files in the dropdown + const results = getSubmenuContextItemsRef.current("file", query); + return results.map((result) => ({ + ...result, + label: result.title, + type: "file", + query: result.id, + icon: result.icon, + })); + }, + }, + }), + props.availableSlashCommands.length + ? SlashCommand.configure({ + HTMLAttributes: { + class: "mention", + }, + suggestion: getSlashCommandDropdownOptions( + availableSlashCommandsRef, + onClose, + onOpen, + ideMessenger, + ), + renderText: (props) => { + return props.node.attrs.label; + }, + }) + : MockExtension, + CodeBlockExtension, + ], + editorProps: { + attributes: { + class: "outline-none -mt-1 overflow-hidden", + style: `font-size: ${getFontSize()}px;`, + }, + }, + content: props.editorState, + editable: !isStreaming || props.isMainInput, + }); + + const onEnterRef = useUpdatingRef( + (modifiers: InputModifiers) => { + if (!editor) { + return; + } + if (isStreaming || isEditModeAndNoCodeToEdit) { + return; + } + + const json = editor.getJSON(); + + // Don't do anything if input box is empty + if (!json.content?.some((c) => c.content)) { + return; + } + + if (props.isMainInput) { + addRef.current(json); + } + + props.onEnter(json, modifiers, editor); + }, + [props.onEnter, editor, props.isMainInput], + ); + + return { editor, onEnterRef }; +} diff --git a/gui/src/components/mainInput/tiptap/imageUtils.ts b/gui/src/components/mainInput/tiptap/imageUtils.ts new file mode 100644 index 000000000..0803e5ab8 --- /dev/null +++ b/gui/src/components/mainInput/tiptap/imageUtils.ts @@ -0,0 +1,73 @@ +import { IIdeMessenger } from "../../../context/IdeMessenger"; + +const IMAGE_RESOLUTION = 1024; + +export function getDataUrlForFile( + file: File, + img: HTMLImageElement, +): string | undefined { + const targetWidth = IMAGE_RESOLUTION; + const targetHeight = IMAGE_RESOLUTION; + const scaleFactor = Math.min( + targetWidth / img.width, + targetHeight / img.height, + ); + + const canvas = document.createElement("canvas"); + canvas.width = img.width * scaleFactor; + canvas.height = img.height * scaleFactor; + + const ctx = canvas.getContext("2d"); + if (!ctx) { + console.error("Error getting image data url: 2d context not found"); + return; + } + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + + const downsizedDataUrl = canvas.toDataURL("image/jpeg", 0.7); + return downsizedDataUrl; +} + +export async function handleImageFile( + ideMessenger: IIdeMessenger, + file: File, +): Promise<[HTMLImageElement, string] | undefined> { + let filesize = file.size / 1024 / 1024; // filesize in MB + // check image type and size + if ( + [ + "image/jpeg", + "image/jpg", + "image/png", + "image/gif", + "image/svg", + "image/webp", + ].includes(file.type) && + filesize < 10 + ) { + // check dimensions + let _URL = window.URL || window.webkitURL; + let img = new window.Image(); + img.src = _URL.createObjectURL(file); + + return await new Promise((resolve) => { + img.onload = function () { + const dataUrl = getDataUrlForFile(file, img); + if (!dataUrl) { + return; + } + + let image = new window.Image(); + image.src = dataUrl; + image.onload = function () { + resolve([image, dataUrl]); + }; + }; + }); + } else { + ideMessenger.post("showToast", [ + "error", + "Images need to be in jpg or png format and less than 10MB in size.", + ]); + } +} From ccd19335fe6b5285c08df0603c268b7880b9c4bf Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 20 Mar 2025 23:38:15 -0700 Subject: [PATCH 009/709] organize keyHandlers --- .../mainInput/tiptap/TipTapEditor.tsx | 58 ++++--------------- .../mainInput/tiptap/keyHandlers.ts | 50 ++++++++++++++++ 2 files changed, 60 insertions(+), 48 deletions(-) create mode 100644 gui/src/components/mainInput/tiptap/keyHandlers.ts diff --git a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx index d1ae79f47..3cddb3710 100644 --- a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx +++ b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx @@ -2,14 +2,7 @@ import { Editor, EditorContent, JSONContent } from "@tiptap/react"; import { ContextProviderDescription, InputModifiers } from "core"; import { rifWithContentsToContextItem } from "core/commands/util"; import { modelSupportsImages } from "core/llm/autodetect"; -import { debounce } from "lodash"; -import { - KeyboardEvent, - useCallback, - useContext, - useEffect, - useState, -} from "react"; +import { useCallback, useContext, useEffect, useState } from "react"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import useIsOSREnabled from "../../../hooks/useIsOSREnabled"; import useUpdatingRef from "../../../hooks/useUpdatingRef"; @@ -23,16 +16,12 @@ import { setNewestCodeblocksForInput, } from "../../../redux/slices/sessionSlice"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; -import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../util"; import InputToolbar, { ToolbarOptions } from "../InputToolbar"; import { ComboBoxItem } from "../types"; -import { - handleJetBrainsOSRMetaKeyIssues, - handleVSCMetaKeyIssues, -} from "../util/handleMetaKeyIssues"; import { DragOverlay } from "./DragOverlay"; import { createEditorConfig, getPlaceholderText } from "./editorConfig"; import { handleImageFile } from "./imageUtils"; +import { useEditorEventHandlers } from "./keyHandlers"; import { InputBoxDiv } from "./StyledComponents"; import "./TipTapEditor.css"; @@ -73,9 +62,6 @@ function TipTapEditor(props: TipTapEditorProps) { }); const [shouldHideToolbar, setShouldHideToolbar] = useState(false); - const debouncedShouldHideToolbar = debounce((value) => { - setShouldHideToolbar(value); - }, 200); useEffect(() => { if (!editor) { @@ -119,38 +105,6 @@ function TipTapEditor(props: TipTapEditorProps) { const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]); - /** - * This handles various issues with meta key actions - * - In JetBrains, when using OSR in JCEF, there is a bug where using the meta key to - * highlight code using arrow keys is not working - * - In VS Code, while working with .ipynb files there is a problem where copy/paste/cut will affect - * the actual notebook cells, even when performing them in our GUI - * - * Currently keydown events for a number of keys are not registering if the - * meta/shift key is pressed, for example "x", "c", "v", "z", etc. - * Until this is resolved we can't turn on OSR for non-Mac users due to issues - * with those key actions. - */ - const handleKeyDown = async (e: KeyboardEvent) => { - if (!editor) { - return; - } - - setActiveKey(e.key); - - if (!editorFocusedRef?.current || !isMetaEquivalentKeyPressed(e)) return; - - if (isOSREnabled) { - handleJetBrainsOSRMetaKeyIssues(e, editor); - } else if (!isJetBrains()) { - await handleVSCMetaKeyIssues(e, editor); - } - }; - - const handleKeyUp = () => { - setActiveKey(null); - }; - useEffect(() => { if (props.isMainInput) { /** @@ -386,6 +340,14 @@ function TipTapEditor(props: TipTapEditorProps) { [editor], ); + const { handleKeyUp, handleKeyDown } = useEditorEventHandlers({ + editor, + isOSREnabled: isOSREnabled, + editorFocusedRef, + isInEditMode, + setActiveKey, + }); + return ( ; + isInEditMode: boolean; + setActiveKey: (key: string | null) => void; +}) { + const { editor, isOSREnabled, editorFocusedRef, isInEditMode, setActiveKey } = + options; + + /** + * This handles various issues with meta key actions + * - In JetBrains, when using OSR in JCEF, there is a bug where using the meta key to + * highlight code using arrow keys is not working + * - In VS Code, while working with .ipynb files there is a problem where copy/paste/cut will affect + * the actual notebook cells, even when performing them in our GUI + * + * Currently keydown events for a number of keys are not registering if the + * meta/shift key is pressed, for example "x", "c", "v", "z", etc. + * Until this is resolved we can't turn on OSR for non-Mac users due to issues + * with those key actions. + */ + const handleKeyDown = async (e: KeyboardEvent) => { + if (!editor) { + return; + } + + setActiveKey(e.key); + + if (!editorFocusedRef?.current || !isMetaEquivalentKeyPressed(e)) return; + + if (isOSREnabled) { + handleJetBrainsOSRMetaKeyIssues(e, editor); + } else if (!isJetBrains()) { + await handleVSCMetaKeyIssues(e, editor); + } + }; + + const handleKeyUp = () => setActiveKey(null); + + return { handleKeyDown, handleKeyUp }; +} From d72005b9faa1ed6489fab5a046170267026020e5 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 20 Mar 2025 23:44:48 -0700 Subject: [PATCH 010/709] refactor out webview listeners --- .../mainInput/tiptap/TipTapEditor.tsx | 192 +--------------- .../mainInput/tiptap/useWebviewListeners.ts | 211 ++++++++++++++++++ 2 files changed, 219 insertions(+), 184 deletions(-) create mode 100644 gui/src/components/mainInput/tiptap/useWebviewListeners.ts diff --git a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx index 3cddb3710..72e5ab749 100644 --- a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx +++ b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx @@ -1,21 +1,16 @@ import { Editor, EditorContent, JSONContent } from "@tiptap/react"; import { ContextProviderDescription, InputModifiers } from "core"; -import { rifWithContentsToContextItem } from "core/commands/util"; import { modelSupportsImages } from "core/llm/autodetect"; import { useCallback, useContext, useEffect, useState } from "react"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import useIsOSREnabled from "../../../hooks/useIsOSREnabled"; import useUpdatingRef from "../../../hooks/useUpdatingRef"; -import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { selectDefaultModel } from "../../../redux/slices/configSlice"; import { - clearCodeToEdit, selectIsInEditMode, setMainEditorContentTrigger, - setNewestCodeblocksForInput, } from "../../../redux/slices/sessionSlice"; -import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; import InputToolbar, { ToolbarOptions } from "../InputToolbar"; import { ComboBoxItem } from "../types"; import { DragOverlay } from "./DragOverlay"; @@ -24,6 +19,7 @@ import { handleImageFile } from "./imageUtils"; import { useEditorEventHandlers } from "./keyHandlers"; import { InputBoxDiv } from "./StyledComponents"; import "./TipTapEditor.css"; +import { useWebviewListeners } from "./useWebviewListeners"; export interface TipTapEditorProps { availableContextProviders: ContextProviderDescription[]; @@ -138,187 +134,15 @@ function TipTapEditor(props: TipTapEditorProps) { }, [editor, props.isMainInput, mainInputContentTrigger]); // IDE event listeners - useWebviewListener( - "userInput", - async (data) => { - if (!props.isMainInput) { - return; - } - editor?.commands.insertContent(data.input); - onEnterRef.current({ useCodebase: false, noContext: true }); - }, - [editor, onEnterRef.current, props.isMainInput], - ); - - useWebviewListener("jetbrains/editorInsetRefresh", async () => { - editor?.chain().clearContent().focus().run(); + useWebviewListeners({ + editor, + onEnterRef, + dispatch, + historyLength, + props, + editorFocusedRef, }); - useWebviewListener( - "focusContinueInput", - async (data) => { - if (!props.isMainInput) { - return; - } - - dispatch(clearCodeToEdit()); - - if (historyLength > 0) { - await dispatch( - saveCurrentSession({ - openNewSession: false, - generateTitle: true, - }), - ); - } - setTimeout(() => { - editor?.commands.blur(); - editor?.commands.focus("end"); - }, 20); - }, - [historyLength, editor, props.isMainInput], - ); - - useWebviewListener( - "focusContinueInputWithoutClear", - async () => { - if (!props.isMainInput) { - return; - } - setTimeout(() => { - editor?.commands.focus("end"); - }, 20); - }, - [editor, props.isMainInput], - ); - - useWebviewListener( - "focusContinueInputWithNewSession", - async () => { - if (!props.isMainInput) { - return; - } - await dispatch( - saveCurrentSession({ - openNewSession: true, - generateTitle: true, - }), - ); - setTimeout(() => { - editor?.commands.focus("end"); - }, 20); - }, - [editor, props.isMainInput], - ); - - useWebviewListener( - "highlightedCode", - async (data) => { - if (!props.isMainInput || !editor) { - return; - } - - const contextItem = rifWithContentsToContextItem( - data.rangeInFileWithContents, - ); - - let index = 0; - for (const el of editor.getJSON()?.content ?? []) { - if (el.attrs?.item?.name === contextItem.name) { - return; // Prevent exact duplicate code blocks - } - if (el.type === "codeBlock") { - index += 2; - } else { - break; - } - } - editor - .chain() - .insertContentAt(index, { - type: "codeBlock", - attrs: { - item: contextItem, - inputId: props.inputId, - }, - }) - .run(); - dispatch( - setNewestCodeblocksForInput({ - inputId: props.inputId, - contextItemId: contextItem.id.itemId, - }), - ); - if (data.prompt) { - editor.commands.focus("end"); - editor.commands.insertContent(data.prompt); - } - - if (data.shouldRun) { - onEnterRef.current({ useCodebase: false, noContext: true }); - } - - setTimeout(() => { - editor.commands.blur(); - editor.commands.focus("end"); - }, 20); - }, - [editor, props.isMainInput, historyLength, onEnterRef.current], - ); - - useWebviewListener( - "focusEdit", - async () => { - if (!props.isMainInput) { - return; - } - - setTimeout(() => { - editor?.commands.focus("end"); - }, 20); - }, - [editor, props.isMainInput], - ); - - useWebviewListener( - "focusEditWithoutClear", - async () => { - if (!props.isMainInput) { - return; - } - - setTimeout(() => { - editor?.commands.focus("end"); - }, 2000); - }, - [editor, props.isMainInput], - ); - - useWebviewListener( - "isContinueInputFocused", - async () => { - return props.isMainInput && !!editorFocusedRef.current; - }, - [editorFocusedRef, props.isMainInput], - !props.isMainInput, - ); - - useWebviewListener( - "focusContinueSessionId", - async (data) => { - if (!props.isMainInput || !data.sessionId) { - return; - } - await dispatch( - loadSession({ - sessionId: data.sessionId, - saveCurrentSession: true, - }), - ); - }, - [props.isMainInput], - ); - const [showDragOverMsg, setShowDragOverMsg] = useState(false); const [activeKey, setActiveKey] = useState(null); diff --git a/gui/src/components/mainInput/tiptap/useWebviewListeners.ts b/gui/src/components/mainInput/tiptap/useWebviewListeners.ts new file mode 100644 index 000000000..3a4694939 --- /dev/null +++ b/gui/src/components/mainInput/tiptap/useWebviewListeners.ts @@ -0,0 +1,211 @@ +import { Editor } from "@tiptap/core"; +import { InputModifiers } from "core"; +import { rifWithContentsToContextItem } from "core/commands/util"; +import { MutableRefObject } from "react"; +import { useWebviewListener } from "../../../hooks/useWebviewListener"; +import { + clearCodeToEdit, + setNewestCodeblocksForInput, +} from "../../../redux/slices/sessionSlice"; +import { AppDispatch } from "../../../redux/store"; +import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; +import { TipTapEditorProps } from "./TipTapEditor"; + +export function useWebviewListeners(options: { + editor: Editor | null; + onEnterRef: MutableRefObject<(modifiers: InputModifiers) => void>; + dispatch: AppDispatch; + historyLength: number; + props: TipTapEditorProps; + editorFocusedRef: MutableRefObject; +}) { + const { + editor, + onEnterRef, + dispatch, + historyLength, + props, + editorFocusedRef, + } = options; + + useWebviewListener( + "userInput", + async (data) => { + if (!props.isMainInput) { + return; + } + editor?.commands.insertContent(data.input); + onEnterRef.current({ useCodebase: false, noContext: true }); + }, + [editor, onEnterRef.current, props.isMainInput], + ); + + useWebviewListener("jetbrains/editorInsetRefresh", async () => { + editor?.chain().clearContent().focus().run(); + }); + + useWebviewListener( + "focusContinueInput", + async (data) => { + if (!props.isMainInput) { + return; + } + + dispatch(clearCodeToEdit()); + + if (historyLength > 0) { + await dispatch( + saveCurrentSession({ + openNewSession: false, + generateTitle: true, + }), + ); + } + setTimeout(() => { + editor?.commands.blur(); + editor?.commands.focus("end"); + }, 20); + }, + [historyLength, editor, props.isMainInput], + ); + + useWebviewListener( + "focusContinueInputWithoutClear", + async () => { + if (!props.isMainInput) { + return; + } + setTimeout(() => { + editor?.commands.focus("end"); + }, 20); + }, + [editor, props.isMainInput], + ); + + useWebviewListener( + "focusContinueInputWithNewSession", + async () => { + if (!props.isMainInput) { + return; + } + await dispatch( + saveCurrentSession({ + openNewSession: true, + generateTitle: true, + }), + ); + setTimeout(() => { + editor?.commands.focus("end"); + }, 20); + }, + [editor, props.isMainInput], + ); + + useWebviewListener( + "highlightedCode", + async (data) => { + if (!props.isMainInput || !editor) { + return; + } + + const contextItem = rifWithContentsToContextItem( + data.rangeInFileWithContents, + ); + + let index = 0; + for (const el of editor.getJSON()?.content ?? []) { + if (el.attrs?.item?.name === contextItem.name) { + return; // Prevent exact duplicate code blocks + } + if (el.type === "codeBlock") { + index += 2; + } else { + break; + } + } + editor + .chain() + .insertContentAt(index, { + type: "codeBlock", + attrs: { + item: contextItem, + inputId: props.inputId, + }, + }) + .run(); + dispatch( + setNewestCodeblocksForInput({ + inputId: props.inputId, + contextItemId: contextItem.id.itemId, + }), + ); + if (data.prompt) { + editor.commands.focus("end"); + editor.commands.insertContent(data.prompt); + } + + if (data.shouldRun) { + onEnterRef.current({ useCodebase: false, noContext: true }); + } + + setTimeout(() => { + editor.commands.blur(); + editor.commands.focus("end"); + }, 20); + }, + [editor, props.isMainInput, historyLength, onEnterRef.current], + ); + + useWebviewListener( + "focusEdit", + async () => { + if (!props.isMainInput) { + return; + } + + setTimeout(() => { + editor?.commands.focus("end"); + }, 20); + }, + [editor, props.isMainInput], + ); + + useWebviewListener( + "focusEditWithoutClear", + async () => { + if (!props.isMainInput) { + return; + } + + setTimeout(() => { + editor?.commands.focus("end"); + }, 2000); + }, + [editor, props.isMainInput], + ); + + useWebviewListener( + "isContinueInputFocused", + async () => { + return props.isMainInput && !!editorFocusedRef.current; + }, + [editorFocusedRef, props.isMainInput], + !props.isMainInput, + ); + + useWebviewListener( + "focusContinueSessionId", + async (data) => { + if (!props.isMainInput || !data.sessionId) { + return; + } + await dispatch( + loadSession({ + sessionId: data.sessionId, + saveCurrentSession: true, + }), + ); + }, + [props.isMainInput], + ); +} From 15b6ccf42b14079a320f5d189d9c3c163aeccad5 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 20 Mar 2025 23:57:58 -0700 Subject: [PATCH 011/709] add tooltip delay --- gui/src/components/gui/Tooltip.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/gui/Tooltip.tsx b/gui/src/components/gui/Tooltip.tsx index b1477ba73..e2c069df8 100644 --- a/gui/src/components/gui/Tooltip.tsx +++ b/gui/src/components/gui/Tooltip.tsx @@ -25,7 +25,7 @@ export function ToolTip(props: any) { return ( tooltipPortalDiv && ReactDOM.createPortal( - , + , tooltipPortalDiv, ) ); From a1d84298bb532725651796017494ae89b4448509 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 21 Mar 2025 09:45:52 -0700 Subject: [PATCH 012/709] lump v1 --- .../components/mainInput/ContinueInputBox.tsx | 8 ++- gui/src/components/mainInput/InputToolbar.tsx | 2 + .../mainInput/Lump/TopInputToolbar.tsx | 65 +++++++++++++++++++ gui/src/components/mainInput/Lump/index.tsx | 59 +++++++++++++++++ .../components/mainInput/Lump/sections.tsx | 36 ++++++++++ .../mainInput/tiptap/TipTapEditor.tsx | 5 ++ .../platform/AssistantSelect.tsx | 12 ++-- gui/src/pages/gui/Chat.tsx | 2 - 8 files changed, 180 insertions(+), 9 deletions(-) create mode 100644 gui/src/components/mainInput/Lump/TopInputToolbar.tsx create mode 100644 gui/src/components/mainInput/Lump/index.tsx create mode 100644 gui/src/components/mainInput/Lump/sections.tsx diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 940584636..aab30acf7 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,12 +1,13 @@ import { Editor, JSONContent } from "@tiptap/react"; import { ContextItemWithId, InputModifiers } from "core"; -import { useMemo } from "react"; +import { useMemo, useState } from "react"; import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; import { useAppSelector } from "../../redux/hooks"; import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; import ContextItemsPeek from "./belowMainInput/ContextItemsPeek"; import { ToolbarOptions } from "./InputToolbar"; +import { Lump } from "./Lump"; import TipTapEditor from "./tiptap/TipTapEditor"; interface ContinueInputBoxProps { @@ -112,9 +113,12 @@ function ContinueInputBox(props: ContinueInputBoxProps) { } : {}; + const [lumpOpen, setLumpOpen] = useState(true); + return (
+ diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index d948dc288..2642fc089 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -83,6 +83,8 @@ interface InputToolbarProps { toolbarOptions?: ToolbarOptions; disabled?: boolean; isMainInput?: boolean; + lumpOpen: boolean; + setLumpOpen: (open: boolean) => void; } function InputToolbar(props: InputToolbarProps) { diff --git a/gui/src/components/mainInput/Lump/TopInputToolbar.tsx b/gui/src/components/mainInput/Lump/TopInputToolbar.tsx new file mode 100644 index 000000000..a5fdebc2b --- /dev/null +++ b/gui/src/components/mainInput/Lump/TopInputToolbar.tsx @@ -0,0 +1,65 @@ +import { + BookOpenIcon, + ChatBubbleLeftIcon, + CubeIcon, + FolderIcon, + PencilIcon, +} from "@heroicons/react/24/outline"; +import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; +import HoverItem from "../InputToolbar/HoverItem"; + +function TopToolbarIcon(props: { + tooltip: string; + icon: React.ComponentType; + itemCount?: number; + onClick: () => void; +}) { + return ( + +
+ +
+
+ ); +} + +interface TopInputProps { + selectedSection: string | null; + setSelectedSection: (value: string | null) => void; +} +export function TopInputToolbar(props: TopInputProps) { + return ( +
+
+
+ props.setSelectedSection("models")} + /> + props.setSelectedSection("rules")} + /> + props.setSelectedSection("docs")} + /> + props.setSelectedSection("prompts")} + /> + props.setSelectedSection("context")} + /> +
+ +
+
+ ); +} diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx new file mode 100644 index 000000000..be2fd5427 --- /dev/null +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -0,0 +1,59 @@ +import { useState } from "react"; +import styled from "styled-components"; +import { + defaultBorderRadius, + vscCommandCenterInactiveBorder, + vscInputBackground, +} from "../.."; +import { TopInputToolbar } from "./TopInputToolbar"; +import { SelectedSection } from "./sections"; + +interface LumpProps { + open: boolean; + setOpen: (open: boolean) => void; +} + +const LumpDiv = styled.div<{ open: boolean }>` + background-color: ${vscInputBackground}; + margin-left: 4px; + margin-right: 4px; + height: ${(props) => (props.open ? "24px" : "12px")}; + border-radius: ${defaultBorderRadius} ${defaultBorderRadius} 0 0; + border-top: 1px solid ${vscCommandCenterInactiveBorder}; + border-left: 1px solid ${vscCommandCenterInactiveBorder}; + border-right: 1px solid ${vscCommandCenterInactiveBorder}; +`; + +export function Lump(props: LumpProps) { + const { open, setOpen } = props; + const [selectedSection, setSelectedSection] = useState(null); + + if (!open) { + return null; + } + + return ( +
+ +
+ {open && ( + <> + +
setOpen(false)} + className="cursor-pointer select-none px-2" + > + × +
+ + )} +
+
+ + +
+ ); +} diff --git a/gui/src/components/mainInput/Lump/sections.tsx b/gui/src/components/mainInput/Lump/sections.tsx new file mode 100644 index 000000000..023e9a21a --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections.tsx @@ -0,0 +1,36 @@ +function ModelsSection() { + return
Models content
; +} + +function RulesSection() { + return
Rules content
; +} + +function DocsSection() { + return
Docs content
; +} + +function PromptsSection() { + return
Prompts content
; +} + +function ContextSection() { + return
Context content
; +} + +export function SelectedSection(props: { selectedSection: string | null }) { + switch (props.selectedSection) { + case "models": + return ; + case "rules": + return ; + case "docs": + return ; + case "prompts": + return ; + case "context": + return ; + default: + return null; + } +} diff --git a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx index 72e5ab749..fbe5a53b1 100644 --- a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx +++ b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx @@ -32,6 +32,8 @@ export interface TipTapEditorProps { ) => void; editorState?: JSONContent; toolbarOptions?: ToolbarOptions; + lumpOpen: boolean; + setLumpOpen: (open: boolean) => void; placeholder?: string; historyKey: string; inputId: string; @@ -226,6 +228,7 @@ function TipTapEditor(props: TipTapEditorProps) { }} >
+ {/* */}
diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index be2fd5427..8ba6e35c8 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -17,13 +17,16 @@ const LumpDiv = styled.div<{ open: boolean }>` background-color: ${vscInputBackground}; margin-left: 4px; margin-right: 4px; - height: ${(props) => (props.open ? "24px" : "12px")}; border-radius: ${defaultBorderRadius} ${defaultBorderRadius} 0 0; border-top: 1px solid ${vscCommandCenterInactiveBorder}; border-left: 1px solid ${vscCommandCenterInactiveBorder}; border-right: 1px solid ${vscCommandCenterInactiveBorder}; `; +const TopBarContainer = styled.div` + height: 24px; +`; + export function Lump(props: LumpProps) { const { open, setOpen } = props; const [selectedSection, setSelectedSection] = useState(null); @@ -33,27 +36,22 @@ export function Lump(props: LumpProps) { } return ( -
- -
- {open && ( - <> - -
setOpen(false)} - className="cursor-pointer select-none px-2" - > - × -
- - )} -
-
- - -
+ +
+ + +
setOpen(false)} + className="cursor-pointer select-none px-2" + > + × +
+
+ +
+
); } diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 86e11eca2..a7f2a08ac 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -63,7 +63,7 @@ export default function AssistantSelect() { orgSlug: selectedOrganization?.slug, }); }} - className="text-lightgray hover:bg mb-1 mr-3 flex cursor-pointer items-center gap-1 whitespace-nowrap" + className="text-lightgray hover:bg mb-1 mr-3 flex cursor-pointer select-none items-center gap-1 whitespace-nowrap" style={{ fontSize: `${getFontSize() - 3}px` }} > Create your first assistant From db05eeacb78d449d4696555f10cda4365dad6aeb Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 21 Mar 2025 09:50:45 -0700 Subject: [PATCH 014/709] highlights --- .../mainInput/Lump/TopInputToolbar.tsx | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/gui/src/components/mainInput/Lump/TopInputToolbar.tsx b/gui/src/components/mainInput/Lump/TopInputToolbar.tsx index 212cf0920..b6a6633fc 100644 --- a/gui/src/components/mainInput/Lump/TopInputToolbar.tsx +++ b/gui/src/components/mainInput/Lump/TopInputToolbar.tsx @@ -8,16 +8,23 @@ import { import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; import HoverItem from "../InputToolbar/HoverItem"; -function TopToolbarIcon(props: { +interface TopToolbarIconProps { tooltip: string; icon: React.ComponentType; itemCount?: number; onClick: () => void; -}) { + isSelected?: boolean; +} + +function TopToolbarIcon(props: TopToolbarIconProps) { return (
- +
); @@ -27,6 +34,7 @@ interface TopInputProps { selectedSection: string | null; setSelectedSection: (value: string | null) => void; } + export function TopInputToolbar(props: TopInputProps) { return (
@@ -35,6 +43,7 @@ export function TopInputToolbar(props: TopInputProps) { props.setSelectedSection( props.selectedSection === "models" ? null : "models", @@ -44,6 +53,7 @@ export function TopInputToolbar(props: TopInputProps) { props.setSelectedSection( props.selectedSection === "rules" ? null : "rules", @@ -53,6 +63,7 @@ export function TopInputToolbar(props: TopInputProps) { props.setSelectedSection( props.selectedSection === "docs" ? null : "docs", @@ -62,6 +73,7 @@ export function TopInputToolbar(props: TopInputProps) { props.setSelectedSection( props.selectedSection === "prompts" ? null : "prompts", @@ -71,6 +83,7 @@ export function TopInputToolbar(props: TopInputProps) { props.setSelectedSection( props.selectedSection === "context" ? null : "context", From c3f9204b859fd2e7b2e7b5cf78739e914609963a Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 21 Mar 2025 09:59:32 -0700 Subject: [PATCH 015/709] styles --- gui/src/components/mainInput/Lump/index.tsx | 23 +++++-------------- .../platform/AssistantSelect.tsx | 4 ++-- 2 files changed, 8 insertions(+), 19 deletions(-) diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index 8ba6e35c8..70db97266 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -23,10 +23,6 @@ const LumpDiv = styled.div<{ open: boolean }>` border-right: 1px solid ${vscCommandCenterInactiveBorder}; `; -const TopBarContainer = styled.div` - height: 24px; -`; - export function Lump(props: LumpProps) { const { open, setOpen } = props; const [selectedSection, setSelectedSection] = useState(null); @@ -37,19 +33,12 @@ export function Lump(props: LumpProps) { return ( -
- - -
setOpen(false)} - className="cursor-pointer select-none px-2" - > - × -
-
+
+ +
diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index a7f2a08ac..5dafedff2 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -63,7 +63,7 @@ export default function AssistantSelect() { orgSlug: selectedOrganization?.slug, }); }} - className="text-lightgray hover:bg mb-1 mr-3 flex cursor-pointer select-none items-center gap-1 whitespace-nowrap" + className="hover:bg flex cursor-pointer select-none items-center gap-1 whitespace-nowrap text-gray-400" style={{ fontSize: `${getFontSize() - 3}px` }} > Create your first assistant @@ -77,7 +77,7 @@ export default function AssistantSelect() { From 46f46652ca503e86426858260a48b3b41bc2027e Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 21 Mar 2025 10:03:28 -0700 Subject: [PATCH 016/709] style --- gui/src/components/mainInput/ContinueInputBox.tsx | 2 +- gui/src/components/mainInput/Lump/index.tsx | 2 +- .../modelSelection/platform/AssistantSelect.tsx | 15 ++++++++++----- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index aab30acf7..2b91b707b 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -118,7 +118,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) { return (
- + {props.isMainInput && } -
+
-
+
- {props.selectedProfile.title} -
); } @@ -66,7 +71,7 @@ export default function AssistantSelect() { className="hover:bg flex cursor-pointer select-none items-center gap-1 whitespace-nowrap text-gray-400" style={{ fontSize: `${getFontSize() - 3}px` }} > - Create your first assistant + Create your first assistant
); } @@ -77,7 +82,7 @@ export default function AssistantSelect() { From 25f82646181054eedfa44fd4c925c80222e0247f Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 21 Mar 2025 10:06:01 -0700 Subject: [PATCH 017/709] refactor sections --- gui/src/components/mainInput/Lump/index.tsx | 2 +- .../components/mainInput/Lump/sections.tsx | 36 ------------------- .../Lump/sections/ContextSection.tsx | 5 +++ .../mainInput/Lump/sections/DocsSection.tsx | 5 +++ .../mainInput/Lump/sections/ModelsSection.tsx | 5 +++ .../Lump/sections/PromptsSection.tsx | 5 +++ .../mainInput/Lump/sections/RulesSection.tsx | 5 +++ .../Lump/sections/SelectedSection.tsx | 27 ++++++++++++++ 8 files changed, 53 insertions(+), 37 deletions(-) delete mode 100644 gui/src/components/mainInput/Lump/sections.tsx create mode 100644 gui/src/components/mainInput/Lump/sections/ContextSection.tsx create mode 100644 gui/src/components/mainInput/Lump/sections/DocsSection.tsx create mode 100644 gui/src/components/mainInput/Lump/sections/ModelsSection.tsx create mode 100644 gui/src/components/mainInput/Lump/sections/PromptsSection.tsx create mode 100644 gui/src/components/mainInput/Lump/sections/RulesSection.tsx create mode 100644 gui/src/components/mainInput/Lump/sections/SelectedSection.tsx diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index e38a32285..3c50eef32 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -6,7 +6,7 @@ import { vscInputBackground, } from "../.."; import { TopInputToolbar } from "./TopInputToolbar"; -import { SelectedSection } from "./sections"; +import { SelectedSection } from "./sections/SelectedSection"; interface LumpProps { open: boolean; diff --git a/gui/src/components/mainInput/Lump/sections.tsx b/gui/src/components/mainInput/Lump/sections.tsx deleted file mode 100644 index 023e9a21a..000000000 --- a/gui/src/components/mainInput/Lump/sections.tsx +++ /dev/null @@ -1,36 +0,0 @@ -function ModelsSection() { - return
Models content
; -} - -function RulesSection() { - return
Rules content
; -} - -function DocsSection() { - return
Docs content
; -} - -function PromptsSection() { - return
Prompts content
; -} - -function ContextSection() { - return
Context content
; -} - -export function SelectedSection(props: { selectedSection: string | null }) { - switch (props.selectedSection) { - case "models": - return ; - case "rules": - return ; - case "docs": - return ; - case "prompts": - return ; - case "context": - return ; - default: - return null; - } -} diff --git a/gui/src/components/mainInput/Lump/sections/ContextSection.tsx b/gui/src/components/mainInput/Lump/sections/ContextSection.tsx new file mode 100644 index 000000000..40faf0c33 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/ContextSection.tsx @@ -0,0 +1,5 @@ +import React from 'react'; + +export function ContextSection() { + return
Context content
; +} \ No newline at end of file diff --git a/gui/src/components/mainInput/Lump/sections/DocsSection.tsx b/gui/src/components/mainInput/Lump/sections/DocsSection.tsx new file mode 100644 index 000000000..86c8b5fc8 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/DocsSection.tsx @@ -0,0 +1,5 @@ +import React from 'react'; + +export function DocsSection() { + return
Docs content
; +} \ No newline at end of file diff --git a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx new file mode 100644 index 000000000..279b3709a --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx @@ -0,0 +1,5 @@ +import React from 'react'; + +export function ModelsSection() { + return
Models content
; +} \ No newline at end of file diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx new file mode 100644 index 000000000..e7114a8c4 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -0,0 +1,5 @@ +import React from 'react'; + +export function PromptsSection() { + return
Prompts content
; +} \ No newline at end of file diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx new file mode 100644 index 000000000..e329ca70c --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -0,0 +1,5 @@ +import React from 'react'; + +export function RulesSection() { + return
Rules content
; +} \ No newline at end of file diff --git a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx new file mode 100644 index 000000000..655c770fe --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx @@ -0,0 +1,27 @@ +import React from 'react'; +import { ModelsSection } from './ModelsSection'; +import { RulesSection } from './RulesSection'; +import { DocsSection } from './DocsSection'; +import { PromptsSection } from './PromptsSection'; +import { ContextSection } from './ContextSection'; + +interface SelectedSectionProps { + selectedSection: string | null; +} + +export function SelectedSection(props: SelectedSectionProps) { + switch (props.selectedSection) { + case "models": + return ; + case "rules": + return ; + case "docs": + return ; + case "prompts": + return ; + case "context": + return ; + default: + return null; + } +} \ No newline at end of file From 1aca061ec7c9609d675e42a9c9b72daf2210a597 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 21 Mar 2025 10:07:12 -0700 Subject: [PATCH 018/709] remove editorInset --- gui/editorInset/index.html | 13 --------- gui/editorInset/vite.config.ts | 19 ------------ gui/src/editorInset/EditorInset.tsx | 45 ----------------------------- gui/src/editorInset/main.tsx | 18 ------------ 4 files changed, 95 deletions(-) delete mode 100644 gui/editorInset/index.html delete mode 100644 gui/editorInset/vite.config.ts delete mode 100644 gui/src/editorInset/EditorInset.tsx delete mode 100644 gui/src/editorInset/main.tsx diff --git a/gui/editorInset/index.html b/gui/editorInset/index.html deleted file mode 100644 index 1e6607ff2..000000000 --- a/gui/editorInset/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - Continue - - -
- - - diff --git a/gui/editorInset/vite.config.ts b/gui/editorInset/vite.config.ts deleted file mode 100644 index fdc63bbdb..000000000 --- a/gui/editorInset/vite.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -import react from "@vitejs/plugin-react-swc"; -import tailwindcss from "tailwindcss"; -import { defineConfig } from "vite"; - -// https://vitejs.dev/config/ -export default defineConfig({ - plugins: [react(), tailwindcss()], - build: { - // Change the output .js filename to not include a hash - rollupOptions: { - // external: ["vscode-webview"], - output: { - entryFileNames: `assets/[name].js`, - chunkFileNames: `assets/[name].js`, - assetFileNames: `assets/[name].[ext]`, - }, - }, - }, -}); diff --git a/gui/src/editorInset/EditorInset.tsx b/gui/src/editorInset/EditorInset.tsx deleted file mode 100644 index 2f6d10f80..000000000 --- a/gui/src/editorInset/EditorInset.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { useRef } from "react"; -import styled from "styled-components"; -import { defaultBorderRadius } from "../components"; -import TipTapEditor from "../components/mainInput/tiptap/TipTapEditor"; -import useSetup from "../hooks/useSetup"; -import { useAppSelector } from "../redux/hooks"; -import { selectSlashCommandComboBoxInputs } from "../redux/selectors"; - -const EditorInsetDiv = styled.div` - max-width: 500px; - position: relative; - display: flex; - border-radius: ${defaultBorderRadius}; - // box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.4); -`; - -function EditorInset() { - const availableSlashCommands = useAppSelector( - selectSlashCommandComboBoxInputs, - ); - const availableContextProviders = useAppSelector( - (store) => store.config.config.contextProviders, - ); - - useSetup(); - - const elementRef = useRef(null); - - return ( - - { - console.log("Enter: ", e, modifiers); - }} - historyKey="chat" - inputId="editor-inset" - /> - - ); -} - -export default EditorInset; diff --git a/gui/src/editorInset/main.tsx b/gui/src/editorInset/main.tsx deleted file mode 100644 index d15005ee7..000000000 --- a/gui/src/editorInset/main.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import React from "react"; -import ReactDOM from "react-dom/client"; -import { Provider } from "react-redux"; -import "../index.css"; -import { store } from "../redux/store"; - -import CustomPostHogProvider from "../hooks/CustomPostHogProvider"; -import EditorInset from "./EditorInset"; - -ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( - - - - - - - , -); From bbff4f8497d203967e30ba2eebe9f8583cbf5941 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 21 Mar 2025 10:12:33 -0700 Subject: [PATCH 019/709] move model roles to lump --- .../mainInput/Lump/sections/ModelsSection.tsx | 111 +++++++++++++++++- gui/src/pages/config/index.tsx | 105 +---------------- 2 files changed, 110 insertions(+), 106 deletions(-) diff --git a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx index 279b3709a..249ba77bb 100644 --- a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx @@ -1,5 +1,110 @@ -import React from 'react'; +import { ModelRole } from "@continuedev/config-yaml"; +import { ModelDescription } from "core"; +import { useContext } from "react"; +import { useAuth } from "../../../../context/Auth"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import ModelRoleSelector from "../../../../pages/config/ModelRoleSelector"; +import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; +import { + selectDefaultModel, + setDefaultModel, + updateConfig, +} from "../../../../redux/slices/configSlice"; +import { isJetBrains } from "../../../../util"; export function ModelsSection() { - return
Models content
; -} \ No newline at end of file + const { selectedProfile } = useAuth(); + const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + const config = useAppSelector((state) => state.config.config); + const jetbrains = isJetBrains(); + const selectedChatModel = useAppSelector(selectDefaultModel); + + function handleRoleUpdate(role: ModelRole, model: ModelDescription | null) { + if (!selectedProfile) { + return; + } + // Optimistic update + dispatch( + updateConfig({ + ...config, + selectedModelByRole: { + ...config.selectedModelByRole, + [role]: model, + }, + }), + ); + ideMessenger.post("config/updateSelectedModel", { + profileId: selectedProfile.id, + role, + title: model?.title ?? null, + }); + } + + // TODO use handleRoleUpdate for chat + function handleChatModelSelection(model: ModelDescription | null) { + if (!model) { + return; + } + dispatch(setDefaultModel({ title: model.title })); + } + + return ( +
+ handleChatModelSelection(model)} + /> + handleRoleUpdate("autocomplete", model)} + /> + {/* Jetbrains has a model selector inline */} + {!jetbrains && ( + handleRoleUpdate("edit", model)} + /> + )} + handleRoleUpdate("apply", model)} + /> + handleRoleUpdate("embed", model)} + /> + handleRoleUpdate("rerank", model)} + /> +
+ ); +} diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index 14128ffda..f966af2c0 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -1,4 +1,3 @@ -import { ModelRole } from "@continuedev/config-yaml"; import { Listbox, Transition } from "@headlessui/react"; import { ArrowTopRightOnSquareIcon, @@ -7,7 +6,6 @@ import { PlusCircleIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { ModelDescription } from "core"; import { SharedConfigSchema, modifyAnyConfigWithSharedConfig, @@ -24,15 +22,10 @@ import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useNavigationListener } from "../../hooks/useNavigationListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { - selectDefaultModel, - setDefaultModel, - updateConfig, -} from "../../redux/slices/configSlice"; +import { updateConfig } from "../../redux/slices/configSlice"; import { selectProfileThunk } from "../../redux/thunks/profileAndOrg"; -import { getFontSize, isJetBrains } from "../../util"; +import { getFontSize } from "../../util"; import { AccountButton } from "./AccountButton"; -import ModelRoleSelector from "./ModelRoleSelector"; import { ScopeSelect } from "./ScopeSelect"; function ConfigPage() { @@ -76,7 +69,6 @@ function ConfigPage() { /////// User settings section ////// const config = useAppSelector((state) => state.config.config); - const selectedChatModel = useAppSelector(selectDefaultModel); function handleUpdate(sharedConfig: SharedConfigSchema) { // Optimistic update @@ -89,35 +81,6 @@ function ConfigPage() { ideMessenger.post("config/updateSharedConfig", sharedConfig); } - function handleRoleUpdate(role: ModelRole, model: ModelDescription | null) { - if (!selectedProfile) { - return; - } - // Optimistic update - dispatch( - updateConfig({ - ...config, - selectedModelByRole: { - ...config.selectedModelByRole, - [role]: model, - }, - }), - ); - ideMessenger.post("config/updateSelectedModel", { - profileId: selectedProfile.id, - role, - title: model?.title ?? null, - }); - } - - // TODO use handleRoleUpdate for chat - function handleChatModelSelection(model: ModelDescription | null) { - if (!model) { - return; - } - dispatch(setDefaultModel({ title: model.title })); - } - // TODO defaults are in multiple places, should be consolidated and probably not explicit here const showSessionTabs = config.ui?.showSessionTabs ?? false; const codeWrap = config.ui?.codeWrap ?? false; @@ -178,8 +141,6 @@ function ConfigPage() { setFormPromptPath(promptPath); }, [promptPath]); - const jetbrains = isJetBrains(); - return (
- {/* Model Roles as a separate section */} -
-
-

Model Roles

-
- handleChatModelSelection(model)} - /> - handleRoleUpdate("autocomplete", model)} - /> - {/* Jetbrains has a model selector inline */} - {!jetbrains && ( - handleRoleUpdate("edit", model)} - /> - )} - handleRoleUpdate("apply", model)} - /> - handleRoleUpdate("embed", model)} - /> - handleRoleUpdate("rerank", model)} - /> -
-
-
- {!controlServerBetaEnabled || hubEnabled ? (
From b52794245ea9fc94d12a3ae8a650a5b09d232095 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 21 Mar 2025 11:03:45 -0700 Subject: [PATCH 020/709] remove imports --- .../mainInput/Lump/sections/ContextSection.tsx | 4 +--- .../mainInput/Lump/sections/DocsSection.tsx | 4 +--- .../mainInput/Lump/sections/PromptsSection.tsx | 4 +--- .../mainInput/Lump/sections/RulesSection.tsx | 4 +--- .../mainInput/Lump/sections/SelectedSection.tsx | 13 ++++++------- 5 files changed, 10 insertions(+), 19 deletions(-) diff --git a/gui/src/components/mainInput/Lump/sections/ContextSection.tsx b/gui/src/components/mainInput/Lump/sections/ContextSection.tsx index 40faf0c33..7524fd08d 100644 --- a/gui/src/components/mainInput/Lump/sections/ContextSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/ContextSection.tsx @@ -1,5 +1,3 @@ -import React from 'react'; - export function ContextSection() { return
Context content
; -} \ No newline at end of file +} diff --git a/gui/src/components/mainInput/Lump/sections/DocsSection.tsx b/gui/src/components/mainInput/Lump/sections/DocsSection.tsx index 86c8b5fc8..9e68397c8 100644 --- a/gui/src/components/mainInput/Lump/sections/DocsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/DocsSection.tsx @@ -1,5 +1,3 @@ -import React from 'react'; - export function DocsSection() { return
Docs content
; -} \ No newline at end of file +} diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx index e7114a8c4..8e9212e9a 100644 --- a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -1,5 +1,3 @@ -import React from 'react'; - export function PromptsSection() { return
Prompts content
; -} \ No newline at end of file +} diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index e329ca70c..68067006b 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -1,5 +1,3 @@ -import React from 'react'; - export function RulesSection() { return
Rules content
; -} \ No newline at end of file +} diff --git a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx index 655c770fe..18e5f93c6 100644 --- a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx @@ -1,9 +1,8 @@ -import React from 'react'; -import { ModelsSection } from './ModelsSection'; -import { RulesSection } from './RulesSection'; -import { DocsSection } from './DocsSection'; -import { PromptsSection } from './PromptsSection'; -import { ContextSection } from './ContextSection'; +import { ContextSection } from "./ContextSection"; +import { DocsSection } from "./DocsSection"; +import { ModelsSection } from "./ModelsSection"; +import { PromptsSection } from "./PromptsSection"; +import { RulesSection } from "./RulesSection"; interface SelectedSectionProps { selectedSection: string | null; @@ -24,4 +23,4 @@ export function SelectedSection(props: SelectedSectionProps) { default: return null; } -} \ No newline at end of file +} From f613b438da136abc75b77d9175286b200d9ea7a6 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 21 Mar 2025 11:27:58 -0700 Subject: [PATCH 021/709] tool lump section --- gui/src/components/mainInput/InputToolbar.tsx | 3 - .../InputToolbar/ToggleToolsButton.tsx | 178 ------------------ .../InputToolbar/ToolDropdownItem.tsx | 2 +- .../mainInput/Lump/TopInputToolbar.tsx | 11 ++ gui/src/components/mainInput/Lump/index.tsx | 4 +- .../Lump/sections/SelectedSection.tsx | 3 + .../mainInput/Lump/sections/ToolsSection.tsx | 25 +++ 7 files changed, 43 insertions(+), 183 deletions(-) delete mode 100644 gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx create mode 100644 gui/src/components/mainInput/Lump/sections/ToolsSection.tsx diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 2642fc089..9c1bdb15e 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -29,7 +29,6 @@ import { import { ToolTip } from "../gui/Tooltip"; import ModelSelect from "../modelSelection/ModelSelect"; import HoverItem from "./InputToolbar/HoverItem"; -import ToggleToolsButton from "./InputToolbar/ToggleToolsButton"; const StyledDiv = styled.div<{ isHidden?: boolean }>` padding-top: 4px; @@ -158,8 +157,6 @@ function InputToolbar(props: InputToolbarProps) { )} - -
diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx deleted file mode 100644 index 20dae9160..000000000 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ /dev/null @@ -1,178 +0,0 @@ -import { Listbox } from "@headlessui/react"; -import { - EllipsisHorizontalCircleIcon as EllipsisHorizontalIcon, - WrenchScrewdriverIcon as WrenchScrewdriverIconOutline, -} from "@heroicons/react/24/outline"; -import { WrenchScrewdriverIcon as WrenchScrewdriverIconSolid } from "@heroicons/react/24/solid"; -import { useEffect, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; -import { lightGray, vscForeground } from "../.."; -import { useAppSelector } from "../../../redux/hooks"; -import { toggleUseTools } from "../../../redux/slices/uiSlice"; -import { ToolTip } from "../../gui/Tooltip"; -import InfoHover from "../../InfoHover"; -import HoverItem from "./HoverItem"; -import PopoverTransition from "./PopoverTransition"; -import ToolDropdownItem from "./ToolDropdownItem"; -import { selectIsInEditMode } from "../../../redux/slices/sessionSlice"; - -interface ToolDropdownProps { - disabled: boolean; -} - -export default function ToolDropdown(props: ToolDropdownProps) { - const buttonRef = useRef(null); - const dispatch = useDispatch(); - const [isDropdownOpen, setDropdownOpen] = useState(false); - const [isHovered, setIsHovered] = useState(false); - - const useTools = useAppSelector((state) => state.ui.useTools); - const availableTools = useAppSelector((state) => state.config.config.tools); - const [showAbove, setShowAbove] = useState(false); - const isInEditMode = useAppSelector(selectIsInEditMode); - - const ToolsIcon = useTools - ? WrenchScrewdriverIconSolid - : WrenchScrewdriverIconOutline; - - useEffect(() => { - const checkPosition = () => { - if (buttonRef.current) { - const rect = buttonRef.current.getBoundingClientRect(); - const windowHeight = window.innerHeight; - const spaceBelow = windowHeight - rect.bottom; - setShowAbove(spaceBelow < 250); - } - }; - - if (isDropdownOpen) { - checkPosition(); - } - }, [isDropdownOpen]); - - const isDisabled = props.disabled || isInEditMode; - - return ( - !isDisabled && dispatch(toggleUseTools())}> -
- !isDisabled && setIsHovered(true)} - onMouseLeave={() => !isDisabled && setIsHovered(false)} - /> - {isDisabled && ( - - {isInEditMode - ? "Tool use not supported in edit mode" - : "This model does not support tool use"} - - )} - {!useTools && !isDisabled && ( - - Enable tool usage - - )} - - {useTools && !isDisabled && ( - <> - Tools - -
- {}} - as="div" - onClick={(e) => e.stopPropagation()} - disabled={isDisabled} - > - {({ open }) => ( - <> - { - e.stopPropagation(); - setDropdownOpen(!isDropdownOpen); - }} - className="text-lightgray flex cursor-pointer items-center border-none bg-transparent px-0 outline-none" - aria-disabled={isDisabled} - > - - - setDropdownOpen(false)} - > - -
-
- Tool policies{" "} - -

- - Automatic: - {" "} - Can be used without asking -

-

- - Allowed: - {" "} - Will ask before using -

-

- - Disabled: - {" "} - Cannot be used -

-
- } - /> -
-
-
- {availableTools.map((tool: any) => ( - - - - ))} -
- - - - )} - -
- - )} -
- - ); -} diff --git a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx index 5df66f147..adea1943b 100644 --- a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx @@ -26,7 +26,7 @@ function ToolDropdownItem(props: ToolDropdownItemProps) { return (
{ dispatch(toggleToolSetting(props.tool.function.name)); e.stopPropagation(); diff --git a/gui/src/components/mainInput/Lump/TopInputToolbar.tsx b/gui/src/components/mainInput/Lump/TopInputToolbar.tsx index b6a6633fc..ab51c8bfa 100644 --- a/gui/src/components/mainInput/Lump/TopInputToolbar.tsx +++ b/gui/src/components/mainInput/Lump/TopInputToolbar.tsx @@ -4,6 +4,7 @@ import { CubeIcon, FolderIcon, PencilIcon, + WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; import HoverItem from "../InputToolbar/HoverItem"; @@ -90,6 +91,16 @@ export function TopInputToolbar(props: TopInputProps) { ) } /> + + props.setSelectedSection( + props.selectedSection === "tools" ? null : "tools", + ) + } + />
diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index 3c50eef32..bd54b5015 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -39,7 +39,9 @@ export function Lump(props: LumpProps) { setSelectedSection={setSelectedSection} /> - +
+ +
); diff --git a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx index 18e5f93c6..0e0da16d9 100644 --- a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx @@ -3,6 +3,7 @@ import { DocsSection } from "./DocsSection"; import { ModelsSection } from "./ModelsSection"; import { PromptsSection } from "./PromptsSection"; import { RulesSection } from "./RulesSection"; +import { ToolsSection } from "./ToolsSection"; interface SelectedSectionProps { selectedSection: string | null; @@ -20,6 +21,8 @@ export function SelectedSection(props: SelectedSectionProps) { return ; case "context": return ; + case "tools": + return ; default: return null; } diff --git a/gui/src/components/mainInput/Lump/sections/ToolsSection.tsx b/gui/src/components/mainInput/Lump/sections/ToolsSection.tsx new file mode 100644 index 000000000..34106b701 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/ToolsSection.tsx @@ -0,0 +1,25 @@ +import { useAppSelector } from "../../../../redux/hooks"; +import { getFontSize } from "../../../../util"; +import ToolDropdownItem from "../../InputToolbar/ToolDropdownItem"; + +interface ToolsSectionProps {} + +export function ToolsSection({}: ToolsSectionProps) { + const availableTools = useAppSelector((state) => state.config.config.tools); + + return ( +
+ {availableTools.map((tool: any) => ( +
+ +
+ ))} +
+ ); +} From 0c829fd99d0e898c1afdc90a0957c907dcb7f4e2 Mon Sep 17 00:00:00 2001 From: liuk Date: Sat, 22 Mar 2025 02:29:55 +0800 Subject: [PATCH 022/709] feat: Improve ProtocolClient initialization and GUI loading - Introduce `onProtocolClientInitialized` to handle client initialization events. - Use `Delegates.observable` for `ideProtocolClient` to trigger listeners on changes. - Ensure URL loading is deferred until protocol client is initialized. --- .../services/ContinuePluginService.kt | 26 +++++++++++++++++-- .../toolWindow/ContinueBrowser.kt | 20 +++++++------- 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index cf1005596..6ebb8f41f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -1,6 +1,5 @@ package com.github.continuedev.continueintellijextension.services -import IntelliJIDE import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager import com.github.continuedev.continueintellijextension.`continue`.DiffManager @@ -13,12 +12,16 @@ import com.intellij.openapi.project.DumbAware import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel +import kotlin.properties.Delegates @Service(Service.Level.PROJECT) class ContinuePluginService : Disposable, DumbAware { private val coroutineScope = CoroutineScope(Dispatchers.Main) var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null - var ideProtocolClient: IdeProtocolClient? = null + var listener: (() -> Unit)? = null + var ideProtocolClient: IdeProtocolClient? by Delegates.observable(null) { _, _, _ -> + synchronized(this) { listener?.also { listener = null }?.invoke() } + } var coreMessengerManager: CoreMessengerManager? = null val coreMessenger: CoreMessenger? get() = coreMessengerManager?.coreMessenger @@ -41,4 +44,23 @@ class ContinuePluginService : Disposable, DumbAware { ) { continuePluginWindow?.browser?.sendToWebview(messageType, data, messageId) } + + /** + * Add a listener for protocolClient initialization. + * Currently, only one needs to be processed. If there are more than one, + * we can use an array to add listeners to ensure that the message is processed. + */ + fun onProtocolClientInitialized(listener: () -> Unit) { + if (ideProtocolClient == null) { + synchronized(this) { + if (ideProtocolClient == null) { + this.listener = listener + } else { + listener() + } + } + } else { + listener() + } + } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 8cb700f15..43a468cf7 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -1,7 +1,6 @@ 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 @@ -10,11 +9,11 @@ import com.github.continuedev.continueintellijextension.utils.uuid import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonParser -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.ui.jcef.* import com.intellij.ui.jcef.JBCefClient.Properties +import com.intellij.util.application import org.cef.CefApp import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter @@ -30,8 +29,10 @@ class ContinueBrowser(val project: Project, url: String) { val browser: JBCefBrowser + val continuePluginService: ContinuePluginService = project.getService(ContinuePluginService::class.java) + init { - val isOSREnabled = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR + val isOSREnabled = application.getService(ContinueExtensionSettings::class.java).continueState.enableOSR this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build().apply { // To avoid using System.setProperty to affect other plugins, @@ -42,7 +43,6 @@ class ContinueBrowser(val project: Project, url: String) { } registerAppSchemeHandler() - browser.loadURL(url) Disposer.register(ContinuePluginDisposable.getInstance(project), browser) // Listen for events sent from browser @@ -55,11 +55,6 @@ class ContinueBrowser(val project: Project, url: String) { val data = json.get("data") val messageId = json.get("messageId")?.asString - val continuePluginService = ServiceManager.getService( - project, - ContinuePluginService::class.java - ) - val respond = fun(data: Any?) { sendToWebview(messageType, data, messageId ?: uuid()) } @@ -101,6 +96,13 @@ class ContinueBrowser(val project: Project, url: String) { } }, browser.cefBrowser) + // Load the url only after the protocolClient is initialized, + // otherwise some messages will be lost, which are some configurations when the page is loaded. + // Moreover, we should add LoadHandler before loading the url. + continuePluginService.onProtocolClientInitialized { + browser.loadURL(url) + } + } fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) { From a49ac7b6aab1318d2d829b02de2744e6f785895c Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 21 Mar 2025 12:39:03 -0700 Subject: [PATCH 023/709] styling of lump icons --- gui/src/components/index.ts | 3 +- .../mainInput/Lump/TopInputToolbar.tsx | 33 ++++++++++++++++--- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index 04460f3b1..4b0d145b2 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -1,5 +1,5 @@ import styled from "styled-components"; -import { getFontSize, isJetBrains } from "../util"; +import { getFontSize } from "../util"; export const VSC_INPUT_BACKGROUND_VAR = "--vscode-input-background"; export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background"; @@ -59,6 +59,7 @@ export const vscListActiveForeground = `var(${VSC_LIST_ACTIVE_FOREGROUND_VAR}, $ export const vscInputBorder = `var(${VSC_INPUT_BORDER_VAR}, ${lightGray})`; export const vscInputBorderFocus = `var(${VSC_FOCUS_BORDER_VAR}, ${lightGray})`; export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`; +export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #ffffff)`; export const vscCommandCenterActiveBorder = `var(${VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR}, #1bbe84)`; export const vscCommandCenterInactiveBorder = `var(${VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR}, #1bbe84)`; export const vscFindMatchSelected = `var(${VSC_FIND_MATCH_SELECTED_VAR}, rgba(255, 223, 0))`; diff --git a/gui/src/components/mainInput/Lump/TopInputToolbar.tsx b/gui/src/components/mainInput/Lump/TopInputToolbar.tsx index ab51c8bfa..bdf379f9a 100644 --- a/gui/src/components/mainInput/Lump/TopInputToolbar.tsx +++ b/gui/src/components/mainInput/Lump/TopInputToolbar.tsx @@ -6,6 +6,8 @@ import { PencilIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; +import { vscBadgeBackground, vscBadgeForeground } from "../.."; +import { getFontSize } from "../../../util"; import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; import HoverItem from "../InputToolbar/HoverItem"; @@ -20,12 +22,33 @@ interface TopToolbarIconProps { function TopToolbarIcon(props: TopToolbarIconProps) { return ( -
+
+
+ + {props.tooltip} + +
); @@ -40,7 +63,7 @@ export function TopInputToolbar(props: TopInputProps) { return (
-
+
Date: Fri, 21 Mar 2025 12:44:19 -0700 Subject: [PATCH 024/709] make tabs tabbable --- .../components/mainInput/Lump/TopInputToolbar.tsx | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/gui/src/components/mainInput/Lump/TopInputToolbar.tsx b/gui/src/components/mainInput/Lump/TopInputToolbar.tsx index bdf379f9a..e77e62da4 100644 --- a/gui/src/components/mainInput/Lump/TopInputToolbar.tsx +++ b/gui/src/components/mainInput/Lump/TopInputToolbar.tsx @@ -23,18 +23,25 @@ function TopToolbarIcon(props: TopToolbarIconProps) { return (
{ + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + props.onClick(); + } + }} style={{ backgroundColor: props.isSelected ? vscBadgeBackground : undefined, }} - className={`relative flex select-none items-center px-0.5 transition-all duration-200 ${ - props.isSelected ? "rounded-full" : "" - }`} + className={`relative flex select-none items-center rounded-full px-0.5 transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50`} >