diff --git a/core/commands/util.ts b/core/commands/util.ts index 207b6c5ec..931564839 100644 --- a/core/commands/util.ts +++ b/core/commands/util.ts @@ -1,4 +1,4 @@ -import { ContextItemWithId } from "../index.js"; +import { ContextItemWithId } from "../"; export interface RangeInFileWithContents { filepath: string; @@ -15,7 +15,7 @@ export function contextItemToRangeInFileWithContents( const lines = item.name.split("(")[1].split(")")[0].split("-"); const rif: RangeInFileWithContents = { - filepath: item.id.itemId, + filepath: item.uri?.value || "", range: { start: { line: Number.parseInt(lines[0]), diff --git a/core/config/default.ts b/core/config/default.ts index af5b19913..1224725cc 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -23,7 +23,9 @@ export const FREE_TRIAL_MODELS: ModelDescription[] = [ { title: "Claude 3 Sonnet (Free Trial)", provider: "free-trial", - model: "claude-3-sonnet-20240229", + model: "claude-3-5-sonnet-20240620", + systemMessage: + "You are an expert software developer. You give helpful and concise responses.", }, { title: "GPT-4o (Free Trial)", @@ -35,14 +37,16 @@ export const FREE_TRIAL_MODELS: ModelDescription[] = [ { title: "Llama3 70b (Free Trial)", provider: "free-trial", - model: "llama3-70b", + model: "llama3.1-70b", systemMessage: - "You are an expert software developer. You give helpful and concise responses. Whenever you write a code block you include the language after the opening ticks.", + "You are an expert software developer. You give helpful and concise responses.", }, { title: "Codestral (Free Trial)", provider: "free-trial", - model: "codestral", + model: "codestral-latest", + systemMessage: + "You are an expert software developer. You give helpful and concise responses.", }, ]; diff --git a/core/context/providers/CurrentFileContextProvider.ts b/core/context/providers/CurrentFileContextProvider.ts index e149c8079..575350b49 100644 --- a/core/context/providers/CurrentFileContextProvider.ts +++ b/core/context/providers/CurrentFileContextProvider.ts @@ -2,9 +2,9 @@ import { ContextItem, ContextProviderDescription, ContextProviderExtras, -} from "../../index.js"; -import { getBasename } from "../../util/index.js"; -import { BaseContextProvider } from "../index.js"; +} from "../../"; +import { getBasename } from "../../util/"; +import { BaseContextProvider } from "../"; class CurrentFileContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -32,6 +32,10 @@ class CurrentFileContextProvider extends BaseContextProvider { currentFile, )}\n${contents}\n\`\`\``, name: getBasename(currentFile), + uri: { + type: "file", + value: currentFile, + }, }, ]; } diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index e9ae11bde..f54692c47 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -91,7 +91,7 @@ class DocsContextProvider extends BaseContextProvider { await docsService.isJetBrainsAndPreIndexedDocsProvider(); if (isJetBrainsAndPreIndexedDocsProvider) { - extras.ide.showToast( + await extras.ide.showToast( "error", `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + "the embeddings provider, but it cannot be used with JetBrains. " + @@ -105,7 +105,7 @@ class DocsContextProvider extends BaseContextProvider { const preIndexedDoc = preIndexedDocs[query]; if (!!preIndexedDoc) { - Telemetry.capture("docs_pre_indexed_doc_used", { + void Telemetry.capture("docs_pre_indexed_doc_used", { doc: preIndexedDoc["title"], }); } @@ -147,6 +147,10 @@ class DocsContextProvider extends BaseContextProvider { : chunk.otherMetadata?.title || chunk.filepath, description: chunk.filepath, content: chunk.content, + uri: { + type: "url" as const, + value: chunk.filepath, + }, })) .reverse(), { diff --git a/core/context/providers/FileContextProvider.ts b/core/context/providers/FileContextProvider.ts index ef0bfeb54..be558c651 100644 --- a/core/context/providers/FileContextProvider.ts +++ b/core/context/providers/FileContextProvider.ts @@ -36,6 +36,10 @@ class FileContextProvider extends BaseContextProvider { name: query.split(/[\\/]/).pop() ?? query, description: query, content: `\`\`\`${query}\n${content}\n\`\`\``, + uri: { + type: "file", + value: query, + }, }, ]; } diff --git a/core/context/providers/OpenFilesContextProvider.ts b/core/context/providers/OpenFilesContextProvider.ts index b0c85bc2e..c00121a96 100644 --- a/core/context/providers/OpenFilesContextProvider.ts +++ b/core/context/providers/OpenFilesContextProvider.ts @@ -28,10 +28,15 @@ class OpenFilesContextProvider extends BaseContextProvider { openFiles.map(async (filepath: string) => { return { description: filepath, - content: `\`\`\`${await getRelativePath(filepath, workspaceDirs)}\n${await ide.readFile( + content: `\`\`\`${await getRelativePath( filepath, - )}\n\`\`\``, + workspaceDirs, + )}\n${await ide.readFile(filepath)}\n\`\`\``, name: (filepath.split("/").pop() ?? "").split("\\").pop() ?? "", + uri: { + type: "file", + value: filepath, + }, }; }), ); diff --git a/core/context/providers/URLContextProvider.ts b/core/context/providers/URLContextProvider.ts index 2e864fbb9..b0f4bd9ce 100644 --- a/core/context/providers/URLContextProvider.ts +++ b/core/context/providers/URLContextProvider.ts @@ -1,12 +1,13 @@ import { Readability } from "@mozilla/readability"; import { JSDOM } from "jsdom"; import { NodeHtmlMarkdown } from "node-html-markdown"; -import { BaseContextProvider } from "../index.js"; +import { BaseContextProvider } from "../"; import { ContextItem, ContextProviderDescription, ContextProviderExtras, } from "../../index.js"; +import { fetchFavicon } from "../../util/fetchFavicon"; class URLContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -22,6 +23,7 @@ class URLContextProvider extends BaseContextProvider { ): Promise { try { const url = new URL(query); + const icon = await fetchFavicon(url); const resp = await extras.fetch(url); const html = await resp.text(); @@ -37,11 +39,17 @@ class URLContextProvider extends BaseContextProvider { ); const title = article?.title || url.pathname; + return [ { - description: title, + icon, + description: url.toString(), content: markdown, name: title, + uri: { + type: "url", + value: url.toString(), + }, }, ]; } catch (e) { diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 1b250e548..9d19a33f7 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -6,6 +6,7 @@ import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline"; import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline"; import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline"; +import path from "path"; export async function retrieveContextItemsFromEmbeddings( extras: ContextProviderExtras, @@ -94,21 +95,32 @@ export async function retrieveContextItemsFromEmbeddings( } return [ - ...results.map((r) => { - const name = `${getRelativePath(r.filepath, workspaceDirs)} (${ - r.startLine - }-${r.endLine})`; - const description = `${r.filepath} (${r.startLine}-${r.endLine})`; - return { - name, - description, - content: `\`\`\`${name}\n${r.content}\n\`\`\``, - }; - }), { ...INSTRUCTIONS_BASE_ITEM, content: "Use the above code to answer the following question. You should not reference any files outside of what is shown, unless they are commonly known files, like a .gitignore or package.json. Reference the filenames whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more.", }, + ...results + .sort((a, b) => a.filepath.localeCompare(b.filepath)) + .map((r) => { + const name = `${path.basename(r.filepath)} (${r.startLine}-${ + r.endLine + })`; + const description = `${r.filepath}`; + + if (r.filepath.includes("package.json")) { + console.log(); + } + + return { + name, + description, + content: `\`\`\`${name}\n${r.content}\n\`\`\``, + uri: { + type: "file" as const, + value: r.filepath, + }, + }; + }), ]; } diff --git a/core/index.d.ts b/core/index.d.ts index 16c48a3ad..659f9f80c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -271,6 +271,13 @@ export interface ContextItemId { itemId: string; } +export type ContextItemUriTypes = "file" | "url"; + +export interface ContextItemUri { + type: ContextItemUriTypes; + value: string; +} + export interface ContextItem { content: string; name: string; @@ -278,16 +285,11 @@ export interface ContextItem { editing?: boolean; editable?: boolean; icon?: string; + uri?: ContextItemUri; } -export interface ContextItemWithId { - content: string; - name: string; - description: string; +export interface ContextItemWithId extends ContextItem { id: ContextItemId; - editing?: boolean; - editable?: boolean; - icon?: string; } export interface InputModifiers { diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 6a02babd4..a8b41cafe 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -341,6 +341,10 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { name: row.title, description: getLastNPathParts(row.path, 2), content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``, + uri: { + type: "file", + value: row.path, + }, }; } diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 75e633733..30e205c3b 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -32,6 +32,7 @@ import { SiteIndexingResults, } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; +import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon"; // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { @@ -154,7 +155,10 @@ export default class DocsService { params: {}, }); - this.ide.showToast("info", "Successfuly added docs context provider"); + await this.ide.showToast( + "info", + "Successfuly added docs context provider", + ); } return res === actionMsg; @@ -177,7 +181,7 @@ export default class DocsService { while (!(await generator.next()).done) {} } - this.ide.showToast("info", "Docs indexing completed"); + await this.ide.showToast("info", "Docs indexing completed"); } async list() { @@ -250,7 +254,7 @@ export default class DocsService { } } - Telemetry.capture("docs_pages_crawled", { + void Telemetry.capture("docs_pages_crawled", { count: processedPages, }); @@ -321,7 +325,7 @@ export default class DocsService { await this.delete(startUrl); } - const favicon = await this.fetchFavicon(siteIndexingConfig); + const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); await this.add({ siteIndexingConfig, @@ -460,7 +464,7 @@ export default class DocsService { for (const doc of newDocs) { console.log(`Indexing new doc: ${doc.startUrl}`); - Telemetry.capture("add_docs_config", { url: doc.startUrl }); + void Telemetry.capture("add_docs_config", { url: doc.startUrl }); const generator = this.indexAndAdd(doc); while (!(await generator.next()).done) {} @@ -537,8 +541,9 @@ export default class DocsService { private async getLanceTableNameFromEmbeddingsProvider( isPreIndexedDoc: boolean, ) { - const embeddingsProvider = - await this.getEmbeddingsProvider(isPreIndexedDoc); + const embeddingsProvider = await this.getEmbeddingsProvider( + isPreIndexedDoc, + ); const embeddingsProviderId = this.removeInvalidLanceTableNameChars( embeddingsProvider.id, ); @@ -694,7 +699,12 @@ export default class DocsService { const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; const startUrl = new URL(siteEmbeddings.url).toString(); - const favicon = await this.fetchFavicon(preIndexedDocs[startUrl]); + + const faviconUrl = preIndexedDocs[startUrl].faviconUrl; + const favicon = + typeof faviconUrl === "string" + ? await getFaviconBase64(faviconUrl) + : undefined; await this.add({ favicon, @@ -707,30 +717,6 @@ export default class DocsService { }); } - private async fetchFavicon(siteIndexingConfig: SiteIndexingConfig) { - const faviconUrl = - siteIndexingConfig.faviconUrl ?? - new URL("/favicon.ico", siteIndexingConfig.startUrl); - - try { - const response = await fetch(faviconUrl); - const arrayBuffer = await response.arrayBuffer(); - const base64 = btoa( - new Uint8Array(arrayBuffer).reduce( - (data, byte) => data + String.fromCharCode(byte), - "", - ), - ); - const mimeType = response.headers.get("content-type") || "image/x-icon"; - - return `data:${mimeType};base64,${base64}`; - } catch { - console.error(`Failed to fetch favicon: ${faviconUrl}`); - } - - return undefined; - } - private async shouldReindexDocsOnNewEmbeddingsProvider( curEmbeddingsProviderId: EmbeddingsProvider["id"], ): Promise { diff --git a/core/util/fetchFavicon.ts b/core/util/fetchFavicon.ts new file mode 100644 index 000000000..8b1c8616a --- /dev/null +++ b/core/util/fetchFavicon.ts @@ -0,0 +1,65 @@ +import { JSDOM } from "jsdom"; + +export async function findFaviconPath(url: URL): Promise { + const baseUrl = `${url.protocol}//${url.hostname}`; + + try { + const response = await fetch(baseUrl); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const html = await response.text(); + const dom = new JSDOM(html); + const document = dom.window.document; + + // Look for favicon in tags + const linkTags = document.querySelectorAll('link[rel*="icon"]'); + + for (const link of linkTags) { + const href = link.getAttribute("href"); + if (href) { + return new URL(href, baseUrl).toString(); + } + } + } catch (error) { + console.debug(`Failed to fetch favicon for ${baseUrl}: ${error}`); + } + + console.debug(`Failed to find favicon for ${baseUrl}`); + return undefined; +} + +export async function getFaviconBase64( + faviconUrl: string, +): Promise { + try { + const response = await fetch(faviconUrl); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const arrayBuffer = await response.arrayBuffer(); + const base64 = btoa( + new Uint8Array(arrayBuffer).reduce( + (data, byte) => data + String.fromCharCode(byte), + "", + ), + ); + const mimeType = response.headers.get("content-type") || "image/x-icon"; + + return `data:${mimeType};base64,${base64}`; + } catch (error) { + console.debug(`Failed to fetch favicon from ${faviconUrl}: ${error}`); + return undefined; + } +} + +export async function fetchFavicon(url: URL): Promise { + const faviconPath = await findFaviconPath(url); + if (faviconPath) { + return getFaviconBase64(faviconPath); + } + return undefined; +} diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index 251ff7b1c..aba23e14a 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -9,7 +9,6 @@ import { useOnboardingCard } from "./hooks/useOnboardingCard"; const StyledCard = styled.div` margin: auto; border-radius: ${defaultBorderRadius}; - padding: 1rem 1.5rem; background-color: ${vscInputBackground}; box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1); @@ -43,13 +42,13 @@ export function OnboardingCard(props: OnboardingCardProps) { } return ( - + - +
{renderTabContent()}
diff --git a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx index ee061e1f9..f38fbaccd 100644 --- a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx +++ b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx @@ -65,13 +65,13 @@ function BestExperienceConfigForm({
{chatModel.title}{" "} - by Anthropic + by Anthropic
@@ -99,13 +99,13 @@ function BestExperienceConfigForm({
{autocompleteModel.title}{" "} - by Mistral + by Mistral
@@ -129,7 +129,7 @@ function BestExperienceConfigForm({ -
+
diff --git a/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx b/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx index ee3eb942c..44c5c5caa 100644 --- a/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx @@ -7,7 +7,7 @@ interface OllamaCompletedStepProps { function OllamaCompletedStep({ text }: OllamaCompletedStepProps) { return (
-

{text}

+

{text}

); diff --git a/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx index 37831a70f..721807c6a 100644 --- a/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx @@ -35,7 +35,7 @@ function OllamaModelDownload({ ) : ( <> -

{command}

+

{command}

{tooltipPortalDiv && diff --git a/gui/src/components/OnboardingCard/components/OllamaStatus.tsx b/gui/src/components/OnboardingCard/components/OllamaStatus.tsx index 9cc323ec6..39bd7978c 100644 --- a/gui/src/components/OnboardingCard/components/OllamaStatus.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaStatus.tsx @@ -35,14 +35,14 @@ export function OllamaStatus({ isOllamaConnected }: OllamaStatusProps) { case OllamaConnectionStatuses.WaitingToDownload: return ( -

{downloadUrl}

+

{downloadUrl}

); case OllamaConnectionStatuses.Downloading: return (
-

+

Checking for connection to Ollama at http://localhost:11434

diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx index 7e7fcdcee..d44524cb5 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx @@ -9,23 +9,39 @@ interface OnboardingCardTabsProps { export type TabTitle = "Quickstart" | "Best" | "Local"; -export const TabTitles: { [k in TabTitle]: { xs: string; default: string } } = { +export const TabTitles: { [k in TabTitle]: { md: string; default: string } } = { Quickstart: { - xs: "Quickstart", + md: "Quickstart", default: "Quickstart", }, Best: { - xs: "Best", + md: "Best", default: "Best experience", }, Local: { - xs: "Local", + md: "Local", default: "Local with Ollama", }, }; +const StyledSelect = styled.select` + width: 100%; + padding: 0.5rem; + background-color: transparent; + color: ${vscForeground}; + border: none; + border-bottom: 1px solid ${vscForeground}; + border-radius: 0; + font-size: 1rem; + cursor: pointer; + display: block; + + &:focus { + outline: none; + } +`; + const TabButton = styled.button<{ isActive: boolean }>` - padding: 1rem 1rem 0.5rem 1rem; margin-bottom: -1px; focus: outline-none; background: transparent; @@ -54,23 +70,48 @@ export function OnboardingCardTabs({ onTabClick, }: OnboardingCardTabsProps) { return ( - - {Object.entries(TabTitles).map(([tabType, titles]) => { - if (hasPassedFTL() && tabType === "Quickstart") { - return undefined; - } +
+
+ + {Object.entries(TabTitles).map(([tabType, titles]) => { + if (hasPassedFTL() && tabType === "Quickstart") { + return undefined; + } - return ( - onTabClick(tabType as TabTitle)} - > -

{titles.default}

-

{titles.xs}

-
- ); - })} -
+ return ( + onTabClick(tabType as TabTitle)} + > +

+ {titles.default} +

+

{titles.md}

+
+ ); + })} + +
+
+ onTabClick(e.target.value as TabTitle)} + > + {Object.entries(TabTitles).map(([tabType, titles]) => { + if (hasPassedFTL() && tabType === "Quickstart") { + return null; + } + + return ( + + ); + })} + +
+
); } diff --git a/gui/src/components/OnboardingCard/components/ProviderAlert.tsx b/gui/src/components/OnboardingCard/components/ProviderAlert.tsx index dd1e9f339..8c2c1ca6f 100644 --- a/gui/src/components/OnboardingCard/components/ProviderAlert.tsx +++ b/gui/src/components/OnboardingCard/components/ProviderAlert.tsx @@ -17,7 +17,7 @@ function ProviderAlert() { } return ( -
+

Prefer to use an different provider like OpenAI? diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx index 0f5e5f441..d5b372245 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx @@ -7,7 +7,9 @@ function OnboardingBestTab() { return (

- +
+ +
); diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx index f0eadf43b..ff77e18e8 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx @@ -3,18 +3,18 @@ import QuickStartSubmitButton from "../components/QuickStartSubmitButton"; function OnboardingQuickstartTab() { return ( -
-
-
+
+
+
-

+

Quickly get up and running using our API keys. After this trial, we'll help you set up your own models.

-

+

To prevent abuse, we'll ask you to sign in to GitHub.

diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx index 48f8cbc2a..9354a73b5 100644 --- a/gui/src/components/gui/StepContainer.tsx +++ b/gui/src/components/gui/StepContainer.tsx @@ -124,14 +124,14 @@ function StepContainer(props: StepContainerProps) { {(props.isLast || isHovered || typeof feedback !== "undefined") && !active && (
{props.modelTitle && ( - <> +
{props.modelTitle}
- +
)} {truncatedEarly && ( diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 3d3200433..5327719d2 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -1,14 +1,8 @@ -import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline"; +import { ChevronDownIcon, ChevronRightIcon } from "@heroicons/react/24/outline"; import { ContextItemWithId } from "core"; import { contextItemToRangeInFileWithContents } from "core/commands/util"; import React, { useContext } from "react"; -import styled from "styled-components"; -import { - defaultBorderRadius, - lightGray, - vscBackground, - vscForeground, -} from ".."; +import { lightGray, vscBackground } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { getFontSize } from "../../util"; import FileIcon from "../FileIcon"; @@ -16,70 +10,26 @@ import SafeImg from "../SafeImg"; import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils"; import { getIconFromDropdownItem } from "./MentionList"; -const ContextItemDiv = styled.div` - cursor: pointer; - padding: 6px 10px 6px 6px; - margin-left: 4px; - margin-right: 12px; - display: flex; - align-items: center; - border-radius: ${defaultBorderRadius}; - font-size: ${getFontSize()}; - max-width: 100%; - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; - - &:hover { - background-color: #fff1; - } -`; - -export const ContextItems = styled.span` - margin-left: 5px; - font-size: ${getFontSize() - 1}px; - color: ${lightGray}; - - &:hover { - text-decoration: underline; - } -`; - interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; } -function filterInstructionContextItem( - contextItems: ContextItemsPeekProps["contextItems"], -) { - return contextItems?.filter( - (ctxItem) => !ctxItem.name.includes(INSTRUCTIONS_BASE_ITEM.name), - ); +interface ContextItemsPeekItemProps { + contextItem: ContextItemWithId; } -const ContextItemsPeek = (props: ContextItemsPeekProps) => { +function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { const ideMessenger = useContext(IdeMessengerContext); - const [open, setOpen] = React.useState(false); + function openContextItem() { + const { uri, name, description, content } = contextItem; - const ctxItems = filterInstructionContextItem(props.contextItems); + if (uri?.type === "url") { + ideMessenger.post("openUrl", uri.value); + } else if (uri) { + const isRangeInFile = name.includes(" (") && name.endsWith(")"); - if (!ctxItems || ctxItems.length === 0) { - return null; - } - - const contextItemsText = `${ctxItems.length} context ${ - ctxItems.length > 1 ? "items" : "item" - }`; - - function openContextItem(contextItem: ContextItemWithId) { - if (contextItem.description.startsWith("http")) { - window.open(contextItem.description, "_blank"); - } else if ( - contextItem.description.startsWith("/") || - contextItem.description.startsWith("\\") - ) { - if (contextItem.name.includes(" (") && contextItem.name.endsWith(")")) { + if (isRangeInFile) { const rif = contextItemToRangeInFileWithContents(contextItem); ideMessenger.ide.showLines( rif.filepath, @@ -87,23 +37,23 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { rif.range.end.line, ); } else { - ideMessenger.ide.openFile(contextItem.description); + ideMessenger.ide.openFile(description); } } else { - ideMessenger.ide.showVirtualFile(contextItem.name, contextItem.content); + ideMessenger.ide.showVirtualFile(name, content); } } - const getContextItemIcon = (contextItem: ContextItemWithId) => { - const dimmensions = "1.4em"; + function getContextItemIcon() { + const dimensions = "18px"; if (contextItem.icon) { return ( ); @@ -114,13 +64,16 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { if (shouldShowFileIcon) { return ( - +
+ +
); } @@ -131,79 +84,99 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { return ( ); - }; + } return (
+
+ {getContextItemIcon()} +
+
+ {contextItem.name} +
+
+ {contextItem.description} +
+
+
+
+ ); +} + +function ContextItemsPeek({ contextItems }: ContextItemsPeekProps) { + const [open, setOpen] = React.useState(false); + + const ctxItems = contextItems?.filter( + (ctxItem) => !ctxItem.name.includes(INSTRUCTIONS_BASE_ITEM.name), + ); + + if (!ctxItems || ctxItems.length === 0) { + return null; + } + + const contextItemsText = `${ctxItems.length} context ${ + ctxItems.length > 1 ? "items" : "item" + }`; + + return ( +
setOpen((prev) => !prev)} > - {open ? ( - + - ) : ( + /> - )} - {contextItemsText} + /> +
+ + {contextItemsText} +
- {open && ( -
- {ctxItems?.map((contextItem, idx) => { - const contextItemContent = ( - openContextItem(contextItem)}> - {getContextItemIcon(contextItem)} - {contextItem.name} - - ); - - return contextItem.description.startsWith("http") ? ( - - {contextItemContent} - - ) : ( - {contextItemContent} - ); - })} -
- )} +
+ {ctxItems.map((contextItem, idx) => ( + + ))} +
); -}; +} export default ContextItemsPeek; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index a95a71502..e8bbd080a 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -1,6 +1,6 @@ import { + AtSymbolIcon, PhotoIcon as OutlinePhotoIcon, - PlusIcon, } from "@heroicons/react/24/outline"; import { PhotoIcon as SolidPhotoIcon } from "@heroicons/react/24/solid"; import { InputModifiers } from "core"; @@ -28,7 +28,6 @@ import ModelSelect from "../modelSelection/ModelSelect"; const StyledDiv = styled.div<{ isHidden: boolean }>` padding: 4px 0; - display: flex; justify-content: space-between; gap: 1px; background-color: ${vscInputBackground}; @@ -37,64 +36,47 @@ const StyledDiv = styled.div<{ isHidden: boolean }>` cursor: ${(props) => (props.isHidden ? "default" : "text")}; opacity: ${(props) => (props.isHidden ? 0 : 1)}; pointer-events: ${(props) => (props.isHidden ? "none" : "auto")}; - user-select: none; & > * { flex: 0 0 auto; } +`; - /* Hide the "Use codebase" span first */ - @media (max-width: 450px) { - & > span:last-child > span:nth-last-child(2) { - display: none; - } +const HoverItem = styled.span<{ isActive?: boolean }>` + padding: 0 4px; + padding-top: 2px; + padding-bottom: 2px; + cursor: pointer; + transition: color 200ms; + + &:hover { + color: #d1d5db; } `; -const SecondToDisappearContainer = styled.span` - display: flex; - align-items: center; - - @media (max-width: 350px) { - display: none; - } -`; - -const StyledSpan = styled.span` - font-size: ${() => `${getFontSize() - 2}px`}; - color: ${lightGray}; -`; - -const EnterButton = styled.div<{ offFocus: boolean }>` +const EnterButton = styled.div` padding: 2px 4px; display: flex; align-items: center; - - background-color: ${(props) => - props.offFocus ? undefined : lightGray + "33"}; + background-color: ${lightGray}33; border-radius: ${defaultBorderRadius}; color: ${vscForeground}; + cursor: pointer; &:hover { background-color: ${vscBadgeBackground}; color: ${vscBadgeForeground}; } - - cursor: pointer; `; interface InputToolbarProps { onEnter?: (modifiers: InputModifiers) => void; - usingCodebase?: boolean; onAddContextItem?: () => void; - onClick?: () => void; - onImageFileSelected?: (file: File) => void; - hidden?: boolean; - showNoContext: boolean; + activeKey: string | null; } function InputToolbar(props: InputToolbarProps) { @@ -104,26 +86,28 @@ function InputToolbar(props: InputToolbarProps) { const defaultModel = useSelector(defaultModelSelector); const useActiveFile = useSelector(selectUseActiveFile); + console.log(props.activeKey); + return ( <> - - - - - { - props.onAddContextItem(); - }} - className="hover:underline cursor-pointer" +
+
+ +
+
+ - Add Context{" "} - + {defaultModel && modelSupportsImages( defaultModel.provider, @@ -149,18 +133,14 @@ function InputToolbar(props: InputToolbarProps) { /> {fileSelectHovered ? ( { fileInputRef.current?.click(); }} /> ) : ( { fileInputRef.current?.click(); }} @@ -168,47 +148,40 @@ function InputToolbar(props: InputToolbarProps) { )} )} - - +
+
+ +
+
+ {props.activeKey === "Alt" ? ( + + {`${getAltKeyLabel()}⏎ + ${useActiveFile ? "No active file" : "Active file"}`} + + ) : ( + + props.onEnter({ + useCodebase: true, + noContext: !useActiveFile, + }) + } + > + + {" "} + {getMetaKeyLabel()}⏎ @codebase + + @codebase + + )} +
- - {props.showNoContext ? ( - - {getAltKeyLabel()} ⏎{" "} - {useActiveFile ? "No context" : "Use active file"} - - ) : ( - { - props.onEnter({ - useCodebase: true, - noContext: !useActiveFile, - }); - }} - className={"hover:underline cursor-pointer float-right"} - > - {getMetaKeyLabel()} ⏎ Use @codebase - - )} { props.onEnter({ useCodebase: isMetaEquivalentKeyPressed(e), @@ -216,9 +189,10 @@ function InputToolbar(props: InputToolbarProps) { }); }} > - ⏎ Enter + ⏎ Enter + ⏎ - +
); diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 2fc543907..21f0b3923 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -57,6 +57,7 @@ import { getSlashCommandDropdownOptions, } from "./getSuggestion"; import { ComboBoxItem } from "./types"; +import { v4 } from "uuid"; const InputBoxDiv = styled.div` resize: none; @@ -729,7 +730,11 @@ function TipTapEditor(props: TipTapEditorProps) { description: `${relativePath} ${rangeStr}`, id: { providerTitle: "code", - itemId: rif.filepath, + itemId: v4(), + }, + uri: { + type: "file", + value: rif.filepath, }, }; @@ -810,19 +815,15 @@ function TipTapEditor(props: TipTapEditorProps) { }; }, []); - const [optionKeyHeld, setOptionKeyHeld] = useState(false); + const [activeKey, setActiveKey] = useState(null); return ( { - if (e.key === "Alt") { - setOptionKeyHeld(true); - } + setActiveKey(e.key); }} onKeyUp={(e) => { - if (e.key === "Alt") { - setOptionKeyHeld(false); - } + setActiveKey(null); }} className="cursor-text" onClick={() => { @@ -874,7 +875,7 @@ function TipTapEditor(props: TipTapEditorProps) { }} />
) : ( diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index e1199b138..573d0544c 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -5,7 +5,7 @@ import { XMarkIcon, } from "@heroicons/react/24/outline"; import { ContextItemWithId } from "core"; -import { getMarkdownLanguageTagForFile } from "core/util"; +import { dedent, getMarkdownLanguageTagForFile } from "core/util"; import React, { useContext } from "react"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscEditorBackground } from ".."; @@ -66,18 +66,14 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { const [collapsed, setCollapsed] = React.useState(true); const [hovered, setHovered] = React.useState(false); + const content = dedent`${props.item.content}`; + const fence = React.useMemo(() => { - const backticks = props.item.content.match(backticksRegex); + const backticks = content.match(backticksRegex); return backticks ? backticks.sort().at(-1) + "`" : "```"; }, [props.item.content]); const codeBlockRef = React.useRef(null); - const codeBlockHeight = `${Math.min( - MAX_PREVIEW_HEIGHT, - codeBlockRef.current?.scrollHeight ?? - // Best estimate of height I currently could find - props.item.content.split("\n").length * 18 + 36, - )}px`; return (
{(codeBlockRef.current?.scrollHeight ?? 0) > MAX_PREVIEW_HEIGHT && ( {collapsed ? ( setCollapsed(false)} /> ) : ( setCollapsed(true)} /> )} diff --git a/gui/src/components/markdown/MonacoCodeBlock.tsx b/gui/src/components/markdown/MonacoCodeBlock.tsx deleted file mode 100644 index 2ad2d3e64..000000000 --- a/gui/src/components/markdown/MonacoCodeBlock.tsx +++ /dev/null @@ -1,281 +0,0 @@ -export {}; -// import { wireTmGrammars } from "monaco-editor-textmate"; -// import { Registry } from "monaco-textmate"; -// import { useEffect, useMemo, useRef } from "react"; -// import MonacoEditor, { monaco } from "react-monaco-editor"; -// import styled from "styled-components"; -// import { -// VSC_EDITOR_BACKGROUND_VAR, -// defaultBorderRadius, -// parseColorForHex, -// } from ".."; -// import { useAppendedString } from "../../hooks/useAppendedString"; -// import "./monaco.css"; - -// const fetchTextMateGrammar = async (lang: string): Promise => { -// return ( -// await fetch(`${(window as any).vscMediaUrl}/textmate-syntaxes/${lang}`) -// ).text(); -// }; - -// const supportedLanguages = { -// "source.ts": ["typescript", "TypeScript.tmLanguage.json"], -// "source.js": ["javascript", "JavaScript.tmLanguage.json"], -// "source.rust": ["rust", "rust.json"], -// // "source.batchfile": ["batchfile", "Batch File.tmLanguage"], -// "source.c": ["c", "c.json"], -// "source.cpp": ["cpp", "c++.json"], -// // "source.clojure": ["clojure", "Clojure.tmLanguage"], -// // "source.coffeescript": ["coffeescript", "coffeescript.json"], -// // "source.cshtml": ["cshtml", "cshtml.json"], -// // "source.css": ["css", "css.plist"], -// // "source.diff": ["diff", "diff.tmLanguage"], -// // "source.dockerfile": ["dockerfile", "Dockerfile.tmLanguage"], -// // "source.fsharp": ["fsharp", "fsharp.json"], -// // "source.git-commit": ["git-commit", "git-commit.tmLanguage"], -// // "source.git-rebase": ["git-rebase", "git-rebase.tmLanguage"], -// "source.go": ["go", "go.json"], -// // "source.groovy": ["groovy", "Groovy.tmLanguage"], -// // "source.handlebars": ["handlebars", "Handlebars.json"], -// // "source.html": ["html", "html.json"], -// // "source.jade": ["jade", "Jade.json"], -// // "source.java": ["java", "java.json"], -// // "source.javascript": ["javascript", "JavaScript.tmLanguage.json"], -// // // "source.json": ["json", "JSON.tmLanguage"], -// // "source.less": ["less", "less.tmLanguage.json"], -// // "source.lua": ["lua", "lua.json"], -// "source.python": ["python", "MagicPython.tmLanguage.json"], -// // "source.magicregexp": ["magicregexp", "MagicRegExp.tmLanguage.json"], -// // "source.makefile": ["makefile", "Makefile.json"], -// // // "source.markdown": ["markdown", "markdown.tmLanguage"], -// // // "source.objective-c": ["objective-c", "Objective-C.tmLanguage"], -// // // "source.perl6": ["perl6", "Perl 6.tmLanguage"], -// // // "source.perl": ["perl", "Perl.plist"], -// // "source.php": ["php", "php.json"], -// // // "source.platform": ["platform", "Platform.tmLanguage"], -// // // "source.powershell": ["powershell", "PowershellSyntax.tmLanguage"], -// // // "source.properties": ["properties", "properties.plist"], -// // // "source.r": ["r", "R.plist"], -// // // "source.regexp": ["regexp", "Regular Expressions (JavaScript).tmLanguage"], -// // // "source.ruby": ["ruby", "Ruby.plist"], -// // "source.scss": ["scss", "scss.json"], -// // "source.shaderlab": ["shaderlab", "shaderlab.json"], -// // "source.shell-unix-bash": [ -// // "shell-unix-bash", -// // "Shell-Unix-Bash.tmLanguage.json", -// // ], -// // // "source.sql": ["sql", "SQL.plist"], -// "source.swift": ["swift", "swift.json"], -// "source.tsx": ["tsx", "TypeScriptReact.tmLanguage.json"], -// // "source.xml": ["xml", "xml.json"], -// // "source.xsl": ["xsl", "xsl.json"], -// "source.yaml": ["yaml", "yaml.json"], -// }; - -// export const supportedLanguagesArray = Object.keys(supportedLanguages).map( -// (l) => supportedLanguages[l][0] -// ); - -// const registry = new Registry({ -// getGrammarDefinition: async (scopeName) => { -// if (scopeName in supportedLanguages) { -// const [_, tmFilename] = supportedLanguages[scopeName]; -// let content; -// try { -// content = await fetchTextMateGrammar(tmFilename); -// } catch (e) { -// console.warn("Error fetching grammar for language", scopeName, e); -// content = await fetchTextMateGrammar("TypeScript.tmLanguage.json"); -// } - -// return { -// format: "json", -// content, -// }; -// } else { -// return null; -// } -// }, -// }); - -// const getThemeFromWindow = () => { -// const colorTheme = (window as any).fullColorTheme; -// return { -// ...colorTheme, -// base: colorTheme.base || "vs-dark", -// inherit: true, -// encodedTokensColors: undefined, -// // rules: [], -// colors: { -// "editor.background": parseColorForHex(VSC_EDITOR_BACKGROUND_VAR), -// }, -// }; -// }; - -// const Container = styled.div<{ showBorder: 0 | 1 }>` -// border-radius: ${defaultBorderRadius}; -// overflow: hidden; -// margin: 0; -// `; - -// interface MonacoCodeBlockProps { -// codeString: string; -// preProps: any; -// language: string; -// showBorder: boolean; -// } - -// export const MonacoCodeBlock = (props: MonacoCodeBlockProps) => { -// const monacoRef = useRef(null); -// const editorRef = useRef(null); - -// /* THEMING */ - -// const liftOff = async (monaco) => { -// try { -// const grammars = new Map(); -// for (const [scopeName, [languageId, _]] of Object.entries( -// supportedLanguages -// )) { -// grammars.set(languageId, scopeName); -// monaco.languages.register({ id: languageId }); -// } -// await wireTmGrammars(monaco, registry, grammars, editorRef.current); -// } catch (e) { -// console.error("Error wiring grammars", e); -// } -// }; - -// const onEditorDidMount = ( -// editor: monaco.editor.IStandaloneCodeEditor, -// monaco: any -// ) => { -// monacoRef.current = monaco; -// editorRef.current = editor; - -// monacoRef.current.editor.defineTheme("custom-theme", getThemeFromWindow()); -// liftOff(monacoRef.current).then(() => { -// monacoRef.current.editor.setTheme("custom-theme"); -// }); - -// editorRef.current.onDidContentSizeChange(() => { -// editorRef.current.layout({ -// width: editorRef.current.getLayoutInfo().width, -// height: editorRef.current.getContentHeight(), -// }); -// }); -// }; - -// useEffect(() => { -// const listener = (e) => { -// if (e.data.type === "setTheme") { -// (window as any).fullColorTheme = e.data.theme; -// monacoRef.current.editor.defineTheme( -// "custom-theme", -// getThemeFromWindow() -// ); -// monacoRef.current.editor.setTheme("custom-theme"); -// } -// }; -// window.addEventListener("message", listener); -// return () => { -// window.removeEventListener("message", listener); -// }; -// }, [monacoRef.current]); - -// /* STREAMING UPDATES */ - -// const appendText = (text: string, lineCount: number) => { -// const editor = editorRef.current; -// const model = editor.getModel(); -// if (!model) return; - -// const modelLineCount = model.getLineCount(); -// lineCount = lineCount === 0 ? 1 : lineCount; -// lineCount = Math.min(lineCount, modelLineCount); -// const lastLineColumn = model.getLineMaxColumn(lineCount); - -// const id = { major: 1, minor: 1 }; -// const op = { -// identifier: id, -// range: { -// startLineNumber: lineCount, -// startColumn: lastLineColumn, -// endLineNumber: lineCount + 1, -// endColumn: 0, -// }, -// text: text, -// forceMoveMarkers: true, -// }; - -// editor.getModel().applyEdits([op]); -// }; - -// // useEffect(() => { -// // if (props.codeString === prevFullTextRef.current) return; - -// // let newText = props.codeString.slice(prevFullTextRef.current.length); -// // if (newText === "") return; - -// // // To avoid the optimistic code block fences. Because the unwanted ones are always at the end of the block, this solves the problem -// // if (newText.endsWith("`") || newText.endsWith("`\n")) { -// // newText = newText.slice(0, newText.indexOf("`")); -// // } - -// // appendText(newText); -// // prevFullTextRef.current = props.codeString; -// // }, [props.codeString, prevFullTextRef.current]); - -// useAppendedString(props.codeString, appendText); - -// const memoizedEditor = useMemo(() => { -// const rootStyle = getComputedStyle(document.documentElement); -// const fontFamily = rootStyle -// .getPropertyValue("--vscode-editor-font-family") -// .trim(); - -// return ( -// -// ); -// }, []); - -// return ( -// -// {memoizedEditor} -// -// ); -// }; diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index a386e3e87..53bed5d93 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -20,7 +20,6 @@ import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; const StyledMarkdown = styled.div<{ fontSize?: number; - showBorder?: boolean; }>` pre { background-color: ${vscEditorBackground}; @@ -30,7 +29,7 @@ const StyledMarkdown = styled.div<{ overflow-x: scroll; overflow-y: hidden; - padding: ${(props) => (props.showBorder ? "8px 12px" : "0px 2px")}; + padding: 6px; margin: 0px; } @@ -180,9 +179,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( }, [props.source]); return ( - - {reactContent} - + {reactContent} ); }); diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 548d83537..1048ad562 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -318,10 +318,15 @@ function ModelSelect() { style={{ padding: 0 }} onClick={calculatePosition} > - - {modelSelectTitle(defaultModel) || "Select model"}{" "} - +
+ + {modelSelectTitle(defaultModel) || "Select model"}{" "} + +
@@ -339,8 +344,6 @@ function ModelSelect() {
{selectedProfileId === "local" && ( <> - {options.length > 0 && } -