Merge branch 'main' into ui-background-rays
This commit is contained in:
1
app/commit.json
Normal file
1
app/commit.json
Normal file
@@ -0,0 +1 @@
|
||||
{ "commit": "eddf5603c3865536f96774fc3358cf24760fb613" }
|
||||
@@ -52,7 +52,7 @@ export const Artifact = memo(({ messageId }: ArtifactProps) => {
|
||||
if (actions.length !== 0 && artifact.type === 'bundled') {
|
||||
const finished = !actions.find((action) => action.status !== 'complete');
|
||||
|
||||
if (finished != allActionFinished) {
|
||||
if (allActionFinished !== finished) {
|
||||
setAllActionFinished(finished);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import type { ProviderInfo } from '~/utils/types';
|
||||
import { ExportChatButton } from '~/components/chat/chatExportAndImport/ExportChatButton';
|
||||
import { ImportButtons } from '~/components/chat/chatExportAndImport/ImportButtons';
|
||||
import { ExamplePrompts } from '~/components/chat/ExamplePrompts';
|
||||
import GitCloneButton from './GitCloneButton';
|
||||
|
||||
import FilePreview from './FilePreview';
|
||||
import { ModelSelector } from '~/components/chat/ModelSelector';
|
||||
@@ -87,13 +88,65 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
|
||||
ref,
|
||||
) => {
|
||||
const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
|
||||
const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
|
||||
const [apiKeys, setApiKeys] = useState<Record<string, string>>(() => {
|
||||
const savedKeys = Cookies.get('apiKeys');
|
||||
|
||||
if (savedKeys) {
|
||||
try {
|
||||
return JSON.parse(savedKeys);
|
||||
} catch (error) {
|
||||
console.error('Failed to parse API keys from cookies:', error);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
});
|
||||
const [modelList, setModelList] = useState(MODEL_LIST);
|
||||
const [isModelSettingsCollapsed, setIsModelSettingsCollapsed] = useState(false);
|
||||
const [isListening, setIsListening] = useState(false);
|
||||
const [recognition, setRecognition] = useState<SpeechRecognition | null>(null);
|
||||
const [transcript, setTranscript] = useState('');
|
||||
|
||||
// Load enabled providers from cookies
|
||||
const [enabledProviders, setEnabledProviders] = useState(() => {
|
||||
const savedProviders = Cookies.get('providers');
|
||||
|
||||
if (savedProviders) {
|
||||
try {
|
||||
const parsedProviders = JSON.parse(savedProviders);
|
||||
return PROVIDER_LIST.filter((p) => parsedProviders[p.name]);
|
||||
} catch (error) {
|
||||
console.error('Failed to parse providers from cookies:', error);
|
||||
return PROVIDER_LIST;
|
||||
}
|
||||
}
|
||||
|
||||
return PROVIDER_LIST;
|
||||
});
|
||||
|
||||
// Update enabled providers when cookies change
|
||||
useEffect(() => {
|
||||
const updateProvidersFromCookies = () => {
|
||||
const savedProviders = Cookies.get('providers');
|
||||
|
||||
if (savedProviders) {
|
||||
try {
|
||||
const parsedProviders = JSON.parse(savedProviders);
|
||||
setEnabledProviders(PROVIDER_LIST.filter((p) => parsedProviders[p.name]));
|
||||
} catch (error) {
|
||||
console.error('Failed to parse providers from cookies:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
updateProvidersFromCookies();
|
||||
|
||||
const interval = setInterval(updateProvidersFromCookies, 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [PROVIDER_LIST]);
|
||||
|
||||
console.log(transcript);
|
||||
useEffect(() => {
|
||||
// Load API keys from cookies on component mount
|
||||
@@ -183,23 +236,6 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
|
||||
}
|
||||
};
|
||||
|
||||
const updateApiKey = (provider: string, key: string) => {
|
||||
try {
|
||||
const updatedApiKeys = { ...apiKeys, [provider]: key };
|
||||
setApiKeys(updatedApiKeys);
|
||||
|
||||
// Save updated API keys to cookies with 30 day expiry and secure settings
|
||||
Cookies.set('apiKeys', JSON.stringify(updatedApiKeys), {
|
||||
expires: 30, // 30 days
|
||||
secure: true, // Only send over HTTPS
|
||||
sameSite: 'strict', // Protect against CSRF
|
||||
path: '/', // Accessible across the site
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error saving API keys to cookies:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileUpload = () => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
@@ -323,21 +359,6 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
|
||||
<rect className={classNames(styles.PromptShine)} x="48" y="24" width="70" height="1"></rect>
|
||||
</svg>
|
||||
<div>
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<button
|
||||
onClick={() => setIsModelSettingsCollapsed(!isModelSettingsCollapsed)}
|
||||
className={classNames('flex items-center gap-2 p-2 rounded-lg transition-all', {
|
||||
'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent':
|
||||
isModelSettingsCollapsed,
|
||||
'bg-bolt-elements-item-backgroundDefault text-bolt-elements-item-contentDefault':
|
||||
!isModelSettingsCollapsed,
|
||||
})}
|
||||
>
|
||||
<div className={`i-ph:caret-${isModelSettingsCollapsed ? 'right' : 'down'} text-lg`} />
|
||||
<span>Model Settings</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className={isModelSettingsCollapsed ? 'hidden' : ''}>
|
||||
<ModelSelector
|
||||
key={provider?.name + ':' + modelList.length}
|
||||
@@ -349,11 +370,15 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
|
||||
providerList={PROVIDER_LIST}
|
||||
apiKeys={apiKeys}
|
||||
/>
|
||||
{provider && (
|
||||
{enabledProviders.length > 0 && provider && (
|
||||
<APIKeyManager
|
||||
provider={provider}
|
||||
apiKey={apiKeys[provider.name] || ''}
|
||||
setApiKey={(key) => updateApiKey(provider.name, key)}
|
||||
setApiKey={(key) => {
|
||||
const newApiKeys = { ...apiKeys, [provider.name]: key };
|
||||
setApiKeys(newApiKeys);
|
||||
Cookies.set('apiKeys', JSON.stringify(newApiKeys));
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -441,6 +466,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
|
||||
<SendButton
|
||||
show={input.length > 0 || isStreaming || uploadedFiles.length > 0}
|
||||
isStreaming={isStreaming}
|
||||
disabled={enabledProviders.length === 0}
|
||||
onClick={(event) => {
|
||||
if (isStreaming) {
|
||||
handleStop?.();
|
||||
@@ -491,6 +517,20 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
|
||||
disabled={isStreaming}
|
||||
/>
|
||||
{chatStarted && <ClientOnly>{() => <ExportChatButton exportChat={exportChat} />}</ClientOnly>}
|
||||
<IconButton
|
||||
title="Model Settings"
|
||||
className={classNames('transition-all flex items-center gap-1', {
|
||||
'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent':
|
||||
isModelSettingsCollapsed,
|
||||
'bg-bolt-elements-item-backgroundDefault text-bolt-elements-item-contentDefault':
|
||||
!isModelSettingsCollapsed,
|
||||
})}
|
||||
onClick={() => setIsModelSettingsCollapsed(!isModelSettingsCollapsed)}
|
||||
disabled={enabledProviders.length === 0}
|
||||
>
|
||||
<div className={`i-ph:caret-${isModelSettingsCollapsed ? 'right' : 'down'} text-lg`} />
|
||||
{isModelSettingsCollapsed ? <span className="text-xs">{model}</span> : <span />}
|
||||
</IconButton>
|
||||
</div>
|
||||
{input.length > 3 ? (
|
||||
<div className="text-xs text-bolt-elements-textTertiary">
|
||||
@@ -503,7 +543,12 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{!chatStarted && ImportButtons(importChat)}
|
||||
{!chatStarted && (
|
||||
<div className="flex justify-center gap-2">
|
||||
{ImportButtons(importChat)}
|
||||
<GitCloneButton importChat={importChat} />
|
||||
</div>
|
||||
)}
|
||||
{!chatStarted &&
|
||||
ExamplePrompts((event, messageInput) => {
|
||||
if (isStreaming) {
|
||||
|
||||
115
app/components/chat/GitCloneButton.tsx
Normal file
115
app/components/chat/GitCloneButton.tsx
Normal file
@@ -0,0 +1,115 @@
|
||||
import ignore from 'ignore';
|
||||
import { useGit } from '~/lib/hooks/useGit';
|
||||
import type { Message } from 'ai';
|
||||
import WithTooltip from '~/components/ui/Tooltip';
|
||||
import { detectProjectCommands, createCommandsMessage } from '~/utils/projectCommands';
|
||||
import { generateId } from '~/utils/fileUtils';
|
||||
|
||||
const IGNORE_PATTERNS = [
|
||||
'node_modules/**',
|
||||
'.git/**',
|
||||
'.github/**',
|
||||
'.vscode/**',
|
||||
'**/*.jpg',
|
||||
'**/*.jpeg',
|
||||
'**/*.png',
|
||||
'dist/**',
|
||||
'build/**',
|
||||
'.next/**',
|
||||
'coverage/**',
|
||||
'.cache/**',
|
||||
'.vscode/**',
|
||||
'.idea/**',
|
||||
'**/*.log',
|
||||
'**/.DS_Store',
|
||||
'**/npm-debug.log*',
|
||||
'**/yarn-debug.log*',
|
||||
'**/yarn-error.log*',
|
||||
'**/*lock.json',
|
||||
'**/*lock.yaml',
|
||||
];
|
||||
|
||||
const ig = ignore().add(IGNORE_PATTERNS);
|
||||
|
||||
interface GitCloneButtonProps {
|
||||
className?: string;
|
||||
importChat?: (description: string, messages: Message[]) => Promise<void>;
|
||||
}
|
||||
|
||||
export default function GitCloneButton({ importChat }: GitCloneButtonProps) {
|
||||
const { ready, gitClone } = useGit();
|
||||
const onClick = async (_e: any) => {
|
||||
if (!ready) {
|
||||
return;
|
||||
}
|
||||
|
||||
const repoUrl = prompt('Enter the Git url');
|
||||
|
||||
if (repoUrl) {
|
||||
const { workdir, data } = await gitClone(repoUrl);
|
||||
|
||||
if (importChat) {
|
||||
const filePaths = Object.keys(data).filter((filePath) => !ig.ignores(filePath));
|
||||
console.log(filePaths);
|
||||
|
||||
const textDecoder = new TextDecoder('utf-8');
|
||||
|
||||
// Convert files to common format for command detection
|
||||
const fileContents = filePaths
|
||||
.map((filePath) => {
|
||||
const { data: content, encoding } = data[filePath];
|
||||
return {
|
||||
path: filePath,
|
||||
content: encoding === 'utf8' ? content : content instanceof Uint8Array ? textDecoder.decode(content) : '',
|
||||
};
|
||||
})
|
||||
.filter((f) => f.content);
|
||||
|
||||
// Detect and create commands message
|
||||
const commands = await detectProjectCommands(fileContents);
|
||||
const commandsMessage = createCommandsMessage(commands);
|
||||
|
||||
// Create files message
|
||||
const filesMessage: Message = {
|
||||
role: 'assistant',
|
||||
content: `Cloning the repo ${repoUrl} into ${workdir}
|
||||
<boltArtifact id="imported-files" title="Git Cloned Files" type="bundled">
|
||||
${fileContents
|
||||
.map(
|
||||
(file) =>
|
||||
`<boltAction type="file" filePath="${file.path}">
|
||||
${file.content}
|
||||
</boltAction>`,
|
||||
)
|
||||
.join('\n')}
|
||||
</boltArtifact>`,
|
||||
id: generateId(),
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
const messages = [filesMessage];
|
||||
|
||||
if (commandsMessage) {
|
||||
messages.push(commandsMessage);
|
||||
}
|
||||
|
||||
await importChat(`Git Project:${repoUrl.split('/').slice(-1)[0]}`, messages);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<WithTooltip tooltip="Clone A Git Repo">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
onClick(e);
|
||||
}}
|
||||
title="Clone A Git Repo"
|
||||
className="px-4 py-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background text-bolt-elements-textPrimary hover:bg-bolt-elements-background-depth-3 transition-all flex items-center gap-2"
|
||||
>
|
||||
<span className="i-ph:git-branch" />
|
||||
Clone A Git Repo
|
||||
</button>
|
||||
</WithTooltip>
|
||||
);
|
||||
}
|
||||
@@ -1,102 +1,75 @@
|
||||
import React from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import type { Message } from 'ai';
|
||||
import { toast } from 'react-toastify';
|
||||
import ignore from 'ignore';
|
||||
import { MAX_FILES, isBinaryFile, shouldIncludeFile } from '~/utils/fileUtils';
|
||||
import { createChatFromFolder } from '~/utils/folderImport';
|
||||
|
||||
interface ImportFolderButtonProps {
|
||||
className?: string;
|
||||
importChat?: (description: string, messages: Message[]) => Promise<void>;
|
||||
}
|
||||
|
||||
// Common patterns to ignore, similar to .gitignore
|
||||
const IGNORE_PATTERNS = [
|
||||
'node_modules/**',
|
||||
'.git/**',
|
||||
'dist/**',
|
||||
'build/**',
|
||||
'.next/**',
|
||||
'coverage/**',
|
||||
'.cache/**',
|
||||
'.vscode/**',
|
||||
'.idea/**',
|
||||
'**/*.log',
|
||||
'**/.DS_Store',
|
||||
'**/npm-debug.log*',
|
||||
'**/yarn-debug.log*',
|
||||
'**/yarn-error.log*',
|
||||
];
|
||||
|
||||
const ig = ignore().add(IGNORE_PATTERNS);
|
||||
const generateId = () => Math.random().toString(36).substring(2, 15);
|
||||
|
||||
const isBinaryFile = async (file: File): Promise<boolean> => {
|
||||
const chunkSize = 1024; // Read the first 1 KB of the file
|
||||
const buffer = new Uint8Array(await file.slice(0, chunkSize).arrayBuffer());
|
||||
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
const byte = buffer[i];
|
||||
|
||||
if (byte === 0 || (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13)) {
|
||||
return true; // Found a binary character
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
export const ImportFolderButton: React.FC<ImportFolderButtonProps> = ({ className, importChat }) => {
|
||||
const shouldIncludeFile = (path: string): boolean => {
|
||||
return !ig.ignores(path);
|
||||
};
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const createChatFromFolder = async (files: File[], binaryFiles: string[]) => {
|
||||
const fileArtifacts = await Promise.all(
|
||||
files.map(async (file) => {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const allFiles = Array.from(e.target.files || []);
|
||||
|
||||
reader.onload = () => {
|
||||
const content = reader.result as string;
|
||||
const relativePath = file.webkitRelativePath.split('/').slice(1).join('/');
|
||||
resolve(
|
||||
`<boltAction type="file" filePath="${relativePath}">
|
||||
${content}
|
||||
</boltAction>`,
|
||||
);
|
||||
};
|
||||
reader.onerror = reject;
|
||||
reader.readAsText(file);
|
||||
});
|
||||
}),
|
||||
);
|
||||
if (allFiles.length > MAX_FILES) {
|
||||
toast.error(
|
||||
`This folder contains ${allFiles.length.toLocaleString()} files. This product is not yet optimized for very large projects. Please select a folder with fewer than ${MAX_FILES.toLocaleString()} files.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const binaryFilesMessage =
|
||||
binaryFiles.length > 0
|
||||
? `\n\nSkipped ${binaryFiles.length} binary files:\n${binaryFiles.map((f) => `- ${f}`).join('\n')}`
|
||||
: '';
|
||||
const folderName = allFiles[0]?.webkitRelativePath.split('/')[0] || 'Unknown Folder';
|
||||
setIsLoading(true);
|
||||
|
||||
const message: Message = {
|
||||
role: 'assistant',
|
||||
content: `I'll help you set up these files.${binaryFilesMessage}
|
||||
const loadingToast = toast.loading(`Importing ${folderName}...`);
|
||||
|
||||
<boltArtifact id="imported-files" title="Imported Files" type="bundled">
|
||||
${fileArtifacts.join('\n\n')}
|
||||
</boltArtifact>`,
|
||||
id: generateId(),
|
||||
createdAt: new Date(),
|
||||
};
|
||||
try {
|
||||
const filteredFiles = allFiles.filter((file) => shouldIncludeFile(file.webkitRelativePath));
|
||||
|
||||
const userMessage: Message = {
|
||||
role: 'user',
|
||||
id: generateId(),
|
||||
content: 'Import my files',
|
||||
createdAt: new Date(),
|
||||
};
|
||||
if (filteredFiles.length === 0) {
|
||||
toast.error('No files found in the selected folder');
|
||||
return;
|
||||
}
|
||||
|
||||
const description = `Folder Import: ${files[0].webkitRelativePath.split('/')[0]}`;
|
||||
const fileChecks = await Promise.all(
|
||||
filteredFiles.map(async (file) => ({
|
||||
file,
|
||||
isBinary: await isBinaryFile(file),
|
||||
})),
|
||||
);
|
||||
|
||||
if (importChat) {
|
||||
await importChat(description, [userMessage, message]);
|
||||
const textFiles = fileChecks.filter((f) => !f.isBinary).map((f) => f.file);
|
||||
const binaryFilePaths = fileChecks
|
||||
.filter((f) => f.isBinary)
|
||||
.map((f) => f.file.webkitRelativePath.split('/').slice(1).join('/'));
|
||||
|
||||
if (textFiles.length === 0) {
|
||||
toast.error('No text files found in the selected folder');
|
||||
return;
|
||||
}
|
||||
|
||||
if (binaryFilePaths.length > 0) {
|
||||
toast.info(`Skipping ${binaryFilePaths.length} binary files`);
|
||||
}
|
||||
|
||||
const messages = await createChatFromFolder(textFiles, binaryFilePaths, folderName);
|
||||
|
||||
if (importChat) {
|
||||
await importChat(folderName, [...messages]);
|
||||
}
|
||||
|
||||
toast.success('Folder imported successfully');
|
||||
} catch (error) {
|
||||
console.error('Failed to import folder:', error);
|
||||
toast.error('Failed to import folder');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
toast.dismiss(loadingToast);
|
||||
e.target.value = ''; // Reset file input
|
||||
}
|
||||
};
|
||||
|
||||
@@ -108,46 +81,8 @@ ${fileArtifacts.join('\n\n')}
|
||||
className="hidden"
|
||||
webkitdirectory=""
|
||||
directory=""
|
||||
onChange={async (e) => {
|
||||
const allFiles = Array.from(e.target.files || []);
|
||||
const filteredFiles = allFiles.filter((file) => shouldIncludeFile(file.webkitRelativePath));
|
||||
|
||||
if (filteredFiles.length === 0) {
|
||||
toast.error('No files found in the selected folder');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const fileChecks = await Promise.all(
|
||||
filteredFiles.map(async (file) => ({
|
||||
file,
|
||||
isBinary: await isBinaryFile(file),
|
||||
})),
|
||||
);
|
||||
|
||||
const textFiles = fileChecks.filter((f) => !f.isBinary).map((f) => f.file);
|
||||
const binaryFilePaths = fileChecks
|
||||
.filter((f) => f.isBinary)
|
||||
.map((f) => f.file.webkitRelativePath.split('/').slice(1).join('/'));
|
||||
|
||||
if (textFiles.length === 0) {
|
||||
toast.error('No text files found in the selected folder');
|
||||
return;
|
||||
}
|
||||
|
||||
if (binaryFilePaths.length > 0) {
|
||||
toast.info(`Skipping ${binaryFilePaths.length} binary files`);
|
||||
}
|
||||
|
||||
await createChatFromFolder(textFiles, binaryFilePaths);
|
||||
} catch (error) {
|
||||
console.error('Failed to import folder:', error);
|
||||
toast.error('Failed to import folder');
|
||||
}
|
||||
|
||||
e.target.value = ''; // Reset file input
|
||||
}}
|
||||
{...({} as any)} // if removed webkitdirectory will throw errors as unknow attribute
|
||||
onChange={handleFileChange}
|
||||
{...({} as any)}
|
||||
/>
|
||||
<button
|
||||
onClick={() => {
|
||||
@@ -155,9 +90,10 @@ ${fileArtifacts.join('\n\n')}
|
||||
input?.click();
|
||||
}}
|
||||
className={className}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<div className="i-ph:upload-simple" />
|
||||
Import Folder
|
||||
{isLoading ? 'Importing...' : 'Import Folder'}
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { ProviderInfo } from '~/types/model';
|
||||
import type { ModelInfo } from '~/utils/types';
|
||||
import { useEffect, useState } from 'react';
|
||||
import Cookies from 'js-cookie';
|
||||
|
||||
interface ModelSelectorProps {
|
||||
model?: string;
|
||||
@@ -19,12 +21,79 @@ export const ModelSelector = ({
|
||||
modelList,
|
||||
providerList,
|
||||
}: ModelSelectorProps) => {
|
||||
// Load enabled providers from cookies
|
||||
const [enabledProviders, setEnabledProviders] = useState(() => {
|
||||
const savedProviders = Cookies.get('providers');
|
||||
|
||||
if (savedProviders) {
|
||||
try {
|
||||
const parsedProviders = JSON.parse(savedProviders);
|
||||
return providerList.filter((p) => parsedProviders[p.name]);
|
||||
} catch (error) {
|
||||
console.error('Failed to parse providers from cookies:', error);
|
||||
return providerList;
|
||||
}
|
||||
}
|
||||
|
||||
return providerList;
|
||||
});
|
||||
|
||||
// Update enabled providers when cookies change
|
||||
useEffect(() => {
|
||||
// Function to update providers from cookies
|
||||
const updateProvidersFromCookies = () => {
|
||||
const savedProviders = Cookies.get('providers');
|
||||
|
||||
if (savedProviders) {
|
||||
try {
|
||||
const parsedProviders = JSON.parse(savedProviders);
|
||||
const newEnabledProviders = providerList.filter((p) => parsedProviders[p.name]);
|
||||
setEnabledProviders(newEnabledProviders);
|
||||
|
||||
// If current provider is disabled, switch to first enabled provider
|
||||
if (provider && !parsedProviders[provider.name] && newEnabledProviders.length > 0) {
|
||||
const firstEnabledProvider = newEnabledProviders[0];
|
||||
setProvider?.(firstEnabledProvider);
|
||||
|
||||
// Also update the model to the first available one for the new provider
|
||||
const firstModel = modelList.find((m) => m.provider === firstEnabledProvider.name);
|
||||
|
||||
if (firstModel) {
|
||||
setModel?.(firstModel.name);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to parse providers from cookies:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Initial update
|
||||
updateProvidersFromCookies();
|
||||
|
||||
// Set up an interval to check for cookie changes
|
||||
const interval = setInterval(updateProvidersFromCookies, 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [providerList, provider, setProvider, modelList, setModel]);
|
||||
|
||||
if (enabledProviders.length === 0) {
|
||||
return (
|
||||
<div className="mb-2 p-4 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background text-bolt-elements-textPrimary">
|
||||
<p className="text-center">
|
||||
No providers are currently enabled. Please enable at least one provider in the settings to start using the
|
||||
chat.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mb-2 flex gap-2 flex-col sm:flex-row">
|
||||
<select
|
||||
value={provider?.name ?? ''}
|
||||
onChange={(e) => {
|
||||
const newProvider = providerList.find((p: ProviderInfo) => p.name === e.target.value);
|
||||
const newProvider = enabledProviders.find((p: ProviderInfo) => p.name === e.target.value);
|
||||
|
||||
if (newProvider && setProvider) {
|
||||
setProvider(newProvider);
|
||||
@@ -38,7 +107,7 @@ export const ModelSelector = ({
|
||||
}}
|
||||
className="flex-1 p-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background text-bolt-elements-textPrimary focus:outline-none focus:ring-2 focus:ring-bolt-elements-focus transition-all"
|
||||
>
|
||||
{providerList.map((provider: ProviderInfo) => (
|
||||
{enabledProviders.map((provider: ProviderInfo) => (
|
||||
<option key={provider.name} value={provider.name}>
|
||||
{provider.name}
|
||||
</option>
|
||||
|
||||
@@ -3,25 +3,30 @@ import { AnimatePresence, cubicBezier, motion } from 'framer-motion';
|
||||
interface SendButtonProps {
|
||||
show: boolean;
|
||||
isStreaming?: boolean;
|
||||
disabled?: boolean;
|
||||
onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
|
||||
onImagesSelected?: (images: File[]) => void;
|
||||
}
|
||||
|
||||
const customEasingFn = cubicBezier(0.4, 0, 0.2, 1);
|
||||
|
||||
export const SendButton = ({ show, isStreaming, onClick }: SendButtonProps) => {
|
||||
export const SendButton = ({ show, isStreaming, disabled, onClick }: SendButtonProps) => {
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{show ? (
|
||||
<motion.button
|
||||
className="absolute flex justify-center items-center top-[18px] right-[22px] p-1 bg-accent-500 hover:brightness-94 color-white rounded-md w-[34px] h-[34px] transition-theme"
|
||||
className="absolute flex justify-center items-center top-[18px] right-[22px] p-1 bg-accent-500 hover:brightness-94 color-white rounded-md w-[34px] h-[34px] transition-theme disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
transition={{ ease: customEasingFn, duration: 0.17 }}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: 10 }}
|
||||
disabled={disabled}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
onClick?.(event);
|
||||
|
||||
if (!disabled) {
|
||||
onClick?.(event);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="text-lg">
|
||||
|
||||
@@ -5,7 +5,7 @@ import { ImportFolderButton } from '~/components/chat/ImportFolderButton';
|
||||
|
||||
export function ImportButtons(importChat: ((description: string, messages: Message[]) => Promise<void>) | undefined) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center flex-1 p-4">
|
||||
<div className="flex flex-col items-center justify-center w-auto">
|
||||
<input
|
||||
type="file"
|
||||
id="chat-import"
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { LanguageDescription } from '@codemirror/language';
|
||||
|
||||
export const supportedLanguages = [
|
||||
LanguageDescription.of({
|
||||
name: 'VUE',
|
||||
extensions: ['vue'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-vue').then((module) => module.vue());
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'TS',
|
||||
extensions: ['ts'],
|
||||
|
||||
117
app/components/git/GitUrlImport.client.tsx
Normal file
117
app/components/git/GitUrlImport.client.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
import { useSearchParams } from '@remix-run/react';
|
||||
import { generateId, type Message } from 'ai';
|
||||
import ignore from 'ignore';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { ClientOnly } from 'remix-utils/client-only';
|
||||
import { BaseChat } from '~/components/chat/BaseChat';
|
||||
import { Chat } from '~/components/chat/Chat.client';
|
||||
import { useGit } from '~/lib/hooks/useGit';
|
||||
import { useChatHistory } from '~/lib/persistence';
|
||||
import { createCommandsMessage, detectProjectCommands } from '~/utils/projectCommands';
|
||||
|
||||
const IGNORE_PATTERNS = [
|
||||
'node_modules/**',
|
||||
'.git/**',
|
||||
'.github/**',
|
||||
'.vscode/**',
|
||||
'**/*.jpg',
|
||||
'**/*.jpeg',
|
||||
'**/*.png',
|
||||
'dist/**',
|
||||
'build/**',
|
||||
'.next/**',
|
||||
'coverage/**',
|
||||
'.cache/**',
|
||||
'.vscode/**',
|
||||
'.idea/**',
|
||||
'**/*.log',
|
||||
'**/.DS_Store',
|
||||
'**/npm-debug.log*',
|
||||
'**/yarn-debug.log*',
|
||||
'**/yarn-error.log*',
|
||||
'**/*lock.json',
|
||||
'**/*lock.yaml',
|
||||
];
|
||||
|
||||
export function GitUrlImport() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const { ready: historyReady, importChat } = useChatHistory();
|
||||
const { ready: gitReady, gitClone } = useGit();
|
||||
const [imported, setImported] = useState(false);
|
||||
|
||||
const importRepo = async (repoUrl?: string) => {
|
||||
if (!gitReady && !historyReady) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (repoUrl) {
|
||||
const ig = ignore().add(IGNORE_PATTERNS);
|
||||
const { workdir, data } = await gitClone(repoUrl);
|
||||
|
||||
if (importChat) {
|
||||
const filePaths = Object.keys(data).filter((filePath) => !ig.ignores(filePath));
|
||||
|
||||
const textDecoder = new TextDecoder('utf-8');
|
||||
|
||||
// Convert files to common format for command detection
|
||||
const fileContents = filePaths
|
||||
.map((filePath) => {
|
||||
const { data: content, encoding } = data[filePath];
|
||||
return {
|
||||
path: filePath,
|
||||
content: encoding === 'utf8' ? content : content instanceof Uint8Array ? textDecoder.decode(content) : '',
|
||||
};
|
||||
})
|
||||
.filter((f) => f.content);
|
||||
|
||||
// Detect and create commands message
|
||||
const commands = await detectProjectCommands(fileContents);
|
||||
const commandsMessage = createCommandsMessage(commands);
|
||||
|
||||
// Create files message
|
||||
const filesMessage: Message = {
|
||||
role: 'assistant',
|
||||
content: `Cloning the repo ${repoUrl} into ${workdir}
|
||||
<boltArtifact id="imported-files" title="Git Cloned Files" type="bundled">
|
||||
${fileContents
|
||||
.map(
|
||||
(file) =>
|
||||
`<boltAction type="file" filePath="${file.path}">
|
||||
${file.content}
|
||||
</boltAction>`,
|
||||
)
|
||||
.join('\n')}
|
||||
</boltArtifact>`,
|
||||
id: generateId(),
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
const messages = [filesMessage];
|
||||
|
||||
if (commandsMessage) {
|
||||
messages.push(commandsMessage);
|
||||
}
|
||||
|
||||
await importChat(`Git Project:${repoUrl.split('/').slice(-1)[0]}`, messages);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!historyReady || !gitReady || imported) {
|
||||
return;
|
||||
}
|
||||
|
||||
const url = searchParams.get('url');
|
||||
|
||||
if (!url) {
|
||||
window.location.href = '/';
|
||||
return;
|
||||
}
|
||||
|
||||
importRepo(url);
|
||||
setImported(true);
|
||||
}, [searchParams, historyReady, gitReady, imported]);
|
||||
|
||||
return <ClientOnly fallback={<BaseChat />}>{() => <Chat />}</ClientOnly>;
|
||||
}
|
||||
63
app/components/settings/Settings.module.scss
Normal file
63
app/components/settings/Settings.module.scss
Normal file
@@ -0,0 +1,63 @@
|
||||
.settings-tabs {
|
||||
button {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 0.5rem;
|
||||
text-align: left;
|
||||
font-size: 0.875rem;
|
||||
transition: all 0.2s;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
&.active {
|
||||
background: var(--bolt-elements-button-primary-background);
|
||||
color: var(--bolt-elements-textPrimary);
|
||||
}
|
||||
|
||||
&:not(.active) {
|
||||
background: var(--bolt-elements-bg-depth-3);
|
||||
color: var(--bolt-elements-textPrimary);
|
||||
|
||||
&:hover {
|
||||
background: var(--bolt-elements-button-primary-backgroundHover);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.settings-button {
|
||||
background-color: var(--bolt-elements-button-primary-background);
|
||||
color: var(--bolt-elements-textPrimary);
|
||||
border-radius: 0.5rem;
|
||||
padding: 0.5rem 1rem;
|
||||
transition: background-color 0.2s;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--bolt-elements-button-primary-backgroundHover);
|
||||
}
|
||||
}
|
||||
|
||||
.settings-danger-area {
|
||||
background-color: transparent;
|
||||
color: var(--bolt-elements-textPrimary);
|
||||
border-radius: 0.5rem;
|
||||
padding: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
border-style: solid;
|
||||
border-color: var(--bolt-elements-button-danger-backgroundHover) ;
|
||||
border-width: thin;
|
||||
|
||||
button {
|
||||
background-color: var(--bolt-elements-button-danger-background);
|
||||
color: var(--bolt-elements-button-danger-text);
|
||||
border-radius: 0.5rem;
|
||||
padding: 0.5rem 1rem;
|
||||
transition: background-color 0.2s;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--bolt-elements-button-danger-backgroundHover);
|
||||
}
|
||||
}
|
||||
}
|
||||
481
app/components/settings/SettingsWindow.tsx
Normal file
481
app/components/settings/SettingsWindow.tsx
Normal file
@@ -0,0 +1,481 @@
|
||||
import * as RadixDialog from '@radix-ui/react-dialog';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useState } from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { DialogTitle, dialogVariants, dialogBackdropVariants } from '~/components/ui/Dialog';
|
||||
import { IconButton } from '~/components/ui/IconButton';
|
||||
import { providersList } from '~/lib/stores/settings';
|
||||
import { db, getAll, deleteById } from '~/lib/persistence';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useNavigate } from '@remix-run/react';
|
||||
import commit from '~/commit.json';
|
||||
import Cookies from 'js-cookie';
|
||||
import styles from './Settings.module.scss';
|
||||
import { Switch } from '~/components/ui/Switch';
|
||||
|
||||
interface SettingsProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
type TabType = 'chat-history' | 'providers' | 'features' | 'debug' | 'connection';
|
||||
|
||||
// Providers that support base URL configuration
|
||||
const URL_CONFIGURABLE_PROVIDERS = ['Ollama', 'LMStudio', 'OpenAILike'];
|
||||
|
||||
export const SettingsWindow = ({ open, onClose }: SettingsProps) => {
|
||||
const navigate = useNavigate();
|
||||
const [activeTab, setActiveTab] = useState<TabType>('chat-history');
|
||||
const [isDebugEnabled, setIsDebugEnabled] = useState(() => {
|
||||
const savedDebugState = Cookies.get('isDebugEnabled');
|
||||
return savedDebugState === 'true';
|
||||
});
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [githubUsername, setGithubUsername] = useState(Cookies.get('githubUsername') || '');
|
||||
const [githubToken, setGithubToken] = useState(Cookies.get('githubToken') || '');
|
||||
const [isLocalModelsEnabled, setIsLocalModelsEnabled] = useState(() => {
|
||||
const savedLocalModelsState = Cookies.get('isLocalModelsEnabled');
|
||||
return savedLocalModelsState === 'true';
|
||||
});
|
||||
|
||||
// Load base URLs from cookies
|
||||
const [baseUrls, setBaseUrls] = useState(() => {
|
||||
const savedUrls = Cookies.get('providerBaseUrls');
|
||||
|
||||
if (savedUrls) {
|
||||
try {
|
||||
return JSON.parse(savedUrls);
|
||||
} catch (error) {
|
||||
console.error('Failed to parse base URLs from cookies:', error);
|
||||
return {
|
||||
Ollama: 'http://localhost:11434',
|
||||
LMStudio: 'http://localhost:1234',
|
||||
OpenAILike: '',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
Ollama: 'http://localhost:11434',
|
||||
LMStudio: 'http://localhost:1234',
|
||||
OpenAILike: '',
|
||||
};
|
||||
});
|
||||
|
||||
const handleBaseUrlChange = (provider: string, url: string) => {
|
||||
setBaseUrls((prev: Record<string, string>) => {
|
||||
const newUrls = { ...prev, [provider]: url };
|
||||
Cookies.set('providerBaseUrls', JSON.stringify(newUrls));
|
||||
|
||||
return newUrls;
|
||||
});
|
||||
};
|
||||
|
||||
const tabs: { id: TabType; label: string; icon: string }[] = [
|
||||
{ id: 'chat-history', label: 'Chat History', icon: 'i-ph:book' },
|
||||
{ id: 'providers', label: 'Providers', icon: 'i-ph:key' },
|
||||
{ id: 'features', label: 'Features', icon: 'i-ph:star' },
|
||||
{ id: 'connection', label: 'Connection', icon: 'i-ph:link' },
|
||||
...(isDebugEnabled ? [{ id: 'debug' as TabType, label: 'Debug Tab', icon: 'i-ph:bug' }] : []),
|
||||
];
|
||||
|
||||
// Load providers from cookies on mount
|
||||
const [providers, setProviders] = useState(() => {
|
||||
const savedProviders = Cookies.get('providers');
|
||||
|
||||
if (savedProviders) {
|
||||
try {
|
||||
const parsedProviders = JSON.parse(savedProviders);
|
||||
|
||||
// Merge saved enabled states with the base provider list
|
||||
return providersList.map((provider) => ({
|
||||
...provider,
|
||||
isEnabled: parsedProviders[provider.name] || false,
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error('Failed to parse providers from cookies:', error);
|
||||
}
|
||||
}
|
||||
|
||||
return providersList;
|
||||
});
|
||||
|
||||
const handleToggleProvider = (providerName: string, enabled: boolean) => {
|
||||
setProviders((prevProviders) => {
|
||||
const newProviders = prevProviders.map((provider) =>
|
||||
provider.name === providerName ? { ...provider, isEnabled: enabled } : provider,
|
||||
);
|
||||
|
||||
// Save to cookies
|
||||
const enabledStates = newProviders.reduce(
|
||||
(acc, provider) => ({
|
||||
...acc,
|
||||
[provider.name]: provider.isEnabled,
|
||||
}),
|
||||
{},
|
||||
);
|
||||
Cookies.set('providers', JSON.stringify(enabledStates));
|
||||
|
||||
return newProviders;
|
||||
});
|
||||
};
|
||||
|
||||
const filteredProviders = providers
|
||||
.filter((provider) => {
|
||||
const isLocalModelProvider = ['OpenAILike', 'LMStudio', 'Ollama'].includes(provider.name);
|
||||
return isLocalModelsEnabled || !isLocalModelProvider;
|
||||
})
|
||||
.filter((provider) => provider.name.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
const handleCopyToClipboard = () => {
|
||||
const debugInfo = {
|
||||
OS: navigator.platform,
|
||||
Browser: navigator.userAgent,
|
||||
ActiveFeatures: providers.filter((provider) => provider.isEnabled).map((provider) => provider.name),
|
||||
BaseURLs: {
|
||||
Ollama: process.env.REACT_APP_OLLAMA_URL,
|
||||
OpenAI: process.env.REACT_APP_OPENAI_URL,
|
||||
LMStudio: process.env.REACT_APP_LM_STUDIO_URL,
|
||||
},
|
||||
Version: versionHash,
|
||||
};
|
||||
navigator.clipboard.writeText(JSON.stringify(debugInfo, null, 2)).then(() => {
|
||||
alert('Debug information copied to clipboard!');
|
||||
});
|
||||
};
|
||||
|
||||
const downloadAsJson = (data: any, filename: string) => {
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const handleDeleteAllChats = async () => {
|
||||
if (!db) {
|
||||
toast.error('Database is not available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsDeleting(true);
|
||||
|
||||
const allChats = await getAll(db);
|
||||
|
||||
// Delete all chats one by one
|
||||
await Promise.all(allChats.map((chat) => deleteById(db!, chat.id)));
|
||||
|
||||
toast.success('All chats deleted successfully');
|
||||
navigate('/', { replace: true });
|
||||
} catch (error) {
|
||||
toast.error('Failed to delete chats');
|
||||
console.error(error);
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportAllChats = async () => {
|
||||
if (!db) {
|
||||
toast.error('Database is not available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const allChats = await getAll(db);
|
||||
const exportData = {
|
||||
chats: allChats,
|
||||
exportDate: new Date().toISOString(),
|
||||
};
|
||||
|
||||
downloadAsJson(exportData, `all-chats-${new Date().toISOString()}.json`);
|
||||
toast.success('Chats exported successfully');
|
||||
} catch (error) {
|
||||
toast.error('Failed to export chats');
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const versionHash = commit.commit; // Get the version hash from commit.json
|
||||
|
||||
const handleSaveConnection = () => {
|
||||
Cookies.set('githubUsername', githubUsername);
|
||||
Cookies.set('githubToken', githubToken);
|
||||
toast.success('GitHub credentials saved successfully!');
|
||||
};
|
||||
|
||||
const handleToggleDebug = (enabled: boolean) => {
|
||||
setIsDebugEnabled(enabled);
|
||||
Cookies.set('isDebugEnabled', String(enabled));
|
||||
};
|
||||
|
||||
const handleToggleLocalModels = (enabled: boolean) => {
|
||||
setIsLocalModelsEnabled(enabled);
|
||||
Cookies.set('isLocalModelsEnabled', String(enabled));
|
||||
};
|
||||
|
||||
return (
|
||||
<RadixDialog.Root open={open}>
|
||||
<RadixDialog.Portal>
|
||||
<RadixDialog.Overlay asChild onClick={onClose}>
|
||||
<motion.div
|
||||
className="bg-black/50 fixed inset-0 z-max backdrop-blur-sm"
|
||||
initial="closed"
|
||||
animate="open"
|
||||
exit="closed"
|
||||
variants={dialogBackdropVariants}
|
||||
/>
|
||||
</RadixDialog.Overlay>
|
||||
<RadixDialog.Content asChild>
|
||||
<motion.div
|
||||
className="fixed top-[50%] left-[50%] z-max h-[85vh] w-[90vw] max-w-[900px] translate-x-[-50%] translate-y-[-50%] border border-bolt-elements-borderColor rounded-lg shadow-lg focus:outline-none overflow-hidden"
|
||||
initial="closed"
|
||||
animate="open"
|
||||
exit="closed"
|
||||
variants={dialogVariants}
|
||||
>
|
||||
<div className="flex h-full">
|
||||
<div
|
||||
className={classNames(
|
||||
'w-48 border-r border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 p-4 flex flex-col justify-between',
|
||||
styles['settings-tabs'],
|
||||
)}
|
||||
>
|
||||
<DialogTitle className="flex-shrink-0 text-lg font-semibold text-bolt-elements-textPrimary mb-2">
|
||||
Settings
|
||||
</DialogTitle>
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={classNames(activeTab === tab.id ? styles.active : '')}
|
||||
>
|
||||
<div className={tab.icon} />
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
<div className="mt-auto flex flex-col gap-2">
|
||||
<a
|
||||
href="https://github.com/coleam00/bolt.new-any-llm"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={classNames(styles['settings-button'], 'flex items-center gap-2')}
|
||||
>
|
||||
<div className="i-ph:github-logo" />
|
||||
GitHub
|
||||
</a>
|
||||
<a
|
||||
href="https://coleam00.github.io/bolt.new-any-llm"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={classNames(styles['settings-button'], 'flex items-center gap-2')}
|
||||
>
|
||||
<div className="i-ph:book" />
|
||||
Docs
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 flex flex-col p-8 pt-10 bg-bolt-elements-background-depth-2">
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{activeTab === 'chat-history' && (
|
||||
<div className="p-4">
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Chat History</h3>
|
||||
<button
|
||||
onClick={handleExportAllChats}
|
||||
className={classNames(
|
||||
'bg-bolt-elements-button-primary-background',
|
||||
'rounded-lg px-4 py-2 mb-4 transition-colors duration-200',
|
||||
'hover:bg-bolt-elements-button-primary-backgroundHover',
|
||||
'text-bolt-elements-button-primary-text',
|
||||
)}
|
||||
>
|
||||
Export All Chats
|
||||
</button>
|
||||
|
||||
<div
|
||||
className={classNames(
|
||||
'text-bolt-elements-textPrimary rounded-lg py-4 mb-4',
|
||||
styles['settings-danger-area'],
|
||||
)}
|
||||
>
|
||||
<h4 className="font-semibold">Danger Area</h4>
|
||||
<p className="mb-2">This action cannot be undone!</p>
|
||||
<button
|
||||
onClick={handleDeleteAllChats}
|
||||
disabled={isDeleting}
|
||||
className={classNames(
|
||||
'bg-bolt-elements-button-danger-background',
|
||||
'rounded-lg px-4 py-2 transition-colors duration-200',
|
||||
isDeleting
|
||||
? 'opacity-50 cursor-not-allowed'
|
||||
: 'hover:bg-bolt-elements-button-danger-backgroundHover',
|
||||
'text-bolt-elements-button-danger-text',
|
||||
)}
|
||||
>
|
||||
{isDeleting ? 'Deleting...' : 'Delete All Chats'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'providers' && (
|
||||
<div className="p-4">
|
||||
<div className="flex mb-4">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search providers..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full bg-white dark:bg-bolt-elements-background-depth-4 relative px-2 py-1.5 rounded-md focus:outline-none placeholder-bolt-elements-textTertiary text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary border border-bolt-elements-borderColor"
|
||||
/>
|
||||
</div>
|
||||
{filteredProviders.map((provider) => (
|
||||
<div
|
||||
key={provider.name}
|
||||
className="flex flex-col mb-2 provider-item hover:bg-bolt-elements-bg-depth-3 p-4 rounded-lg border border-bolt-elements-borderColor "
|
||||
>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-bolt-elements-textPrimary">{provider.name}</span>
|
||||
<Switch
|
||||
className="ml-auto"
|
||||
checked={provider.isEnabled}
|
||||
onCheckedChange={(enabled) => handleToggleProvider(provider.name, enabled)}
|
||||
/>
|
||||
</div>
|
||||
{/* Base URL input for configurable providers */}
|
||||
{URL_CONFIGURABLE_PROVIDERS.includes(provider.name) && provider.isEnabled && (
|
||||
<div className="mt-2">
|
||||
<label className="block text-sm text-bolt-elements-textSecondary mb-1">Base URL:</label>
|
||||
<input
|
||||
type="text"
|
||||
value={baseUrls[provider.name]}
|
||||
onChange={(e) => handleBaseUrlChange(provider.name, e.target.value)}
|
||||
placeholder={`Enter ${provider.name} base URL`}
|
||||
className="w-full bg-white dark:bg-bolt-elements-background-depth-4 relative px-2 py-1.5 rounded-md focus:outline-none placeholder-bolt-elements-textTertiary text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary border border-bolt-elements-borderColor"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'features' && (
|
||||
<div className="p-4 bg-bolt-elements-bg-depth-2 border border-bolt-elements-borderColor rounded-lg mb-4">
|
||||
<div className="mb-6">
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Optional Features</h3>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-bolt-elements-textPrimary">Debug Info</span>
|
||||
<Switch
|
||||
className="ml-auto"
|
||||
checked={isDebugEnabled}
|
||||
onCheckedChange={handleToggleDebug}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-6 border-t border-bolt-elements-borderColor pt-4">
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Experimental Features</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary mb-4">
|
||||
Disclaimer: Experimental features may be unstable and are subject to change.
|
||||
</p>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-bolt-elements-textPrimary">Enable Local Models</span>
|
||||
<Switch
|
||||
className="ml-auto"
|
||||
checked={isLocalModelsEnabled}
|
||||
onCheckedChange={handleToggleLocalModels}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'debug' && isDebugEnabled && (
|
||||
<div className="p-4">
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Debug Tab</h3>
|
||||
<button
|
||||
onClick={handleCopyToClipboard}
|
||||
className="bg-blue-500 text-white rounded-lg px-4 py-2 hover:bg-blue-600 mb-4 transition-colors duration-200"
|
||||
>
|
||||
Copy to Clipboard
|
||||
</button>
|
||||
|
||||
<h4 className="text-md font-medium text-bolt-elements-textPrimary">System Information</h4>
|
||||
<p className="text-bolt-elements-textSecondary">OS: {navigator.platform}</p>
|
||||
<p className="text-bolt-elements-textSecondary">Browser: {navigator.userAgent}</p>
|
||||
|
||||
<h4 className="text-md font-medium text-bolt-elements-textPrimary mt-4">Active Features</h4>
|
||||
<ul>
|
||||
{providers
|
||||
.filter((provider) => provider.isEnabled)
|
||||
.map((provider) => (
|
||||
<li key={provider.name} className="text-bolt-elements-textSecondary">
|
||||
{provider.name}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<h4 className="text-md font-medium text-bolt-elements-textPrimary mt-4">Base URLs</h4>
|
||||
<ul>
|
||||
<li className="text-bolt-elements-textSecondary">Ollama: {process.env.REACT_APP_OLLAMA_URL}</li>
|
||||
<li className="text-bolt-elements-textSecondary">OpenAI: {process.env.REACT_APP_OPENAI_URL}</li>
|
||||
<li className="text-bolt-elements-textSecondary">
|
||||
LM Studio: {process.env.REACT_APP_LM_STUDIO_URL}
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<h4 className="text-md font-medium text-bolt-elements-textPrimary mt-4">Version Information</h4>
|
||||
<p className="text-bolt-elements-textSecondary">Version Hash: {versionHash}</p>
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'connection' && (
|
||||
<div className="p-4 mb-4 border border-bolt-elements-borderColor rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">GitHub Connection</h3>
|
||||
<div className="flex mb-4">
|
||||
<div className="flex-1 mr-2">
|
||||
<label className="block text-sm text-bolt-elements-textSecondary mb-1">GitHub Username:</label>
|
||||
<input
|
||||
type="text"
|
||||
value={githubUsername}
|
||||
onChange={(e) => setGithubUsername(e.target.value)}
|
||||
className="w-full bg-white dark:bg-bolt-elements-background-depth-4 relative px-2 py-1.5 rounded-md focus:outline-none placeholder-bolt-elements-textTertiary text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary border border-bolt-elements-borderColor"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm text-bolt-elements-textSecondary mb-1">Personal Access Token:</label>
|
||||
<input
|
||||
type="password"
|
||||
value={githubToken}
|
||||
onChange={(e) => setGithubToken(e.target.value)}
|
||||
className="w-full bg-white dark:bg-bolt-elements-background-depth-4 relative px-2 py-1.5 rounded-md focus:outline-none placeholder-bolt-elements-textTertiary text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary border border-bolt-elements-borderColor"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex mb-4">
|
||||
<button
|
||||
onClick={handleSaveConnection}
|
||||
className="bg-bolt-elements-button-primary-background rounded-lg px-4 py-2 mr-2 transition-colors duration-200 hover:bg-bolt-elements-button-primary-backgroundHover text-bolt-elements-button-primary-text"
|
||||
>
|
||||
Save Connection
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<RadixDialog.Close asChild onClick={onClose}>
|
||||
<IconButton icon="i-ph:x" className="absolute top-[10px] right-[10px]" />
|
||||
</RadixDialog.Close>
|
||||
</motion.div>
|
||||
</RadixDialog.Content>
|
||||
</RadixDialog.Portal>
|
||||
</RadixDialog.Root>
|
||||
);
|
||||
};
|
||||
@@ -3,6 +3,8 @@ import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { Dialog, DialogButton, DialogDescription, DialogRoot, DialogTitle } from '~/components/ui/Dialog';
|
||||
import { ThemeSwitch } from '~/components/ui/ThemeSwitch';
|
||||
import { SettingsWindow } from '~/components/settings/SettingsWindow';
|
||||
import { SettingsButton } from '~/components/ui/SettingsButton';
|
||||
import { db, deleteById, getAll, chatId, type ChatHistoryItem, useChatHistory } from '~/lib/persistence';
|
||||
import { cubicEasingFn } from '~/utils/easings';
|
||||
import { logger } from '~/utils/logger';
|
||||
@@ -39,6 +41,7 @@ export const Menu = () => {
|
||||
const [list, setList] = useState<ChatHistoryItem[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [dialogContent, setDialogContent] = useState<DialogContent>(null);
|
||||
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
|
||||
|
||||
const { filteredItems: filteredList, handleSearchChange } = useSearchFilter({
|
||||
items: list,
|
||||
@@ -200,10 +203,12 @@ export const Menu = () => {
|
||||
</Dialog>
|
||||
</DialogRoot>
|
||||
</div>
|
||||
<div className="flex items-center border-t border-bolt-elements-borderColor p-4">
|
||||
<ThemeSwitch className="ml-auto" />
|
||||
<div className="flex items-center justify-between border-t border-bolt-elements-borderColor p-4">
|
||||
<SettingsButton onClick={() => setIsSettingsOpen(true)} />
|
||||
<ThemeSwitch />
|
||||
</div>
|
||||
</div>
|
||||
<SettingsWindow open={isSettingsOpen} onClose={() => setIsSettingsOpen(false)} />
|
||||
</motion.div>
|
||||
);
|
||||
};
|
||||
|
||||
17
app/components/ui/SettingsButton.tsx
Normal file
17
app/components/ui/SettingsButton.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { memo } from 'react';
|
||||
import { IconButton } from '~/components/ui/IconButton';
|
||||
interface SettingsButtonProps {
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
export const SettingsButton = memo(({ onClick }: SettingsButtonProps) => {
|
||||
return (
|
||||
<IconButton
|
||||
onClick={onClick}
|
||||
icon="i-ph:gear"
|
||||
size="xl"
|
||||
title="Settings"
|
||||
className="text-[#666] hover:text-bolt-elements-textPrimary hover:bg-bolt-elements-item-backgroundActive/10 transition-colors"
|
||||
/>
|
||||
);
|
||||
});
|
||||
37
app/components/ui/Switch.tsx
Normal file
37
app/components/ui/Switch.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { memo } from 'react';
|
||||
import * as SwitchPrimitive from '@radix-ui/react-switch';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
interface SwitchProps {
|
||||
className?: string;
|
||||
checked?: boolean;
|
||||
onCheckedChange?: (event: boolean) => void;
|
||||
}
|
||||
|
||||
export const Switch = memo(({ className, onCheckedChange, checked }: SwitchProps) => {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
className={classNames(
|
||||
'relative h-6 w-11 cursor-pointer rounded-full bg-bolt-elements-button-primary-background',
|
||||
'transition-colors duration-200 ease-in-out',
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||
'data-[state=checked]:bg-bolt-elements-item-contentAccent',
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
onCheckedChange={(e) => onCheckedChange?.(e)}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
className={classNames(
|
||||
'block h-5 w-5 rounded-full bg-white',
|
||||
'shadow-lg shadow-black/20',
|
||||
'transition-transform duration-200 ease-in-out',
|
||||
'translate-x-0.5',
|
||||
'data-[state=checked]:translate-x-[1.375rem]',
|
||||
'will-change-transform',
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
);
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import { renderLogger } from '~/utils/logger';
|
||||
import { EditorPanel } from './EditorPanel';
|
||||
import { Preview } from './Preview';
|
||||
import useViewport from '~/lib/hooks';
|
||||
import Cookies from 'js-cookie';
|
||||
|
||||
interface WorkspaceProps {
|
||||
chatStarted?: boolean;
|
||||
@@ -180,21 +181,22 @@ export const Workbench = memo(({ chatStarted, isStreaming }: WorkspaceProps) =>
|
||||
return;
|
||||
}
|
||||
|
||||
const githubUsername = prompt('Please enter your GitHub username:');
|
||||
const githubUsername = Cookies.get('githubUsername');
|
||||
const githubToken = Cookies.get('githubToken');
|
||||
|
||||
if (!githubUsername) {
|
||||
alert('GitHub username is required. Push to GitHub cancelled.');
|
||||
return;
|
||||
if (!githubUsername || !githubToken) {
|
||||
const usernameInput = prompt('Please enter your GitHub username:');
|
||||
const tokenInput = prompt('Please enter your GitHub personal access token:');
|
||||
|
||||
if (!usernameInput || !tokenInput) {
|
||||
alert('GitHub username and token are required. Push to GitHub cancelled.');
|
||||
return;
|
||||
}
|
||||
|
||||
workbenchStore.pushToGitHub(repoName, usernameInput, tokenInput);
|
||||
} else {
|
||||
workbenchStore.pushToGitHub(repoName, githubUsername, githubToken);
|
||||
}
|
||||
|
||||
const githubToken = prompt('Please enter your GitHub personal access token:');
|
||||
|
||||
if (!githubToken) {
|
||||
alert('GitHub token is required. Push to GitHub cancelled.');
|
||||
return;
|
||||
}
|
||||
|
||||
workbenchStore.pushToGitHub(repoName, githubUsername, githubToken);
|
||||
}}
|
||||
>
|
||||
<div className="i-ph:github-logo" />
|
||||
|
||||
287
app/lib/hooks/useGit.ts
Normal file
287
app/lib/hooks/useGit.ts
Normal file
@@ -0,0 +1,287 @@
|
||||
import type { WebContainer } from '@webcontainer/api';
|
||||
import { useCallback, useEffect, useRef, useState, type MutableRefObject } from 'react';
|
||||
import { webcontainer as webcontainerPromise } from '~/lib/webcontainer';
|
||||
import git, { type GitAuth, type PromiseFsClient } from 'isomorphic-git';
|
||||
import http from 'isomorphic-git/http/web';
|
||||
import Cookies from 'js-cookie';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
const lookupSavedPassword = (url: string) => {
|
||||
const domain = url.split('/')[2];
|
||||
const gitCreds = Cookies.get(`git:${domain}`);
|
||||
|
||||
if (!gitCreds) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const { username, password } = JSON.parse(gitCreds || '{}');
|
||||
return { username, password };
|
||||
} catch (error) {
|
||||
console.log(`Failed to parse Git Cookie ${error}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const saveGitAuth = (url: string, auth: GitAuth) => {
|
||||
const domain = url.split('/')[2];
|
||||
Cookies.set(`git:${domain}`, JSON.stringify(auth));
|
||||
};
|
||||
|
||||
export function useGit() {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [webcontainer, setWebcontainer] = useState<WebContainer>();
|
||||
const [fs, setFs] = useState<PromiseFsClient>();
|
||||
const fileData = useRef<Record<string, { data: any; encoding?: string }>>({});
|
||||
useEffect(() => {
|
||||
webcontainerPromise.then((container) => {
|
||||
fileData.current = {};
|
||||
setWebcontainer(container);
|
||||
setFs(getFs(container, fileData));
|
||||
setReady(true);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const gitClone = useCallback(
|
||||
async (url: string) => {
|
||||
if (!webcontainer || !fs || !ready) {
|
||||
throw 'Webcontainer not initialized';
|
||||
}
|
||||
|
||||
fileData.current = {};
|
||||
await git.clone({
|
||||
fs,
|
||||
http,
|
||||
dir: webcontainer.workdir,
|
||||
url,
|
||||
depth: 1,
|
||||
singleBranch: true,
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
onAuth: (url) => {
|
||||
// let domain=url.split("/")[2]
|
||||
|
||||
let auth = lookupSavedPassword(url);
|
||||
|
||||
if (auth) {
|
||||
return auth;
|
||||
}
|
||||
|
||||
if (confirm('This repo is password protected. Ready to enter a username & password?')) {
|
||||
auth = {
|
||||
username: prompt('Enter username'),
|
||||
password: prompt('Enter password'),
|
||||
};
|
||||
return auth;
|
||||
} else {
|
||||
return { cancel: true };
|
||||
}
|
||||
},
|
||||
onAuthFailure: (url, _auth) => {
|
||||
toast.error(`Error Authenticating with ${url.split('/')[2]}`);
|
||||
},
|
||||
onAuthSuccess: (url, auth) => {
|
||||
saveGitAuth(url, auth);
|
||||
},
|
||||
});
|
||||
|
||||
const data: Record<string, { data: any; encoding?: string }> = {};
|
||||
|
||||
for (const [key, value] of Object.entries(fileData.current)) {
|
||||
data[key] = value;
|
||||
}
|
||||
|
||||
return { workdir: webcontainer.workdir, data };
|
||||
},
|
||||
[webcontainer],
|
||||
);
|
||||
|
||||
return { ready, gitClone };
|
||||
}
|
||||
|
||||
const getFs = (
|
||||
webcontainer: WebContainer,
|
||||
record: MutableRefObject<Record<string, { data: any; encoding?: string }>>,
|
||||
) => ({
|
||||
promises: {
|
||||
readFile: async (path: string, options: any) => {
|
||||
const encoding = options.encoding;
|
||||
const relativePath = pathUtils.relative(webcontainer.workdir, path);
|
||||
console.log('readFile', relativePath, encoding);
|
||||
|
||||
return await webcontainer.fs.readFile(relativePath, encoding);
|
||||
},
|
||||
writeFile: async (path: string, data: any, options: any) => {
|
||||
const encoding = options.encoding;
|
||||
const relativePath = pathUtils.relative(webcontainer.workdir, path);
|
||||
console.log('writeFile', { relativePath, data, encoding });
|
||||
|
||||
if (record.current) {
|
||||
record.current[relativePath] = { data, encoding };
|
||||
}
|
||||
|
||||
return await webcontainer.fs.writeFile(relativePath, data, { ...options, encoding });
|
||||
},
|
||||
mkdir: async (path: string, options: any) => {
|
||||
const relativePath = pathUtils.relative(webcontainer.workdir, path);
|
||||
console.log('mkdir', relativePath, options);
|
||||
|
||||
return await webcontainer.fs.mkdir(relativePath, { ...options, recursive: true });
|
||||
},
|
||||
readdir: async (path: string, options: any) => {
|
||||
const relativePath = pathUtils.relative(webcontainer.workdir, path);
|
||||
console.log('readdir', relativePath, options);
|
||||
|
||||
return await webcontainer.fs.readdir(relativePath, options);
|
||||
},
|
||||
rm: async (path: string, options: any) => {
|
||||
const relativePath = pathUtils.relative(webcontainer.workdir, path);
|
||||
console.log('rm', relativePath, options);
|
||||
|
||||
return await webcontainer.fs.rm(relativePath, { ...(options || {}) });
|
||||
},
|
||||
rmdir: async (path: string, options: any) => {
|
||||
const relativePath = pathUtils.relative(webcontainer.workdir, path);
|
||||
console.log('rmdir', relativePath, options);
|
||||
|
||||
return await webcontainer.fs.rm(relativePath, { recursive: true, ...options });
|
||||
},
|
||||
|
||||
// Mock implementations for missing functions
|
||||
unlink: async (path: string) => {
|
||||
// unlink is just removing a single file
|
||||
const relativePath = pathUtils.relative(webcontainer.workdir, path);
|
||||
return await webcontainer.fs.rm(relativePath, { recursive: false });
|
||||
},
|
||||
|
||||
stat: async (path: string) => {
|
||||
try {
|
||||
const relativePath = pathUtils.relative(webcontainer.workdir, path);
|
||||
const resp = await webcontainer.fs.readdir(pathUtils.dirname(relativePath), { withFileTypes: true });
|
||||
const name = pathUtils.basename(relativePath);
|
||||
const fileInfo = resp.find((x) => x.name == name);
|
||||
|
||||
if (!fileInfo) {
|
||||
throw new Error(`ENOENT: no such file or directory, stat '${path}'`);
|
||||
}
|
||||
|
||||
return {
|
||||
isFile: () => fileInfo.isFile(),
|
||||
isDirectory: () => fileInfo.isDirectory(),
|
||||
isSymbolicLink: () => false,
|
||||
size: 1,
|
||||
mode: 0o666, // Default permissions
|
||||
mtimeMs: Date.now(),
|
||||
uid: 1000,
|
||||
gid: 1000,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.log(error?.message);
|
||||
|
||||
const err = new Error(`ENOENT: no such file or directory, stat '${path}'`) as NodeJS.ErrnoException;
|
||||
err.code = 'ENOENT';
|
||||
err.errno = -2;
|
||||
err.syscall = 'stat';
|
||||
err.path = path;
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
|
||||
lstat: async (path: string) => {
|
||||
/*
|
||||
* For basic usage, lstat can return the same as stat
|
||||
* since we're not handling symbolic links
|
||||
*/
|
||||
return await getFs(webcontainer, record).promises.stat(path);
|
||||
},
|
||||
|
||||
readlink: async (path: string) => {
|
||||
/*
|
||||
* Since WebContainer doesn't support symlinks,
|
||||
* we'll throw a "not a symbolic link" error
|
||||
*/
|
||||
throw new Error(`EINVAL: invalid argument, readlink '${path}'`);
|
||||
},
|
||||
|
||||
symlink: async (target: string, path: string) => {
|
||||
/*
|
||||
* Since WebContainer doesn't support symlinks,
|
||||
* we'll throw a "operation not supported" error
|
||||
*/
|
||||
throw new Error(`EPERM: operation not permitted, symlink '${target}' -> '${path}'`);
|
||||
},
|
||||
|
||||
chmod: async (_path: string, _mode: number) => {
|
||||
/*
|
||||
* WebContainer doesn't support changing permissions,
|
||||
* but we can pretend it succeeded for compatibility
|
||||
*/
|
||||
return await Promise.resolve();
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const pathUtils = {
|
||||
dirname: (path: string) => {
|
||||
// Handle empty or just filename cases
|
||||
if (!path || !path.includes('/')) {
|
||||
return '.';
|
||||
}
|
||||
|
||||
// Remove trailing slashes
|
||||
path = path.replace(/\/+$/, '');
|
||||
|
||||
// Get directory part
|
||||
return path.split('/').slice(0, -1).join('/') || '/';
|
||||
},
|
||||
|
||||
basename: (path: string, ext?: string) => {
|
||||
// Remove trailing slashes
|
||||
path = path.replace(/\/+$/, '');
|
||||
|
||||
// Get the last part of the path
|
||||
const base = path.split('/').pop() || '';
|
||||
|
||||
// If extension is provided, remove it from the result
|
||||
if (ext && base.endsWith(ext)) {
|
||||
return base.slice(0, -ext.length);
|
||||
}
|
||||
|
||||
return base;
|
||||
},
|
||||
relative: (from: string, to: string): string => {
|
||||
// Handle empty inputs
|
||||
if (!from || !to) {
|
||||
return '.';
|
||||
}
|
||||
|
||||
// Normalize paths by removing trailing slashes and splitting
|
||||
const normalizePathParts = (p: string) => p.replace(/\/+$/, '').split('/').filter(Boolean);
|
||||
|
||||
const fromParts = normalizePathParts(from);
|
||||
const toParts = normalizePathParts(to);
|
||||
|
||||
// Find common parts at the start of both paths
|
||||
let commonLength = 0;
|
||||
const minLength = Math.min(fromParts.length, toParts.length);
|
||||
|
||||
for (let i = 0; i < minLength; i++) {
|
||||
if (fromParts[i] !== toParts[i]) {
|
||||
break;
|
||||
}
|
||||
|
||||
commonLength++;
|
||||
}
|
||||
|
||||
// Calculate the number of "../" needed
|
||||
const upCount = fromParts.length - commonLength;
|
||||
|
||||
// Get the remaining path parts we need to append
|
||||
const remainingPath = toParts.slice(commonLength);
|
||||
|
||||
// Construct the relative path
|
||||
const relativeParts = [...Array(upCount).fill('..'), ...remainingPath];
|
||||
|
||||
// Handle empty result case
|
||||
return relativeParts.length === 0 ? '.' : relativeParts.join('/');
|
||||
},
|
||||
};
|
||||
@@ -15,10 +15,33 @@ export interface Shortcuts {
|
||||
toggleTerminal: Shortcut;
|
||||
}
|
||||
|
||||
export interface Provider {
|
||||
name: string;
|
||||
isEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
shortcuts: Shortcuts;
|
||||
providers: Provider[];
|
||||
}
|
||||
|
||||
export const providersList: Provider[] = [
|
||||
{ name: 'Groq', isEnabled: false },
|
||||
{ name: 'HuggingFace', isEnabled: false },
|
||||
{ name: 'OpenAI', isEnabled: false },
|
||||
{ name: 'Anthropic', isEnabled: false },
|
||||
{ name: 'OpenRouter', isEnabled: false },
|
||||
{ name: 'Google', isEnabled: false },
|
||||
{ name: 'Ollama', isEnabled: false },
|
||||
{ name: 'OpenAILike', isEnabled: false },
|
||||
{ name: 'Together', isEnabled: false },
|
||||
{ name: 'Deepseek', isEnabled: false },
|
||||
{ name: 'Mistral', isEnabled: false },
|
||||
{ name: 'Cohere', isEnabled: false },
|
||||
{ name: 'LMStudio', isEnabled: false },
|
||||
{ name: 'xAI', isEnabled: false },
|
||||
];
|
||||
|
||||
export const shortcutsStore = map<Shortcuts>({
|
||||
toggleTerminal: {
|
||||
key: 'j',
|
||||
@@ -29,6 +52,7 @@ export const shortcutsStore = map<Shortcuts>({
|
||||
|
||||
export const settingsStore = map<Settings>({
|
||||
shortcuts: shortcutsStore.get(),
|
||||
providers: providersList,
|
||||
});
|
||||
|
||||
shortcutsStore.subscribe((shortcuts) => {
|
||||
|
||||
@@ -15,6 +15,7 @@ import { Octokit, type RestEndpointMethodTypes } from '@octokit/rest';
|
||||
import * as nodePath from 'node:path';
|
||||
import { extractRelativePath } from '~/utils/diff';
|
||||
import { description } from '~/lib/persistence';
|
||||
import Cookies from 'js-cookie';
|
||||
|
||||
export interface ArtifactState {
|
||||
id: string;
|
||||
@@ -396,15 +397,14 @@ export class WorkbenchStore {
|
||||
return syncedFiles;
|
||||
}
|
||||
|
||||
async pushToGitHub(repoName: string, githubUsername: string, ghToken: string) {
|
||||
async pushToGitHub(repoName: string, githubUsername?: string, ghToken?: string) {
|
||||
try {
|
||||
// Get the GitHub auth token from environment variables
|
||||
const githubToken = ghToken;
|
||||
// Use cookies if username and token are not provided
|
||||
const githubToken = ghToken || Cookies.get('githubToken');
|
||||
const owner = githubUsername || Cookies.get('githubUsername');
|
||||
|
||||
const owner = githubUsername;
|
||||
|
||||
if (!githubToken) {
|
||||
throw new Error('GitHub token is not set in environment variables');
|
||||
if (!githubToken || !owner) {
|
||||
throw new Error('GitHub token or username is not set in cookies or provided.');
|
||||
}
|
||||
|
||||
// Initialize Octokit with the auth token
|
||||
@@ -501,7 +501,8 @@ export class WorkbenchStore {
|
||||
|
||||
alert(`Repository created and code pushed: ${repo.html_url}`);
|
||||
} catch (error) {
|
||||
console.error('Error pushing to GitHub:', error instanceof Error ? error.message : String(error));
|
||||
console.error('Error pushing to GitHub:', error);
|
||||
throw error; // Rethrow the error for further handling
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
23
app/routes/git.tsx
Normal file
23
app/routes/git.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import type { LoaderFunctionArgs } from '@remix-run/cloudflare';
|
||||
import { json, type MetaFunction } from '@remix-run/cloudflare';
|
||||
import { ClientOnly } from 'remix-utils/client-only';
|
||||
import { BaseChat } from '~/components/chat/BaseChat';
|
||||
import { GitUrlImport } from '~/components/git/GitUrlImport.client';
|
||||
import { Header } from '~/components/header/Header';
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return [{ title: 'Bolt' }, { name: 'description', content: 'Talk with Bolt, an AI assistant from StackBlitz' }];
|
||||
};
|
||||
|
||||
export async function loader(args: LoaderFunctionArgs) {
|
||||
return json({ url: args.params.url });
|
||||
}
|
||||
|
||||
export default function Index() {
|
||||
return (
|
||||
<div className="flex flex-col h-full w-full">
|
||||
<Header />
|
||||
<ClientOnly fallback={<BaseChat />}>{() => <GitUrlImport />}</ClientOnly>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,4 +7,5 @@ export type ProviderInfo = {
|
||||
getApiKeyLink?: string;
|
||||
labelForGetApiKey?: string;
|
||||
icon?: string;
|
||||
isEnabled?: boolean;
|
||||
};
|
||||
|
||||
@@ -127,7 +127,7 @@ const PROVIDER_LIST: ProviderInfo[] = [
|
||||
{ name: 'gemini-1.5-flash-8b', label: 'Gemini 1.5 Flash-8b', provider: 'Google', maxTokenAllowed: 8192 },
|
||||
{ name: 'gemini-1.5-pro-latest', label: 'Gemini 1.5 Pro', provider: 'Google', maxTokenAllowed: 8192 },
|
||||
{ name: 'gemini-1.5-pro-002', label: 'Gemini 1.5 Pro-002', provider: 'Google', maxTokenAllowed: 8192 },
|
||||
{ name: 'gemini-exp-1121', label: 'Gemini exp-1121', provider: 'Google', maxTokenAllowed: 8192 },
|
||||
{ name: 'gemini-exp-1206', label: 'Gemini exp-1206', provider: 'Google', maxTokenAllowed: 8192 },
|
||||
],
|
||||
getApiKeyLink: 'https://aistudio.google.com/app/apikey',
|
||||
},
|
||||
|
||||
105
app/utils/fileUtils.ts
Normal file
105
app/utils/fileUtils.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import ignore from 'ignore';
|
||||
|
||||
// Common patterns to ignore, similar to .gitignore
|
||||
export const IGNORE_PATTERNS = [
|
||||
'node_modules/**',
|
||||
'.git/**',
|
||||
'dist/**',
|
||||
'build/**',
|
||||
'.next/**',
|
||||
'coverage/**',
|
||||
'.cache/**',
|
||||
'.vscode/**',
|
||||
'.idea/**',
|
||||
'**/*.log',
|
||||
'**/.DS_Store',
|
||||
'**/npm-debug.log*',
|
||||
'**/yarn-debug.log*',
|
||||
'**/yarn-error.log*',
|
||||
];
|
||||
|
||||
export const MAX_FILES = 1000;
|
||||
export const ig = ignore().add(IGNORE_PATTERNS);
|
||||
|
||||
export const generateId = () => Math.random().toString(36).substring(2, 15);
|
||||
|
||||
export const isBinaryFile = async (file: File): Promise<boolean> => {
|
||||
const chunkSize = 1024;
|
||||
const buffer = new Uint8Array(await file.slice(0, chunkSize).arrayBuffer());
|
||||
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
const byte = buffer[i];
|
||||
|
||||
if (byte === 0 || (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
export const shouldIncludeFile = (path: string): boolean => {
|
||||
return !ig.ignores(path);
|
||||
};
|
||||
|
||||
const readPackageJson = async (files: File[]): Promise<{ scripts?: Record<string, string> } | null> => {
|
||||
const packageJsonFile = files.find((f) => f.webkitRelativePath.endsWith('package.json'));
|
||||
|
||||
if (!packageJsonFile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result as string);
|
||||
reader.onerror = reject;
|
||||
reader.readAsText(packageJsonFile);
|
||||
});
|
||||
|
||||
return JSON.parse(content);
|
||||
} catch (error) {
|
||||
console.error('Error reading package.json:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const detectProjectType = async (
|
||||
files: File[],
|
||||
): Promise<{ type: string; setupCommand: string; followupMessage: string }> => {
|
||||
const hasFile = (name: string) => files.some((f) => f.webkitRelativePath.endsWith(name));
|
||||
|
||||
if (hasFile('package.json')) {
|
||||
const packageJson = await readPackageJson(files);
|
||||
const scripts = packageJson?.scripts || {};
|
||||
|
||||
// Check for preferred commands in priority order
|
||||
const preferredCommands = ['dev', 'start', 'preview'];
|
||||
const availableCommand = preferredCommands.find((cmd) => scripts[cmd]);
|
||||
|
||||
if (availableCommand) {
|
||||
return {
|
||||
type: 'Node.js',
|
||||
setupCommand: `npm install && npm run ${availableCommand}`,
|
||||
followupMessage: `Found "${availableCommand}" script in package.json. Running "npm run ${availableCommand}" after installation.`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'Node.js',
|
||||
setupCommand: 'npm install',
|
||||
followupMessage:
|
||||
'Would you like me to inspect package.json to determine the available scripts for running this project?',
|
||||
};
|
||||
}
|
||||
|
||||
if (hasFile('index.html')) {
|
||||
return {
|
||||
type: 'Static',
|
||||
setupCommand: 'npx --yes serve',
|
||||
followupMessage: '',
|
||||
};
|
||||
}
|
||||
|
||||
return { type: '', setupCommand: '', followupMessage: '' };
|
||||
};
|
||||
68
app/utils/folderImport.ts
Normal file
68
app/utils/folderImport.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import type { Message } from 'ai';
|
||||
import { generateId } from './fileUtils';
|
||||
import { detectProjectCommands, createCommandsMessage } from './projectCommands';
|
||||
|
||||
export const createChatFromFolder = async (
|
||||
files: File[],
|
||||
binaryFiles: string[],
|
||||
folderName: string,
|
||||
): Promise<Message[]> => {
|
||||
const fileArtifacts = await Promise.all(
|
||||
files.map(async (file) => {
|
||||
return new Promise<{ content: string; path: string }>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = () => {
|
||||
const content = reader.result as string;
|
||||
const relativePath = file.webkitRelativePath.split('/').slice(1).join('/');
|
||||
resolve({
|
||||
content,
|
||||
path: relativePath,
|
||||
});
|
||||
};
|
||||
reader.onerror = reject;
|
||||
reader.readAsText(file);
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const commands = await detectProjectCommands(fileArtifacts);
|
||||
const commandsMessage = createCommandsMessage(commands);
|
||||
|
||||
const binaryFilesMessage =
|
||||
binaryFiles.length > 0
|
||||
? `\n\nSkipped ${binaryFiles.length} binary files:\n${binaryFiles.map((f) => `- ${f}`).join('\n')}`
|
||||
: '';
|
||||
|
||||
const filesMessage: Message = {
|
||||
role: 'assistant',
|
||||
content: `I've imported the contents of the "${folderName}" folder.${binaryFilesMessage}
|
||||
|
||||
<boltArtifact id="imported-files" title="Imported Files">
|
||||
${fileArtifacts
|
||||
.map(
|
||||
(file) => `<boltAction type="file" filePath="${file.path}">
|
||||
${file.content}
|
||||
</boltAction>`,
|
||||
)
|
||||
.join('\n\n')}
|
||||
</boltArtifact>`,
|
||||
id: generateId(),
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
const userMessage: Message = {
|
||||
role: 'user',
|
||||
id: generateId(),
|
||||
content: `Import the "${folderName}" folder`,
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
const messages = [userMessage, filesMessage];
|
||||
|
||||
if (commandsMessage) {
|
||||
messages.push(commandsMessage);
|
||||
}
|
||||
|
||||
return messages;
|
||||
};
|
||||
80
app/utils/projectCommands.ts
Normal file
80
app/utils/projectCommands.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import type { Message } from 'ai';
|
||||
import { generateId } from './fileUtils';
|
||||
|
||||
export interface ProjectCommands {
|
||||
type: string;
|
||||
setupCommand: string;
|
||||
followupMessage: string;
|
||||
}
|
||||
|
||||
interface FileContent {
|
||||
content: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export async function detectProjectCommands(files: FileContent[]): Promise<ProjectCommands> {
|
||||
const hasFile = (name: string) => files.some((f) => f.path.endsWith(name));
|
||||
|
||||
if (hasFile('package.json')) {
|
||||
const packageJsonFile = files.find((f) => f.path.endsWith('package.json'));
|
||||
|
||||
if (!packageJsonFile) {
|
||||
return { type: '', setupCommand: '', followupMessage: '' };
|
||||
}
|
||||
|
||||
try {
|
||||
const packageJson = JSON.parse(packageJsonFile.content);
|
||||
const scripts = packageJson?.scripts || {};
|
||||
|
||||
// Check for preferred commands in priority order
|
||||
const preferredCommands = ['dev', 'start', 'preview'];
|
||||
const availableCommand = preferredCommands.find((cmd) => scripts[cmd]);
|
||||
|
||||
if (availableCommand) {
|
||||
return {
|
||||
type: 'Node.js',
|
||||
setupCommand: `npm install && npm run ${availableCommand}`,
|
||||
followupMessage: `Found "${availableCommand}" script in package.json. Running "npm run ${availableCommand}" after installation.`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'Node.js',
|
||||
setupCommand: 'npm install',
|
||||
followupMessage:
|
||||
'Would you like me to inspect package.json to determine the available scripts for running this project?',
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error parsing package.json:', error);
|
||||
return { type: '', setupCommand: '', followupMessage: '' };
|
||||
}
|
||||
}
|
||||
|
||||
if (hasFile('index.html')) {
|
||||
return {
|
||||
type: 'Static',
|
||||
setupCommand: 'npx --yes serve',
|
||||
followupMessage: '',
|
||||
};
|
||||
}
|
||||
|
||||
return { type: '', setupCommand: '', followupMessage: '' };
|
||||
}
|
||||
|
||||
export function createCommandsMessage(commands: ProjectCommands): Message | null {
|
||||
if (!commands.setupCommand) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
role: 'assistant',
|
||||
content: `
|
||||
<boltArtifact id="project-setup" title="Project Setup">
|
||||
<boltAction type="shell">
|
||||
${commands.setupCommand}
|
||||
</boltAction>
|
||||
</boltArtifact>${commands.followupMessage ? `\n\n${commands.followupMessage}` : ''}`,
|
||||
id: generateId(),
|
||||
createdAt: new Date(),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user