diff --git a/core/config/util.ts b/core/config/util.ts index 1b2c397b7..5abf0b9b5 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -1,5 +1,5 @@ -import { ModelDescription } from "../index.js"; -import { editConfigJson } from "../util/paths.js"; +import { ContextProviderWithParams, ModelDescription } from "../"; +import { editConfigJson } from "../util/paths"; function stringify(obj: any, indentation?: number): string { return JSON.stringify( @@ -11,6 +11,18 @@ function stringify(obj: any, indentation?: number): string { ); } +export function addContextProvider(provider: ContextProviderWithParams) { + editConfigJson((config) => { + if (!config.contextProviders) { + config.contextProviders = [provider]; + } else { + config.contextProviders.push(provider); + } + + return config; + }); +} + export function addModel(model: ModelDescription) { editConfigJson((config) => { if (config.models?.some((m: any) => stringify(m) === stringify(model))) { diff --git a/core/context/providers/CustomContextProvider.ts b/core/context/providers/CustomContextProvider.ts index fd996f398..ac14dc9f4 100644 --- a/core/context/providers/CustomContextProvider.ts +++ b/core/context/providers/CustomContextProvider.ts @@ -5,7 +5,7 @@ import type { CustomContextProvider, IContextProvider, LoadSubmenuItemsArgs, -} from "../../index.js"; +} from "../../"; class CustomContextProviderClass implements IContextProvider { custom: CustomContextProvider; diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 972c12190..88df47318 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -90,7 +90,8 @@ class DocsContextProvider extends BaseContextProvider { await docsService.isJetBrainsAndPreIndexedDocsProvider(); if (isJetBrainsAndPreIndexedDocsProvider) { - extras.ide.errorPopup( + extras.ide.showToast( + "error", `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + "the embeddings provider, but it cannot be used with JetBrains. " + "Please select a different embeddings provider to use the '@docs' " + @@ -108,8 +109,9 @@ class DocsContextProvider extends BaseContextProvider { }); } - const embeddingsProvider = - await docsService.getEmbeddingsProvider(!!preIndexedDoc); + const embeddingsProvider = await docsService.getEmbeddingsProvider( + !!preIndexedDoc, + ); const [vector] = await embeddingsProvider.embed([extras.fullInput]); diff --git a/core/core.ts b/core/core.ts index 5de63b5b4..ad72a44ce 100644 --- a/core/core.ts +++ b/core/core.ts @@ -176,7 +176,7 @@ export class Core { message: err.message, stack: err.stack, }); - this.messenger.request("errorPopup", { message: err.message }); + this.ide.showToast("error", err.message); }); // New @@ -272,9 +272,9 @@ export class Core { } if (hasFailed) { - this.ide.infoPopup(`Failed to index ${msg.data.startUrl}`); + this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); } else { - this.ide.infoPopup(`Successfully indexed ${msg.data.startUrl}`); + this.ide.showToast("info", `Successfully indexed ${msg.data.startUrl}`); this.messenger.send("refreshSubmenuItems", undefined); } }); @@ -344,7 +344,10 @@ export class Core { id, })); } catch (e) { - this.ide.errorPopup(`Error getting context items from ${name}: ${e}`); + this.ide.showToast( + "error", + `Error getting context items from ${name}: ${e}`, + ); return []; } }); diff --git a/core/index.d.ts b/core/index.d.ts index eec22f18d..0e87e126a 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -121,7 +121,7 @@ export interface ILLM extends LLMOptions { export type ContextProviderType = "normal" | "query" | "submenu"; export interface ContextProviderDescription { - title: string; + title: ContextProviderName; displayTitle: string; description: string; renderInlineAs?: string; @@ -317,6 +317,9 @@ export interface LLMFullCompletionOptions extends BaseCompletionOptions { model?: string; } + +export type ToastType = "info" | "error" | "warning"; + export interface LLMOptions { model: string; @@ -497,9 +500,11 @@ export interface IDE { getBranch(dir: string): Promise; getTags(artifactId: string): Promise; getRepoName(dir: string): Promise; - errorPopup(message: string): Promise; - infoPopup(message: string): Promise; - + showToast( + type: ToastType, + message: string, + ...otherParams: any[] + ): Promise; getGitRootPath(dir: string): Promise; listDir(dir: string): Promise<[string, FileType][]>; getLastModified(files: string[]): Promise<{ [path: string]: number }>; @@ -569,7 +574,15 @@ type ContextProviderName = | "docs" | "gitlab-mr" | "os" - | "currentFile"; + | "currentFile" + | "outline" + | "continue-proxy" + | "highlights" + | "file" + | "issue" + | "repo-map" + | "url" + | string; type TemplateType = | "llama2" @@ -919,6 +932,13 @@ interface ExperimentalConfig { * Automatically read LLM chat responses aloud using system TTS models */ readResponseTTS?: boolean; + + /** + * If set to true, we will attempt to pull down and install an instance of Chromium + * that is compatible with the current version of Puppeteer. + * This is needed to crawl a large number of documentation sites that are dynamically rendered. + */ + useChromiumForDocsCrawling?: boolean; } interface AnalyticsConfig { diff --git a/core/indexing/docs/DocsCrawler.skip.ts b/core/indexing/docs/DocsCrawler.skip.ts new file mode 100644 index 000000000..5f7bd8936 --- /dev/null +++ b/core/indexing/docs/DocsCrawler.skip.ts @@ -0,0 +1,180 @@ +// import { SpiedFunction } from "jest-mock"; +// import DocsCrawler, { +// ChromiumCrawler, +// ChromiumInstaller, +// type PageData, +// } from "./DocsCrawler"; +// import preIndexedDocs from "./preIndexedDocs"; +// import { jest } from "@jest/globals"; +// import FileSystemIde from "../../util/filesystem"; + +// // Temporary workaround until we have better caching of Chromium +// // download between test runs +// const TIMEOUT_MS = 1_000_000_000; + +// // Skipped until we have a better way to cache Chromium installs +// // between tests and in CI +// describe.skip("crawl", () => { +// const mockIde = new FileSystemIde(process.cwd()); + +// const chromiumInstaller = new ChromiumInstaller(mockIde); +// beforeAll(async () => { +// // Make sure we have Chromium pulled down before beginning tests +// await ChromiumInstaller.install(); +// }, TIMEOUT_MS); + +// describe("GitHub Crawler", () => { +// const repoUrl = +// "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling"; + +// let crawlResults: PageData[]; + +// beforeAll(async () => { +// const docsCrawler = new DocsCrawler(); + +// crawlResults = []; + +// for await (const page of docsCrawler.crawl(new URL(repoUrl))) { +// crawlResults.push(page); +// } +// }, TIMEOUT_MS); + +// test("finds expected markdown files", async () => { +// expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( +// true, +// ); + +// expect( +// crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), +// ).toBe(true); +// }); + +// test("html includes the correct content", async () => { +// const doc = crawlResults.find((page) => +// page.path.endsWith("docs-depth-1.md"), +// ); + +// expect(doc?.content.includes("Test body")).toBe(true); +// expect(doc?.content.includes("Test H2 Header")).toBe(true); +// }); + +// test("ignores non-markdown files, e.g. `test.js` at the root", async () => { +// expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( +// false, +// ); +// }); +// }); + +// describe("Chromium Crawler", () => { +// it("Pre-indexed Docs", () => { +// const results: { [url: string]: boolean } = {}; +// let totalTests = 0; +// let passedTests = 0; + +// Object.keys(preIndexedDocs).forEach((url) => { +// it( +// `Crawl test for ${url}`, +// async () => { +// totalTests++; +// let pageFound = false; + +// try { +// const docsCrawler = new DocsCrawler(); + +// for await (const page of docsCrawler.crawl(new URL(url), 1)) { +// if (page.url === url) { +// pageFound = true; +// break; +// } +// } +// } catch (error) { +// console.error(`Error crawling ${url}:`, error); +// } + +// results[url] = pageFound; +// if (pageFound) { +// passedTests++; +// console.log(`✅ ${url}`); +// } else { +// console.log(`❌ ${url}`); +// } + +// expect(pageFound).toBe(true); +// }, +// TIMEOUT_MS, +// ); +// }); +// }); + +// it( +// "succeeds in crawling a list of common sites", +// async () => { +// const TEST_SITES = [ +// "https://docs.nestjs.com/", +// "https://docs.nestjs.com/", +// "https://go.dev/doc/", +// "https://clickhouse.com/docs", +// "https://www.tensorflow.org/api_docs", +// "https://www.rust-lang.org/learn", +// "https://docs.anthropic.com/en/docs", +// ]; + +// const NUM_PAGES_TO_CRAWL = 10; + +// for (const site of TEST_SITES) { +// const crawlResults: PageData[] = []; +// const docsCrawler = new DocsCrawler(); + +// for await (const page of docsCrawler.crawl( +// new URL(site), +// NUM_PAGES_TO_CRAWL, +// )) { +// crawlResults.push(page); +// } + +// // `toBeGreaterThanOrEqual` because Crawlee doesn't guarantee +// // an exact number of pages to crawl since it runs in parallel +// expect(crawlResults.length).toBeGreaterThanOrEqual( +// NUM_PAGES_TO_CRAWL, +// ); +// } +// }, +// TIMEOUT_MS, +// ); +// }); + +// describe("Cheerio Crawler", () => { +// let mockVerifyOrInstallChromium: SpiedFunction<() => Promise>; + +// beforeAll(() => { +// mockVerifyOrInstallChromium = jest +// .spyOn(ChromiumCrawler, "verifyOrInstallChromium") +// .mockResolvedValue(false); +// }); + +// afterAll(() => { +// mockVerifyOrInstallChromium.mockRestore(); +// }); + +// it( +// "succeeds in crawling a basic site", +// async () => { +// const NUM_PAGES_TO_CRAWL = 1; +// const site = "https://amplified.dev/"; + +// const crawlResults: PageData[] = []; +// const docsCrawler = new DocsCrawler(); + +// for await (const page of docsCrawler.crawl( +// new URL(site), +// NUM_PAGES_TO_CRAWL, +// )) { +// crawlResults.push(page); +// } + +// expect(crawlResults.length).toBeGreaterThanOrEqual(NUM_PAGES_TO_CRAWL); +// }, +// TIMEOUT_MS, +// ); +// }); +// }); diff --git a/core/indexing/docs/DocsCrawler.test.ts b/core/indexing/docs/DocsCrawler.test.ts deleted file mode 100644 index 42083634f..000000000 --- a/core/indexing/docs/DocsCrawler.test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { SpiedFunction } from "jest-mock"; -import DocsCrawler, { ChromiumCrawler, type PageData } from "./DocsCrawler"; -import preIndexedDocs from "./preIndexedDocs"; -import { jest } from "@jest/globals"; - -// Temporary workaround until we have better caching of Chromium -// download between test runs -const TIMEOUT_MS = 1_000_000_000; - -// Skipped until we have a better way to cache Chromium installs -// between tests and in CI -describe.skip("crawl", () => { - beforeAll(async () => { - // Make sure we have Chromium pulled down before beginning tests - await ChromiumCrawler.verifyOrInstallChromium(); - }, TIMEOUT_MS); - - describe("GitHub Crawler", () => { - const repoUrl = - "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling"; - - let crawlResults: PageData[]; - - beforeAll(async () => { - const docsCrawler = new DocsCrawler(); - - crawlResults = []; - - for await (const page of docsCrawler.crawl(new URL(repoUrl))) { - crawlResults.push(page); - } - }, TIMEOUT_MS); - - test("finds expected markdown files", async () => { - expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( - true, - ); - - expect( - crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), - ).toBe(true); - }); - - test("html includes the correct content", async () => { - const doc = crawlResults.find((page) => - page.path.endsWith("docs-depth-1.md"), - ); - - expect(doc?.content.includes("Test body")).toBe(true); - expect(doc?.content.includes("Test H2 Header")).toBe(true); - }); - - test("ignores non-markdown files, e.g. `test.js` at the root", async () => { - expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( - false, - ); - }); - }); - - describe("Chromium Crawler", () => { - it("Pre-indexed Docs", () => { - const results: { [url: string]: boolean } = {}; - let totalTests = 0; - let passedTests = 0; - - Object.keys(preIndexedDocs).forEach((url) => { - it( - `Crawl test for ${url}`, - async () => { - totalTests++; - let pageFound = false; - - try { - const docsCrawler = new DocsCrawler(); - - for await (const page of docsCrawler.crawl(new URL(url), 1)) { - if (page.url === url) { - pageFound = true; - break; - } - } - } catch (error) { - console.error(`Error crawling ${url}:`, error); - } - - results[url] = pageFound; - if (pageFound) { - passedTests++; - console.log(`✅ ${url}`); - } else { - console.log(`❌ ${url}`); - } - - expect(pageFound).toBe(true); - }, - TIMEOUT_MS, - ); - }); - }); - - it( - "succeeds in crawling a list of common sites", - async () => { - const TEST_SITES = [ - "https://docs.nestjs.com/", - "https://docs.nestjs.com/", - "https://go.dev/doc/", - "https://clickhouse.com/docs", - "https://www.tensorflow.org/api_docs", - "https://www.rust-lang.org/learn", - "https://docs.anthropic.com/en/docs", - ]; - - const NUM_PAGES_TO_CRAWL = 10; - - for (const site of TEST_SITES) { - const crawlResults: PageData[] = []; - const docsCrawler = new DocsCrawler(); - - for await (const page of docsCrawler.crawl( - new URL(site), - NUM_PAGES_TO_CRAWL, - )) { - crawlResults.push(page); - } - - // `toBeGreaterThanOrEqual` because Crawlee doesn't guarantee - // an exact number of pages to crawl since it runs in parallel - expect(crawlResults.length).toBeGreaterThanOrEqual( - NUM_PAGES_TO_CRAWL, - ); - } - }, - TIMEOUT_MS, - ); - }); - - describe("Cheerio Crawler", () => { - let mockVerifyOrInstallChromium: SpiedFunction<() => Promise>; - - beforeAll(() => { - mockVerifyOrInstallChromium = jest - .spyOn(ChromiumCrawler, "verifyOrInstallChromium") - .mockResolvedValue(false); - }); - - afterAll(() => { - mockVerifyOrInstallChromium.mockRestore(); - }); - - it( - "succeeds in crawling a basic site", - async () => { - const NUM_PAGES_TO_CRAWL = 1; - const site = "https://amplified.dev/"; - - const crawlResults: PageData[] = []; - const docsCrawler = new DocsCrawler(); - - for await (const page of docsCrawler.crawl( - new URL(site), - NUM_PAGES_TO_CRAWL, - )) { - crawlResults.push(page); - } - - expect(crawlResults.length).toBeGreaterThanOrEqual(NUM_PAGES_TO_CRAWL); - }, - TIMEOUT_MS, - ); - }); -}); diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index 05364f028..7b0541559 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -1,18 +1,18 @@ import { Octokit } from "@octokit/rest"; +import * as cheerio from "cheerio"; import * as fs from "fs"; +import fetch from "node-fetch"; import { URL } from "node:url"; -import { Page } from "puppeteer"; +import { Handler, HTTPResponse, Page } from "puppeteer"; import { + editConfigJson, getChromiumPath, getContinueUtilsPath, - editConfigJson, } from "../../util/paths"; // @ts-ignore // @prettier-ignore import PCR from "puppeteer-chromium-resolver"; -import * as cheerio from "cheerio"; -import fetch from "node-fetch"; -import { GlobalContext } from "../../util/GlobalContext"; +import { ContinueConfig, IDE } from "../.."; export type PageData = { url: string; @@ -23,10 +23,20 @@ export type PageData = { class DocsCrawler { private readonly MAX_REQUESTS_PER_CRAWL = 1000; private readonly GITHUB_HOST = "github.com"; - private useChromiumPromise: Promise | undefined = undefined; + private readonly chromiumInstaller: ChromiumInstaller; - constructor() { - this.useChromiumPromise = ChromiumCrawler.verifyOrInstallChromium(); + constructor( + private readonly ide: IDE, + private readonly config: ContinueConfig, + ) { + this.chromiumInstaller = new ChromiumInstaller(this.ide, this.config); + } + + private shouldUseChromium() { + return ( + this.config.experimental?.useChromiumForDocsCrawling && + this.chromiumInstaller.isInstalled() + ); } async *crawl( @@ -35,11 +45,39 @@ class DocsCrawler { ): AsyncGenerator { if (startUrl.host === this.GITHUB_HOST) { yield* new GitHubCrawler(startUrl).crawl(); + } else if (this.shouldUseChromium()) { + yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl(); } else { - if (await this.useChromiumPromise) { - yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl(); - } else { - yield* new CheerioCrawler(startUrl, maxRequestsPerCrawl).crawl(); + let didCrawlSinglePage = false; + + for await (const pageData of new CheerioCrawler( + startUrl, + maxRequestsPerCrawl, + ).crawl()) { + yield pageData; + didCrawlSinglePage = true; + } + + // We assume that if we failed to crawl a single page, + // it was due to an error that using Chromium can resolve + const shouldProposeUseChromium = + !didCrawlSinglePage && + this.chromiumInstaller.shouldProposeUseChromiumOnCrawlFailure(); + + if (shouldProposeUseChromium) { + const didInstall = + await this.chromiumInstaller.proposeAndAttemptInstall( + startUrl.toString(), + ); + + if (didInstall) { + this.ide.showToast( + "info", + `Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`, + ); + + yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl(); + } } } } @@ -152,12 +190,15 @@ class CheerioCrawler { (this.constructor as any).name }] Starting crawl from: ${url} - Max Depth: ${maxDepth}`, ); + const { baseUrl, basePath } = this.splitUrl(url); + let paths: { path: string; depth: number }[] = [ { path: basePath, depth: 0 }, ]; let index = 0; + while (index < paths.length) { const batch = paths.slice(index, index + 50); @@ -189,15 +230,12 @@ class CheerioCrawler { } } } catch (e) { - if (e instanceof TypeError) { - console.warn("Error while crawling page: ", e); - } else { - console.error("Error while crawling page: ", e); - } + console.debug("Error while crawling page: ", e); } index += batch.length; } + console.log("Crawl completed"); } @@ -264,20 +302,28 @@ class CheerioCrawler { class ChromiumCrawler { private readonly LINK_GROUP_SIZE = 2; - private static PCR_CONFIG = { downloadPath: getContinueUtilsPath() }; constructor( private readonly startUrl: URL, private readonly maxRequestsPerCrawl: number, ) {} + static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) { + editConfigJson((config) => ({ + ...config, + experimental: { + ...config.experimental, + useChromiumForDocsCrawling, + }, + })); + } + async *crawl(): AsyncGenerator { console.debug( - `[${(this.constructor as any).name}] Crawling site repo: ${ - this.startUrl - }`, + `[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`, ); - const stats = await PCR(ChromiumCrawler.PCR_CONFIG); + + const stats = await PCR(ChromiumInstaller.PCR_CONFIG); const browser = await stats.puppeteer.launch({ args: [ "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", @@ -290,17 +336,56 @@ class ChromiumCrawler { yield* this.crawlSitePages(page, this.startUrl); } catch (e) { console.debug("Error getting links: ", e); + console.debug( + `Setting 'useChromiumForDocsCrawling' to 'false' in config.json`, + ); + + ChromiumCrawler.setUseChromiumForDocsCrawling(false); } finally { await browser.close(); } } + /** + * We need to handle redirects manually, otherwise there are race conditions. + * + * https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573 + */ + private async gotoPageAndHandleRedirects(page: Page, url: string) { + const MAX_PAGE_WAIT_MS = 5000; + + await page.goto(url, { + timeout: 0, + waitUntil: "networkidle2", + }); + + let responseEventOccurred = false; + const responseHandler: Handler = (event) => + (responseEventOccurred = true); + + const responseWatcher = new Promise(function (resolve, reject) { + setTimeout(() => { + if (!responseEventOccurred) { + resolve(); + } else { + setTimeout(() => resolve(), MAX_PAGE_WAIT_MS); + } + }, 500); + }); + + page.on("response", responseHandler); + + await Promise.race([responseWatcher, page.waitForNavigation()]); + } + private async *crawlSitePages( page: Page, curUrl: URL, visitedLinks: Set = new Set(), curRequestCount: number = 0, ): AsyncGenerator { + const urlStr = curUrl.toString(); + if (curRequestCount >= this.maxRequestsPerCrawl) { console.warn( `[${ @@ -310,25 +395,25 @@ class ChromiumCrawler { return; } - if (visitedLinks.has(curUrl.toString())) { + if (visitedLinks.has(urlStr)) { return; } console.debug( - `[${(this.constructor as any).name}] Crawling page: ${curUrl.toString()}`, + `[${(this.constructor as any).name}] Crawling page: ${urlStr}`, ); - await page.goto(curUrl.toString()); + await this.gotoPageAndHandleRedirects(page, urlStr); const htmlContent = await page.content(); const linkGroups = await this.getLinkGroupsFromPage(page, curUrl); const requestCount = curRequestCount + 1; - visitedLinks.add(curUrl.toString()); + visitedLinks.add(urlStr); yield { path: curUrl.pathname, - url: curUrl.toString(), + url: urlStr, content: htmlContent, }; @@ -395,34 +480,89 @@ class ChromiumCrawler { return groups; } +} - static async verifyOrInstallChromium() { - const globalContext = new GlobalContext(); +class ChromiumInstaller { + static PCR_CONFIG = { downloadPath: getContinueUtilsPath() }; - // If we previously failed to install Chromium, don't try again - if (globalContext.get("didPrevChromiumInstallFail")) { - return false; + constructor( + private readonly ide: IDE, + private readonly config: ContinueConfig, + ) { + if (this.shouldInstallOnStartup()) { + console.log("Installing Chromium"); + this.install(); } + } - if (fs.existsSync(getChromiumPath())) { - return true; + isInstalled() { + return fs.existsSync(getChromiumPath()); + } + + shouldInstallOnStartup() { + return ( + !this.isInstalled() && + this.config.experimental?.useChromiumForDocsCrawling + ); + } + + shouldProposeUseChromiumOnCrawlFailure() { + const { experimental } = this.config; + + return ( + experimental?.useChromiumForDocsCrawling === undefined || + experimental.useChromiumForDocsCrawling + ); + } + + async proposeAndAttemptInstall(site: string) { + const userAcceptedInstall = await this.proposeInstall(site); + + if (userAcceptedInstall) { + const didInstall = await this.install(); + return didInstall; } + } + private async install() { try { - await PCR(ChromiumCrawler.PCR_CONFIG); + await PCR(ChromiumInstaller.PCR_CONFIG); + + ChromiumCrawler.setUseChromiumForDocsCrawling(true); + return true; } catch (error) { console.debug("Error installing Chromium : ", error); console.debug( - `Setting 'didPrevChromiumInstallFail' to 'true' in ${globalContext.constructor.name}`, + `Setting 'useChromiumForDocsCrawling' to 'false' in config.json`, ); - globalContext.update("didPrevChromiumInstallFail", true); + ChromiumCrawler.setUseChromiumForDocsCrawling(false); + + this.ide.showToast("error", "Failed to install Chromium"); return false; } } + + private async proposeInstall(site: string) { + const msg = + `Unable to crawl documentation site: ${site}\n` + + "We recommend installing Chromium. " + + "Download progress can be viewed in the developer console."; + + const actionMsg = "Install Chromium"; + + const res = await this.ide.showToast("warning", msg, actionMsg); + + return res === actionMsg; + } } export default DocsCrawler; -export { CheerioCrawler, ChromiumCrawler, GitHubCrawler }; +export { + CheerioCrawler, + ChromiumCrawler, + ChromiumInstaller as ChromiumInstaller, + GitHubCrawler, +}; diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 8859806ab..c2c39d0c5 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -31,6 +31,7 @@ import { SiteIndexingResults, } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; +import { addContextProvider } from "../../config/util"; // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { @@ -139,12 +140,34 @@ export default class DocsService { return !!title; } + async showAddDocsContextProviderToast() { + const actionMsg = "Add 'docs' context provider"; + const res = await this.ide.showToast( + "info", + "Starting docs indexing", + actionMsg, + ); + + if (res === actionMsg) { + addContextProvider({ + name: DocsContextProvider.description.title, + params: {}, + }); + + this.ide.showToast("info", "Successfuly added docs context provider"); + } + + return res === actionMsg; + } + async indexAllDocs(reIndex: boolean = false) { if (!this.hasDocsContextProvider()) { - this.ide.infoPopup( - "No 'docs' provider configured under 'contextProviders' in config.json", - ); - return; + const didAddDocsContextProvider = + await this.showAddDocsContextProviderToast(); + + if (!didAddDocsContextProvider) { + return; + } } const docs = await this.list(); @@ -154,7 +177,7 @@ export default class DocsService { while (!(await generator.next()).done) {} } - this.ide.infoPopup("Docs indexing completed"); + this.ide.showToast("info", "Docs indexing completed"); } async list() { @@ -383,7 +406,7 @@ export default class DocsService { private async init(configHandler: ConfigHandler) { this.config = await configHandler.loadConfig(); - this.docsCrawler = new DocsCrawler(); + this.docsCrawler = new DocsCrawler(this.ide, this.config); const embeddingsProvider = await this.getEmbeddingsProvider(); @@ -711,7 +734,8 @@ export default class DocsService { if (isJetBrainsAndPreIndexedDocsProvider) { // A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider - // this.ide.errorPopup( + // this.ide.showToast( + // "error", // "The 'transformers.js' embeddings provider currently cannot be used to index " + // "documentation in JetBrains. To enable documentation indexing, you can use " + // "any of the other providers described in the docs: " + diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index bb5f59810..d27945c3f 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -1,4 +1,4 @@ -import { ControlPlaneSessionInfo } from "../control-plane/client.js"; +import { ControlPlaneSessionInfo } from "../control-plane/client"; import type { ContinueRcJson, DiffLine, @@ -11,7 +11,8 @@ import type { Range, RangeInFile, Thread, -} from "../index.js"; + IDE, +} from "../"; export type ToIdeFromWebviewOrCoreProtocol = { // Methods from IDE type @@ -67,8 +68,10 @@ export type ToIdeFromWebviewOrCoreProtocol = { getBranch: [{ dir: string }, string]; getRepoName: [{ dir: string }, string | undefined]; - errorPopup: [{ message: string }, void]; - infoPopup: [{ message: string }, void]; + showToast: [ + Parameters, + Awaited>, + ]; getGitRootPath: [{ dir: string }, string | undefined]; listDir: [{ dir: string }, [string, FileType][]]; getLastModified: [{ files: string[] }, { [path: string]: number }]; diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index a66d8d6cf..3880b4609 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -5,7 +5,6 @@ import { EmbeddingsProvider } from "../index.js"; export type GlobalContextType = { indexingPaused: boolean; selectedTabAutocompleteModel: string; - didPrevChromiumInstallFail: boolean; lastSelectedProfileForWorkspace: { [workspaceIdentifier: string]: string }; /** * This is needed to handle the case where a JetBrains user has created diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 06209a474..35e1ea71c 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -12,12 +12,20 @@ import { Range, RangeInFile, Thread, + ToastType, } from "../index.d.js"; import { getContinueGlobalPath } from "./paths.js"; class FileSystemIde implements IDE { constructor(private readonly workspaceDir: string) {} + showToast( + type: ToastType, + message: string, + ...otherParams: any[] + ): Promise { + return Promise.resolve(); + } pathSep(): Promise { return Promise.resolve(path.sep); } @@ -73,23 +81,20 @@ class FileSystemIde implements IDE { ]); return Promise.resolve(all); } - infoPopup(message: string): Promise { - return Promise.resolve(); - } - errorPopup(message: string): Promise { - return Promise.resolve(); - } + getRepoName(dir: string): Promise { return Promise.resolve(undefined); } async getTags(artifactId: string): Promise { - const directory =(await this.getWorkspaceDirs())[0]; - return [{ - artifactId, - branch: await this.getBranch(directory), - directory - }]; + const directory = (await this.getWorkspaceDirs())[0]; + return [ + { + artifactId, + branch: await this.getBranch(directory), + directory, + }, + ]; } getIdeInfo(): Promise { diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts index 396df29c7..060c20766 100644 --- a/core/util/messageIde.ts +++ b/core/util/messageIde.ts @@ -10,6 +10,7 @@ import type { Range, RangeInFile, Thread, + ToastType, } from "../index.js"; import { ToIdeFromWebviewOrCoreProtocol } from "../protocol/ide.js"; import { FromIdeProtocol } from "../protocol/index.js"; @@ -25,6 +26,7 @@ export class MessageIde implements IDE { callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1], ) => void, ) {} + pathSep(): Promise { return this.request("pathSep", undefined); } @@ -54,12 +56,8 @@ export class MessageIde implements IDE { return this.request("listDir", { dir }); } - infoPopup(message: string): Promise { - return this.request("infoPopup", { message }); - } - - errorPopup(message: string): Promise { - return this.request("errorPopup", { message }); + showToast: IDE["showToast"] = (...params) => { + return this.request("showToast", params); } getRepoName(dir: string): Promise { diff --git a/core/util/reverseMessageIde.ts b/core/util/reverseMessageIde.ts index a65f1f1f2..46b4c2d0e 100644 --- a/core/util/reverseMessageIde.ts +++ b/core/util/reverseMessageIde.ts @@ -49,12 +49,8 @@ export class ReverseMessageIde { return this.ide.listDir(data.dir); }); - this.on("infoPopup", (data) => { - return this.ide.infoPopup(data.message); - }); - - this.on("errorPopup", (data) => { - return this.ide.errorPopup(data.message); + this.on("showToast", (data) => { + return this.ide.showToast(...data); }); this.on("getRepoName", (data) => { diff --git a/docs/docs/features/talk-to-your-docs.md b/docs/docs/features/talk-to-your-docs.md index 73b2b6b9e..01596e800 100644 --- a/docs/docs/features/talk-to-your-docs.md +++ b/docs/docs/features/talk-to-your-docs.md @@ -24,10 +24,6 @@ To enable the `@docs` context provider, you need to add it to the list of contex The `@docs` context provider works by crawling specified documentation sites, generating embeddings, and storing them locally for you. This process allows for quick and efficient access to your documentation content. -:::info -Note that we download and install a headless browser, Chromium, to crawl documentation sites. This is required to execute JavaScript on the page and ensure that we can crawl all the content. -::: - 1. We crawl the specified documentation site 2. Generate embeddings for the content 3. Store the embeddings locally on your machine @@ -71,6 +67,18 @@ The configuration schema is as follows: - `rootUrl`: The base URL of the documentation site, used to determine which pages to index. - `faviconUrl`: The URL of the site's favicon, used for visual identification in the UI. +## Crawling dynamically generated sites with `useChromiumForDocsCrawling` + +By default, we use a lighter weight tool to crawl documentation sites that cannot render sites that are dynamically generated using JavaScript. + +If you want to crawl a site that is dynamically generated, or you get an error while attempting to crawl a site, you can enable the experimental `useChromiumForDocsCrawling` feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`. + +```json title=config.json +"experimental": { + "useChromiumForDocsCrawling": true +} +``` + ## FAQ ### How often is the indexed content updated? diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/VsCodeIde.ts similarity index 96% rename from extensions/vscode/src/ideProtocol.ts rename to extensions/vscode/src/VsCodeIde.ts index b89e24b43..8ec9bb748 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -13,6 +13,7 @@ import type { Problem, RangeInFile, Thread, + ToastType, } from "core"; import { Range } from "core"; import { walkDir } from "core/indexing/walkDir"; @@ -42,6 +43,7 @@ class VsCodeIde implements IDE { ) { this.ideUtils = new VsCodeIdeUtils(); } + pathSep(): Promise { return Promise.resolve(this.ideUtils.path.sep); } @@ -191,13 +193,24 @@ class VsCodeIde implements IDE { return undefined; } - async infoPopup(message: string): Promise { - vscode.window.showInformationMessage(message); - } + showToast: IDE["showToast"] = async (...params) => { + const [type, message, ...otherParams] = params; + const { showErrorMessage, showWarningMessage, showInformationMessage } = + vscode.window; - async errorPopup(message: string): Promise { - vscode.window.showErrorMessage(message); - } + switch (type) { + case "error": + return showErrorMessage(message, "Show logs").then((selection) => { + if (selection === "Show logs") { + vscode.commands.executeCommand("workbench.action.toggleDevTools"); + } + }); + case "info": + return showInformationMessage(message, ...otherParams); + case "warning": + return showWarningMessage(message, ...otherParams); + } + }; async getRepoName(dir: string): Promise { const repo = await this.getRepo(vscode.Uri.file(dir)); diff --git a/extensions/vscode/src/debug/debug.ts b/extensions/vscode/src/debug/debug.ts index d4f12ea5a..0671df7d5 100644 --- a/extensions/vscode/src/debug/debug.ts +++ b/extensions/vscode/src/debug/debug.ts @@ -1,5 +1,5 @@ import * as vscode from "vscode"; -import type { VsCodeIde } from "../ideProtocol"; +import type { VsCodeIde } from "../VsCodeIde"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; export const threadStopped: Map = new Map(); diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 8323a0d6f..049d50742 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -18,7 +18,7 @@ import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvide import { registerDebugTracker } from "../debug/debug"; import { DiffManager } from "../diff/horizontal"; import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager"; -import { VsCodeIde } from "../ideProtocol"; +import { VsCodeIde } from "../VsCodeIde"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; import { QuickEdit } from "../quickEdit/QuickEditQuickPick"; import { setupRemoteConfigSync } from "../stubs/activation"; @@ -233,6 +233,7 @@ export class VsCodeExtension { "showConfigUpdateToast", true, ); + if (showToast) { vscode.window .showInformationMessage("Config updated", "Don't show again") diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index a51bd8233..a1bb9e109 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -17,7 +17,7 @@ import * as fs from "node:fs"; import * as path from "node:path"; import * as vscode from "vscode"; import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager"; -import { VsCodeIde } from "../ideProtocol"; +import { VsCodeIde } from "../VsCodeIde"; import { getControlPlaneSessionInfo, WorkOsAuthProvider, @@ -282,18 +282,8 @@ export class VsCodeMessenger { const { filepath, startLine, endLine } = msg.data; return ide.showLines(filepath, startLine, endLine); }); - // Other - this.onWebviewOrCore("errorPopup", (msg) => { - vscode.window - .showErrorMessage(msg.data.message, "Show Logs") - .then((selection) => { - if (selection === "Show Logs") { - vscode.commands.executeCommand("workbench.action.toggleDevTools"); - } - }); - }); - this.onWebviewOrCore("infoPopup", (msg) => { - vscode.window.showInformationMessage(msg.data.message); + this.onWebviewOrCore("showToast", (msg) => { + this.ide.showToast(...msg.data); }); this.onWebviewOrCore("getGitHubAuthToken", (msg) => ide.getGitHubAuthToken(), diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index 58f6696c7..6b8c4d6db 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -312,7 +312,7 @@ export class QuickEdit { const modelTitle = await this.getCurModelTitle(); if (!modelTitle) { - this.ide.infoPopup("Please configure a model to use Quick Edit"); + this.ide.showToast("info", "Please configure a model to use Quick Edit"); return undefined; } diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 15f79ddfd..0717ad39f 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -1,4 +1,4 @@ -import type { FileEdit, RangeInFile, Thread } from "core"; +import type { FileEdit, RangeInFile, Thread, ToastType } from "core"; import path from "node:path"; import * as vscode from "vscode"; import { threadStopped } from "../debug/debug"; diff --git a/gui/src/components/ProfileSwitcher.tsx b/gui/src/components/ProfileSwitcher.tsx index 4ffa1f085..44ba57b42 100644 --- a/gui/src/components/ProfileSwitcher.tsx +++ b/gui/src/components/ProfileSwitcher.tsx @@ -146,7 +146,7 @@ function ProfileSwitcher(props: {}) { !lastControlServerBetaEnabledStatus && enableControlServerBeta; if (shouldShowPopup) { - ideMessenger.ide.infoPopup("Continue for Teams enabled"); + ideMessenger.ide.showToast("info", "Continue for Teams enabled"); } setControlServerBetaEnabled(enableControlServerBeta); diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 4cb6fb1fa..ef622240d 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -245,10 +245,10 @@ function TipTapEditor(props: TipTapEditorProps) { }; }); } else { - ideMessenger.post("errorPopup", { - message: - "Images need to be in jpg or png format and less than 10MB in size.", - }); + ideMessenger.post("showToast", [ + "error", + "Images need to be in jpg or png format and less than 10MB in size.", + ]); } return undefined; } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index fa7e01945..34bcdafa5 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -282,10 +282,11 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { ); } } catch (e: any) { - console.log("Continue: error streaming response: ", e); - ideMessenger.post("errorPopup", { - message: `Error streaming response: ${e.message}`, - }); + console.debug("Error streaming response: ", e); + ideMessenger.post("showToast", [ + "error", + `Error streaming response: ${e.message}`, + ]); } finally { dispatch(setInactive()); }