This commit is contained in:
Nate 2024-09-25 00:11:54 -07:00
commit 5b04828bbf
32 changed files with 473 additions and 660 deletions

View file

@ -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]),

View file

@ -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.",
},
];

View file

@ -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,
},
},
];
}

View file

@ -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(),
{

View file

@ -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,
},
},
];
}

View file

@ -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,
},
};
}),
);

View file

@ -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<ContextItem[]> {
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) {

View file

@ -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,
},
};
}),
];
}

16
core/index.d.ts vendored
View file

@ -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 {

View file

@ -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,
},
};
}

View file

@ -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<boolean> {

65
core/util/fetchFavicon.ts Normal file
View file

@ -0,0 +1,65 @@
import { JSDOM } from "jsdom";
export async function findFaviconPath(url: URL): Promise<string | undefined> {
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 <link> 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<string | undefined> {
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<string | undefined> {
const faviconPath = await findFaviconPath(url);
if (faviconPath) {
return getFaviconBase64(faviconPath);
}
return undefined;
}

View file

@ -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 (
<StyledCard className="relative">
<StyledCard className="relative px-2 py-3 xs:py-4 xs:px-4">
<OnboardingCardTabs
activeTab={onboardingCard.activeTab}
onTabClick={onboardingCard.setActiveTab}
/>
<CloseButton onClick={onboardingCard.close}>
<XMarkIcon className="h-5 w-5" />
<XMarkIcon className="h-5 w-5 hidden sm:flex" />
</CloseButton>
<div className="content py-4">{renderTabContent()}</div>
</StyledCard>

View file

@ -65,13 +65,13 @@ function BestExperienceConfigForm({
<div className="text-lg font-bold mb-1 flex flex-row justify-between gap-4">
<label className="text-lg font-bold">Chat model</label>
<div
className="flex items-center text-xs font-semibold justify-end"
className="flex items-center text-xs font-semibold justify-end hidden sm:flex"
style={{ color: lightGray }}
>
<CubeIcon className="w-4 h-4 mr-1 flex-shrink-0" />
<span className="italic text-right inline">
{chatModel.title}{" "}
<span className="max-xs:hidden">by Anthropic</span>
<span className="hidden md:inline">by Anthropic</span>
</span>
</div>
</div>
@ -99,13 +99,13 @@ function BestExperienceConfigForm({
<div className="text-lg font-bold mb-1 flex flex-row justify-between gap-4">
<label className="text-lg font-bold">Autocomplete model</label>
<div
className="flex items-center text-xs font-semibold"
className="flex items-center text-xs font-semibold hidden sm:flex"
style={{ color: lightGray }}
>
<CubeIcon className="w-4 h-4 mr-1 flex-shrink-0 inline" />
<span className="italic text-right">
{autocompleteModel.title}{" "}
<span className="max-xs:hidden">by Mistral</span>
<span className="hidden md:inline">by Mistral</span>
</span>
</div>
</div>
@ -129,7 +129,7 @@ function BestExperienceConfigForm({
</div>
</div>
<div className="mt-2 w-full">
<div className="w-full">
<Button className="w-full" type="submit" disabled={!chatApiKey}>
Connect
</Button>

View file

@ -7,7 +7,7 @@ interface OllamaCompletedStepProps {
function OllamaCompletedStep({ text }: OllamaCompletedStepProps) {
return (
<div className="flex justify-between items-center">
<p className="text-sm w-3/4 font-mono">{text}</p>
<p className="text-sm w-3/4 font-mono truncate mr-1">{text}</p>
<CheckCircleIcon width={24} height={24} className="text-emerald-600" />
</div>
);

View file

@ -35,7 +35,7 @@ function OllamaModelDownload({
) : (
<>
<StyledActionButton data-tooltip-id={id} onClick={onClick}>
<p className="font-mono">{command}</p>
<p className="font-mono truncate">{command}</p>
<CommandLineIcon width={24} height={24} />
</StyledActionButton>
{tooltipPortalDiv &&

View file

@ -35,14 +35,14 @@ export function OllamaStatus({ isOllamaConnected }: OllamaStatusProps) {
case OllamaConnectionStatuses.WaitingToDownload:
return (
<StyledActionButton onClick={onClickDownload}>
<p className="underline text-sm">{downloadUrl}</p>
<p className="underline text-sm truncate mr-1">{downloadUrl}</p>
<ArrowTopRightOnSquareIcon width={24} height={24} />
</StyledActionButton>
);
case OllamaConnectionStatuses.Downloading:
return (
<div className="flex justify-between items-center">
<p className="text-sm w-3/4 font-mono">
<p className="text-sm w-3/4 font-mono truncate mr-1">
Checking for connection to Ollama at http://localhost:11434
</p>
<ArrowPathIcon className="h-4 w-4 animate-spin-slow mr-1" />

View file

@ -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 (
<TabList>
{Object.entries(TabTitles).map(([tabType, titles]) => {
if (hasPassedFTL() && tabType === "Quickstart") {
return undefined;
}
<div>
<div className="hidden xs:block">
<TabList>
{Object.entries(TabTitles).map(([tabType, titles]) => {
if (hasPassedFTL() && tabType === "Quickstart") {
return undefined;
}
return (
<TabButton
key={tabType}
isActive={activeTab === tabType}
onClick={() => onTabClick(tabType as TabTitle)}
>
<p className="hidden xs:block m-0 font-medium">{titles.default}</p>
<p className="block xs:hidden m-0 font-medium">{titles.xs}</p>
</TabButton>
);
})}
</TabList>
return (
<TabButton
className="px-6 py-2 xs:py-2 xs:px-3 sm:px-5"
key={tabType}
isActive={activeTab === tabType}
onClick={() => onTabClick(tabType as TabTitle)}
>
<p className="hidden md:block m-0 font-medium">
{titles.default}
</p>
<p className="block md:hidden m-0 font-medium">{titles.md}</p>
</TabButton>
);
})}
</TabList>
</div>
<div className="block xs:hidden">
<StyledSelect
value={activeTab}
onChange={(e) => onTabClick(e.target.value as TabTitle)}
>
{Object.entries(TabTitles).map(([tabType, titles]) => {
if (hasPassedFTL() && tabType === "Quickstart") {
return null;
}
return (
<option key={tabType} value={tabType}>
{titles.md}
</option>
);
})}
</StyledSelect>
</div>
</div>
);
}

View file

@ -17,7 +17,7 @@ function ProviderAlert() {
}
return (
<div>
<div className="w-full">
<Alert type="info">
<p className="font-semibold text-sm m-0">
Prefer to use an different provider like OpenAI?

View file

@ -7,7 +7,9 @@ function OnboardingBestTab() {
return (
<div className="flex flex-col gap-8">
<ProviderAlert />
<div className="hidden xs:flex w-full">
<ProviderAlert />
</div>
<BestExperienceConfigForm onComplete={submitOnboarding} />
</div>
);

View file

@ -3,18 +3,18 @@ import QuickStartSubmitButton from "../components/QuickStartSubmitButton";
function OnboardingQuickstartTab() {
return (
<div className="flex justify-center items-center">
<div className="flex flex-col items-center justify-center w-3/4 text-center">
<div className="mr-5">
<div className="flex justify-center items-center w-full h-full">
<div className="flex flex-col items-center justify-center w-full max-w-full px-4 xs:px-0 text-center">
<div className="hidden xs:flex">
<ContinueLogo height={75} />
</div>
<p className="text-sm">
<p className="text-sm w-full xs:w-3/4">
Quickly get up and running using our API keys. After this trial, we'll
help you set up your own models.
</p>
<p className="text-sm">
<p className="text-sm w-full xs:w-3/4">
To prevent abuse, we'll ask you to sign in to GitHub.
</p>

View file

@ -124,14 +124,14 @@ function StepContainer(props: StepContainerProps) {
{(props.isLast || isHovered || typeof feedback !== "undefined") &&
!active && (
<div
className="flex items-center gap-1 absolute -bottom-2 right-2"
className="flex items-center gap-1 absolute -bottom-2 right-2 hidden xs:flex"
style={{
color: lightGray,
fontSize: getFontSize() - 3,
}}
>
{props.modelTitle && (
<>
<div className="hidden sm:flex">
<div className="flex items-center">{props.modelTitle}</div>
<div
className="ml-2 mr-1"
@ -141,7 +141,7 @@ function StepContainer(props: StepContainerProps) {
backgroundColor: lightGray,
}}
></div>
</>
</div>
)}
{truncatedEarly && (

View file

@ -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 (
<SafeImg
className="flex-shrink-0 pr-2"
className="flex-shrink-0 mr-2 rounded-md p-1"
src={contextItem.icon}
height={dimmensions}
width={dimmensions}
height={dimensions}
width={dimensions}
fallback={null}
/>
);
@ -114,13 +64,16 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => {
if (shouldShowFileIcon) {
return (
<FileIcon
filename={
contextItem.description.split(" ").shift()?.split("#").shift() || ""
}
height={dimmensions}
width={dimmensions}
/>
<div className="flex-shrink-0 mr-2">
<FileIcon
filename={
contextItem.description.split(" ").shift()?.split("#").shift() ||
""
}
height={dimensions}
width={dimensions}
/>
</div>
);
}
@ -131,79 +84,99 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => {
return (
<ProviderIcon
className="flex-shrink-0 pr-2"
height={dimmensions}
width={dimmensions}
className="flex-shrink-0 mr-2"
height={dimensions}
width={dimensions}
/>
);
};
}
return (
<div
onClick={openContextItem}
className="cursor-pointer px-1.5 py-1 flex items-center rounded hover:bg-white/10 overflow-hidden whitespace-nowrap text-ellipsis mr-2"
style={{ fontSize: `${getFontSize()}px` }}
>
<div className="flex items-center w-full">
{getContextItemIcon()}
<div className="flex min-w-0 flex-1 gap-2 text-xs">
<div className="truncate max-w-[50%] flex-shrink-0">
{contextItem.name}
</div>
<div
className={`text-[${
getFontSize() - 2
}px] text-gray-400 overflow-hidden truncate whitespace-nowrap text-xs flex-1 min-w-0`}
>
{contextItem.description}
</div>
</div>
</div>
</div>
);
}
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 (
<div
className="pl-2 pt-2"
style={{
paddingLeft: "8px",
paddingTop: "8px",
backgroundColor: vscBackground,
}}
>
<div
className="text-gray-300 cursor-pointer flex justify-start items-center"
style={{
color: lightGray,
cursor: "pointer",
display: "flex",
justifyContent: "left",
alignItems: "center",
fontSize: `${getFontSize() - 3}px`,
}}
onClick={() => setOpen((prev) => !prev)}
>
{open ? (
<ChevronUpIcon
width="1.0em"
height="1.0em"
<div className="relative w-4 h-4 mr-1">
<ChevronRightIcon
className={`absolute h-4 w-4 transition-all duration-200 ease-in-out ${
open ? "opacity-0 rotate-90" : "opacity-100 rotate-0"
}`}
style={{ color: lightGray }}
></ChevronUpIcon>
) : (
/>
<ChevronDownIcon
width="1.0em"
height="1.0em"
className={`absolute h-4 w-4 transition-all duration-200 ease-in-out ${
open ? "opacity-100 rotate-0" : "opacity-0 -rotate-90"
}`}
style={{ color: lightGray }}
></ChevronDownIcon>
)}
<ContextItems>{contextItemsText}</ContextItems>
/>
</div>
<span
className={`ml-1 text-xs text-gray-400 hover:text-gray-300 transition-colors duration-200`}
>
{contextItemsText}
</span>
</div>
{open && (
<div
style={{
paddingTop: "2px",
}}
>
{ctxItems?.map((contextItem, idx) => {
const contextItemContent = (
<ContextItemDiv onClick={() => openContextItem(contextItem)}>
{getContextItemIcon(contextItem)}
{contextItem.name}
</ContextItemDiv>
);
return contextItem.description.startsWith("http") ? (
<a
key={idx}
href={contextItem.description}
target="_blank"
style={{ color: vscForeground, textDecoration: "none" }}
>
{contextItemContent}
</a>
) : (
<React.Fragment key={idx}>{contextItemContent}</React.Fragment>
);
})}
</div>
)}
<div
className={`mt-2 overflow-y-auto transition-all duration-300 ease-in-out ${
open ? "max-h-[50vh] opacity-100" : "max-h-0 opacity-0"
}`}
>
{ctxItems.map((contextItem, idx) => (
<ContextItemsPeekItem key={idx} contextItem={contextItem} />
))}
</div>
</div>
);
};
}
export default ContextItemsPeek;

View file

@ -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 (
<>
<StyledDiv
isHidden={props.hidden}
onClick={props.onClick}
id="input-toolbar"
className="hidden xs:flex"
>
<span className="flex gap-2 items-center whitespace-nowrap">
<ModelSelect />
<SecondToDisappearContainer>
<StyledSpan
onClick={(e) => {
props.onAddContextItem();
}}
className="hover:underline cursor-pointer"
<div className="flex gap-2 items-center whitespace-nowrap justify-start">
<div>
<ModelSelect />
</div>
<div className="items-center hidden xs:flex">
<HoverItem
onClick={props.onAddContextItem}
className="text-gray-400 hover:text-gray-300 transition-colors duration-200"
>
Add Context{" "}
<PlusIcon className="h-2.5 w-2.5" aria-hidden="true" />
</StyledSpan>
<AtSymbolIcon className="h-4 w-4" aria-hidden="true" />
</HoverItem>
{defaultModel &&
modelSupportsImages(
defaultModel.provider,
@ -149,18 +133,14 @@ function InputToolbar(props: InputToolbarProps) {
/>
{fileSelectHovered ? (
<SolidPhotoIcon
width="1.4em"
height="1.4em"
color={lightGray}
className="h-4 w-4 text-gray-400 hover:text-gray-300 transition-colors duration-200"
onClick={(e) => {
fileInputRef.current?.click();
}}
/>
) : (
<OutlinePhotoIcon
width="1.4em"
height="1.4em"
color={lightGray}
className="h-4 w-4 text-gray-400 hover:text-gray-300 transition-colors duration-200"
onClick={(e) => {
fileInputRef.current?.click();
}}
@ -168,47 +148,40 @@ function InputToolbar(props: InputToolbarProps) {
)}
</span>
)}
</SecondToDisappearContainer>
</span>
</div>
</div>
<div className="flex items-center gap-2 whitespace-nowrap">
<div className="hidden sm:flex">
{props.activeKey === "Alt" ? (
<HoverItem>
{`${getAltKeyLabel()}⏎
${useActiveFile ? "No active file" : "Active file"}`}
</HoverItem>
) : (
<HoverItem
className={
props.activeKey === "Meta"
? "text-gray-300"
: "text-gray-400 hover:text-gray-300 transition-colors duration-200"
}
onClick={(e) =>
props.onEnter({
useCodebase: true,
noContext: !useActiveFile,
})
}
>
<span className="hidden md:inline">
{" "}
{getMetaKeyLabel()}⏎ @codebase
</span>
<span className="md:hidden">@codebase</span>
</HoverItem>
)}
</div>
<span className="flex items-center gap-2 whitespace-nowrap">
{props.showNoContext ? (
<span
style={{
color: props.usingCodebase ? vscBadgeBackground : lightGray,
backgroundColor: props.usingCodebase
? lightGray + "33"
: undefined,
borderRadius: defaultBorderRadius,
padding: "2px 4px",
}}
>
{getAltKeyLabel()} ⏎{" "}
{useActiveFile ? "No context" : "Use active file"}
</span>
) : (
<StyledSpan
style={{
color: props.usingCodebase ? vscBadgeBackground : lightGray,
backgroundColor: props.usingCodebase
? lightGray + "33"
: undefined,
borderRadius: defaultBorderRadius,
padding: "2px 4px",
}}
onClick={(e) => {
props.onEnter({
useCodebase: true,
noContext: !useActiveFile,
});
}}
className={"hover:underline cursor-pointer float-right"}
>
{getMetaKeyLabel()} ⏎ Use @codebase
</StyledSpan>
)}
<EnterButton
offFocus={props.usingCodebase}
onClick={(e) => {
props.onEnter({
useCodebase: isMetaEquivalentKeyPressed(e),
@ -216,9 +189,10 @@ function InputToolbar(props: InputToolbarProps) {
});
}}
>
⏎ Enter
<span className="hidden md:inline">⏎ Enter</span>
<span className="md:hidden">⏎</span>
</EnterButton>
</span>
</div>
</StyledDiv>
</>
);

View file

@ -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<string | null>(null);
return (
<InputBoxDiv
onKeyDown={(e) => {
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) {
}}
/>
<InputToolbar
showNoContext={optionKeyHeld}
activeKey={activeKey}
hidden={shouldHideToolbar && !props.isMainInput}
onAddContextItem={() => {
if (editor.getText().endsWith("@")) {
@ -894,6 +895,7 @@ function TipTapEditor(props: TipTapEditorProps) {
});
}}
/>
{showDragOverMsg &&
modelSupportsImages(
defaultModel.provider,

View file

@ -28,6 +28,7 @@ import FileIcon from "../FileIcon";
import ButtonWithTooltip from "../ButtonWithTooltip";
import { CopyButton as CopyButtonHeader } from "./CopyButton";
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
import { getBasename } from "core/util";
const ToolbarDiv = styled.div`
display: flex;
@ -217,11 +218,15 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
return (
<ToolbarDiv>
<div
className="flex items-center cursor-pointer py-0.5 px-0.5"
className="flex items-center cursor-pointer py-0.5 px-0.5 max-w-[50%]"
onClick={onClickHeader}
>
<FileIcon filename={props.filepath} height="18px" width="18px" />
<span className="hover:brightness-125 ml-1">{props.filepath}</span>{" "}
<div className="ml-1 truncate">
<span className="hover:brightness-125 truncate inline-block w-full">
{getBasename(props.filepath)}
</span>
</div>
</div>
<div className="flex items-center gap-1">
@ -233,12 +238,12 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
{isCopied ? (
<>
<CheckIcon className="w-3 h-3 text-green-500 hover:brightness-125" />
<span>Copied</span>
<span className="hidden sm:inline">Copied</span>
</>
) : (
<>
<ClipboardIcon className="w-3 h-3 hover:brightness-125" />
<span>Copy</span>
<span className="hidden xs:inline">Copy</span>
</>
)}
</div>
@ -256,7 +261,7 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
style={{ color: lightGray }}
>
<PlayIcon className="w-3 h-3" />
<span>Apply</span>
<span className="hidden xs:inline">Apply</span>
</div>
</ToolbarButton>
) : (

View file

@ -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<HTMLDivElement>(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 (
<PreviewMarkdownDiv
@ -105,8 +101,8 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
);
} else {
ideMessenger.post("showVirtualFile", {
content,
name: props.item.name,
content: props.item.content,
});
}
}}
@ -142,36 +138,32 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
</PreviewMarkdownHeader>
<div
contentEditable={false}
className="m-0"
className={
collapsed ? "max-h-[33vh] overflow-hidden m-0" : "overflow-auto m-0"
}
ref={codeBlockRef}
style={{
height: collapsed ? codeBlockHeight : undefined,
overflow: collapsed ? "hidden" : "auto",
}}
>
<StyledMarkdownPreview
source={`${fence}${getMarkdownLanguageTagForFile(
props.item.description,
)}\n${props.item.content.trimEnd()}\n${fence}`}
)}\n${content}\n${fence}`}
showCodeBorder={false}
/>
</div>
{(codeBlockRef.current?.scrollHeight ?? 0) > MAX_PREVIEW_HEIGHT && (
<ButtonWithTooltip
className="bottom-1 right-1 absolute"
className="bottom-1 right-2 absolute"
text={collapsed ? "Expand" : "Collapse"}
>
{collapsed ? (
<ChevronDownIcon
width="1.2em"
height="1.2em"
className="h-5 w-5"
onClick={() => setCollapsed(false)}
/>
) : (
<ChevronUpIcon
width="1.2em"
height="1.2em"
className="h-5 w-5"
onClick={() => setCollapsed(true)}
/>
)}

View file

@ -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<string> => {
// 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<monaco.editor.IStandaloneCodeEditor | null>(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 (
// <MonacoEditor
// defaultValue={props.codeString}
// editorDidMount={onEditorDidMount}
// language={
// supportedLanguagesArray.includes(props.language)
// ? props.language
// : "typescript"
// }
// theme="vs-dark"
// options={{
// automaticLayout: true,
// readOnly: true,
// minimap: { enabled: false },
// scrollBeyondLastLine: false,
// scrollbar: {
// alwaysConsumeMouseWheel: false,
// verticalScrollbarSize: 4,
// horizontalScrollbarSize: 4,
// },
// hover: {},
// renderWhitespace: "none",
// overviewRulerLanes: 0,
// lineNumbers: "off",
// folding: false,
// guides: {
// indentation: false,
// },
// renderLineHighlight: "none",
// fontLigatures: true,
// fontVariations: true,
// padding: { top: 4, bottom: 4 },
// fontFamily,
// trimAutoWhitespace: false,
// }}
// />
// );
// }, []);
// return (
// <Container showBorder={props.showBorder} {...props.preProps}>
// {memoizedEditor}
// </Container>
// );
// };

View file

@ -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 (
<StyledMarkdown fontSize={getFontSize()} showBorder={props.showCodeBorder}>
{reactContent}
</StyledMarkdown>
<StyledMarkdown fontSize={getFontSize()}>{reactContent}</StyledMarkdown>
);
});

View file

@ -318,10 +318,15 @@ function ModelSelect() {
style={{ padding: 0 }}
onClick={calculatePosition}
>
<span className="hover:underline">
{modelSelectTitle(defaultModel) || "Select model"}{" "}
<ChevronDownIcon className="h-2.5 w-2.5" aria-hidden="true" />
</span>
<div className="text-gray-400 hover:text-gray-300 transition-colors duration-200 flex items-center gap-1 max-w-[33vw]">
<span className="truncate">
{modelSelectTitle(defaultModel) || "Select model"}{" "}
</span>
<ChevronDownIcon
className="h-3 w-3 flex-shrink-0"
aria-hidden="true"
/>
</div>
</StyledListboxButton>
<StyledListboxOptions showAbove={showAbove} className="z-50">
<div className={`max-h-[${MAX_HEIGHT_PX}px]`}>
@ -339,8 +344,6 @@ function ModelSelect() {
<div className="mt-auto">
{selectedProfileId === "local" && (
<>
{options.length > 0 && <Divider className="!my-0" />}
<StyledListboxOption
key={options.length}
onClick={onClickAddModel}

View file

@ -78,15 +78,18 @@ const StopButton = styled.div`
width: fit-content;
margin-right: auto;
margin-left: auto;
font-size: ${getFontSize() - 2}px;
border: 0.5px solid ${lightGray};
border-radius: ${defaultBorderRadius};
padding: 4px 8px;
color: ${lightGray};
cursor: pointer;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
transition: box-shadow 0.3s ease;
&:hover {
box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15), 0 3px 6px rgba(0, 0, 0, 0.1);
}
`;
const StepsDiv = styled.div`

View file

@ -8,9 +8,14 @@ module.exports = {
"./src/*.{js,ts,jsx,tsx}",
],
theme: {
// Note that these breakpoints are primarily optimized for the input toolbar
screens: {
xs: "425px",
...defaultTheme.screens,
xxs: "170px", // Smallest width for Primary Sidebar in VS Code
xs: "250px", // Avg default sidebar width in VS Code
sm: "330px",
md: "460px",
lg: "590px",
xl: "720px",
},
extend: {
animation: {