diff --git a/.changes/unreleased/Added-20240130-123143.yaml b/.changes/unreleased/Added-20240130-123143.yaml new file mode 100644 index 000000000..419c65e6b --- /dev/null +++ b/.changes/unreleased/Added-20240130-123143.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Docs context provider +time: 2024-01-30T12:31:43.521306-08:00 diff --git "a/Icon\r" "b/Icon\r" new file mode 100644 index 000000000..e69de29bb diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 3875dd3a0..803628f0c 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -36,13 +36,15 @@ class DocsContextProvider extends BaseContextProvider { return [ ...chunks .map((chunk) => ({ - name: chunk.filepath - .split("/") - .slice(1) - .join("/") - .split("/tree/main/") - .slice(1) - .join("/"), // chunk.otherMetadata?.title || chunk.filepath, + name: chunk.filepath.includes("/tree/main") // For display of GitHub files + ? chunk.filepath + .split("/") + .slice(1) + .join("/") + .split("/tree/main/") + .slice(1) + .join("/") + : chunk.otherMetadata?.title || chunk.filepath, description: new URL(chunk.filepath, query).toString(), content: chunk.content, })) diff --git a/core/indexing/chunk/markdown.ts b/core/indexing/chunk/markdown.ts index 0ca92158c..0e0901cf0 100644 --- a/core/indexing/chunk/markdown.ts +++ b/core/indexing/chunk/markdown.ts @@ -58,14 +58,29 @@ export async function* markdownChunker( hLevel: number ): AsyncGenerator { if (countTokens(content, "gpt-4") <= maxChunkSize) { + const header = findHeader(content.split("\n")); yield { content, startLine: 0, endLine: content.split("\n").length, + otherMetadata: { + fragment: cleanFragment(header), + title: cleanHeader(header), + }, }; return; } else if (hLevel > 4) { - yield* basicChunker(content, maxChunkSize); + const header = findHeader(content.split("\n")); + + for (const chunk of basicChunker(content, maxChunkSize)) { + yield { + ...chunk, + otherMetadata: { + fragment: cleanFragment(header), + title: cleanHeader(header), + }, + }; + } return; } diff --git a/core/indexing/docs/crawl.ts b/core/indexing/docs/crawl.ts index 13b86c807..0152005f2 100644 --- a/core/indexing/docs/crawl.ts +++ b/core/indexing/docs/crawl.ts @@ -43,11 +43,16 @@ function shouldFilterPath(pathname: string, baseUrl: URL): boolean { return false; } -async function crawlLinks(path: string, baseUrl: URL, visited: Set) { +async function* crawlLinks( + path: string, + baseUrl: URL, + visited: Set +): AsyncGenerator { if (visited.has(path) || shouldFilterPath(path, baseUrl)) { return; } visited.add(path); + yield visited.size; const response = await fetch(new URL(path, baseUrl)); const text = await response.text(); @@ -71,8 +76,12 @@ async function crawlLinks(path: string, baseUrl: URL, visited: Set) { }); await Promise.all( - children.map((child) => crawlLinks(child, baseUrl, visited)) + children.map(async (child) => { + for await (const _ of crawlLinks(child, baseUrl, visited)) { + } + }) ); + yield visited.size; } async function crawlGithubRepo(baseUrl: URL) { @@ -116,25 +125,44 @@ async function crawlGithubRepo(baseUrl: URL) { return paths; } -export async function crawlSubpages(baseUrl: URL) { +export async function* crawlSubpages( + baseUrl: URL +): AsyncGenerator { // Special case for GitHub repos if (baseUrl.hostname === "github.com") { return crawlGithubRepo(baseUrl); } // First, check if the parent of the path redirects to the same page - const parentUrl = new URL(baseUrl); - parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/"); - const response = await fetch(parentUrl); - - let useParent = response.url === baseUrl.toString(); + if (baseUrl.pathname.endsWith("/")) { + baseUrl.pathname = baseUrl.pathname.slice(0, -1); + } + let realBaseUrl = new URL(baseUrl); + while (true) { + let parentUrl = new URL(realBaseUrl); + parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/"); + if ( + parentUrl.pathname === realBaseUrl.pathname || + parentUrl.pathname === "" + ) { + break; + } + const response = await fetch(parentUrl); + const redirected = response.url.toString() === baseUrl.toString() + "/"; + if (!redirected) { + break; + } + realBaseUrl = parentUrl; + } const visited = new Set(); - await crawlLinks( - (useParent ? parentUrl.pathname : baseUrl.pathname) || "/", - baseUrl, + for await (const count of crawlLinks( + realBaseUrl.pathname || "/", + realBaseUrl, visited - ); + )) { + yield count; + } return [...visited]; } diff --git a/core/indexing/docs/db.ts b/core/indexing/docs/db.ts index 760fc0f87..21a23d827 100644 --- a/core/indexing/docs/db.ts +++ b/core/indexing/docs/db.ts @@ -22,7 +22,7 @@ async function createDocsTable(db: Database) { db.exec(`CREATE TABLE IF NOT EXISTS docs ( id INTEGER PRIMARY KEY AUTOINCREMENT, title STRING NOT NULL, - baseUrl STRING NOT NULL + baseUrl STRING NOT NULL UNIQUE )`); } diff --git a/core/indexing/docs/index.ts b/core/indexing/docs/index.ts index 7b147dcdd..5c2ade9ac 100644 --- a/core/indexing/docs/index.ts +++ b/core/indexing/docs/index.ts @@ -16,7 +16,7 @@ export async function* indexDocs( embeddingsProvider: EmbeddingsProvider ): AsyncGenerator { const existingDocs = await listDocs(); - if (existingDocs.find((doc) => doc.title === title)) { + if (existingDocs.find((doc) => doc.baseUrl === baseUrl.toString())) { yield { progress: 1, desc: "Already indexed", @@ -29,8 +29,23 @@ export async function* indexDocs( desc: "Finding subpages", }; - let subpaths = await crawlSubpages(baseUrl); - console.log("Found subpaths", subpaths); + const subpathGenerator = crawlSubpages(baseUrl); + let { value, done } = await subpathGenerator.next(); + while (true) { + if (done) { + break; + } + yield { + progress: 0, + desc: `Finding subpages (${value})`, + }; + const next = await subpathGenerator.next(); + value = next.value; + done = next.done; + } + + let subpaths = value as string[]; + const chunks: Chunk[] = []; const embeddings: number[][] = []; @@ -53,7 +68,7 @@ export async function* indexDocs( for (let i = 0; i < subpaths.length; i++) { const subpath = subpaths[i]; yield { - progress: 1 / (subpaths.length + 1), + progress: Math.max(1, Math.floor(100 / (subpaths.length + 1))), desc: `${subpath}`, }; @@ -75,6 +90,7 @@ export async function* indexDocs( (chunk.otherMetadata?.fragment ? `#${chunk.otherMetadata.fragment}` : ""), + otherMetadata: chunk.otherMetadata, index, digest: subpath, }); diff --git a/docs/docs/customization/context-providers.md b/docs/docs/customization/context-providers.md index a8c0d5ea2..692035656 100644 --- a/docs/docs/customization/context-providers.md +++ b/docs/docs/customization/context-providers.md @@ -32,6 +32,14 @@ Type '@terminal' to reference the contents of your IDE's terminal. { "name": "terminal" } ``` +### Documentation + +Type `@docs` to index and retrieve snippets from any documentation site. You can add any site by selecting "Add Docs" in the dropdown, then entering the root URL of the documentation site and a title to remember it by. After the site has been indexed, you can type `@docs`, select your documentation from the dropdown, and Continue will use similarity search to automatically find important sections when answering your question. + +```json +{ "name": "docs" } +``` + ### Open Files Type '@open' to reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files. diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 9976e7abd..86aadd082 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -968,6 +968,7 @@ "problems", "folder", "issue", + "docs", "tree" ], "markdownEnumDescriptions": [ @@ -982,6 +983,7 @@ "Include important files from a folder in the prompt, as determined by similarity search", "Reference GitHub issues from a repository", "Retrieve important pages from a documentation website, as determined by similarity search", + "Index and retrieve the contents of any documentation site, using embeddings to find important snippets", "Display a file tree of the current workspace" ], "type": "string" diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 9976e7abd..86aadd082 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -968,6 +968,7 @@ "problems", "folder", "issue", + "docs", "tree" ], "markdownEnumDescriptions": [ @@ -982,6 +983,7 @@ "Include important files from a folder in the prompt, as determined by similarity search", "Reference GitHub issues from a repository", "Retrieve important pages from a documentation website, as determined by similarity search", + "Index and retrieve the contents of any documentation site, using embeddings to find important snippets", "Display a file tree of the current workspace" ], "type": "string" diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index 90276bafb..9e8c80bbd 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -674,7 +674,7 @@ export function getSidebarContent( embeddingsProvider )) { progress.report({ - increment: update.progress * 100, + increment: update.progress, message: update.desc, }); } @@ -682,6 +682,10 @@ export function getSidebarContent( vscode.window.showInformationMessage( `🎉 Successfully indexed ${title}` ); + + debugPanelWebview?.postMessage({ + type: "refreshSubmenuItems", + }); } ); break; diff --git a/extensions/vscode/src/util/indexCodebase.ts b/extensions/vscode/src/util/indexCodebase.ts index 8b21cbcd1..90d1697ee 100644 --- a/extensions/vscode/src/util/indexCodebase.ts +++ b/extensions/vscode/src/util/indexCodebase.ts @@ -71,8 +71,6 @@ export async function vsCodeIndexCodebase(workspaceDirs: string[]) { (filepath) => ideProtocolClient.readFile(filepath) ); - console.log("RESULTS: ", codebaseIndex.artifactId, results); - for await (let { progress, desc } of codebaseIndex.update( tag, results, diff --git a/gui/src/App.tsx b/gui/src/App.tsx index d57d17642..0ad8260cc 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -66,19 +66,28 @@ const router = createMemoryRouter([ }, ]); -export const SubmenuContextProvidersContext = createContext< - (providerTitle: string | undefined, query: string) => ContextSubmenuItem[] ->(() => []); +export const SubmenuContextProvidersContext = createContext<{ + getSubmenuContextItems: ( + providerTitle: string | undefined, + query: string + ) => ContextSubmenuItem[]; + addItem: (providerTitle: string, item: ContextSubmenuItem) => void; +}>({ + getSubmenuContextItems: () => [], + addItem: () => {}, +}); function App() { const dispatch = useDispatch(); useSetup(dispatch); - const { getSubmenuContextItems } = useSubmenuContextProviders(); + const submenuContextProvidersMethods = useSubmenuContextProviders(); return ( - + ); diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 3b342de2c..54a158078 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -1,9 +1,10 @@ import { postToIde } from "core/ide/messaging"; -import React, { useLayoutEffect } from "react"; +import { usePostHog } from "posthog-js/react"; +import React, { useContext, useLayoutEffect } from "react"; import { useDispatch } from "react-redux"; import styled from "styled-components"; import { Button, Input } from ".."; -import useSubmenuContextProviders from "../../hooks/useSubmenuContextProviders"; +import { SubmenuContextProvidersContext } from "../../App"; import { setShowDialog } from "../../redux/slices/uiStateSlice"; const GridDiv = styled.div` @@ -19,14 +20,17 @@ function AddDocsDialog() { const [urlValid, setUrlValid] = React.useState(false); const dispatch = useDispatch(); - const { addItem } = useSubmenuContextProviders(); + const { addItem } = useContext(SubmenuContextProvidersContext); const ref = React.useRef(null); + const posthog = usePostHog(); useLayoutEffect(() => { - if (ref.current) { - ref.current.focus(); - } + setTimeout(() => { + if (ref.current) { + ref.current.focus(); + } + }, 100); }, [ref]); return ( @@ -63,6 +67,7 @@ function AddDocsDialog() { title: docsTitle, description: new URL(docsUrl).hostname, }); + posthog.capture("add_docs", { url: docsUrl }); }} > Done diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index deb8fa03c..4827b8960 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -123,7 +123,7 @@ interface TipTapEditorProps { function TipTapEditor(props: TipTapEditorProps) { const dispatch = useDispatch(); - const getSubmenuContextItems = useContext(SubmenuContextProvidersContext); + const { getSubmenuContextItems } = useContext(SubmenuContextProvidersContext); const historyLength = useSelector( (store: RootStore) => store.state.history.length diff --git a/gui/src/hooks/useSubmenuContextProviders.tsx b/gui/src/hooks/useSubmenuContextProviders.tsx index c059f6ee2..1896379e4 100644 --- a/gui/src/hooks/useSubmenuContextProviders.tsx +++ b/gui/src/hooks/useSubmenuContextProviders.tsx @@ -43,6 +43,19 @@ function useSubmenuContextProviders() { }); } + useEffect(() => { + const handler = (e) => { + if (e.data.type !== "refreshSubmenuItems") { + return; + } + setLoaded(false); + }; + window.addEventListener("message", handler); + return () => { + window.removeEventListener("message", handler); + }; + }, []); + function addItem(providerTitle: string, item: ContextSubmenuItem) { console.log("Adding item", item, providerTitle, Object.keys(minisearches)); if (!minisearches[providerTitle]) {