add install ollama models , fixes

This commit is contained in:
Stijnus 2025-01-28 22:57:06 +01:00
parent f32016c91d
commit 0765bc3173
19 changed files with 1496 additions and 715 deletions

View File

@ -251,31 +251,67 @@ export const ChatImpl = memo(
const sendMessage = async (_event: React.UIEvent, messageInput?: string) => {
const _input = messageInput || input;
if (_input.length === 0 || isLoading) {
if (!_input) {
return;
}
/**
* @note (delm) Usually saving files shouldn't take long but it may take longer if there
* many unsaved files. In that case we need to block user input and show an indicator
* of some kind so the user is aware that something is happening. But I consider the
* happy case to be no unsaved files and I would expect users to save their changes
* before they send another message.
*/
await workbenchStore.saveAllFiles();
if (error != null) {
setMessages(messages.slice(0, -1));
if (isLoading) {
abort();
return;
}
const fileModifications = workbenchStore.getFileModifcations();
chatStore.setKey('aborted', false);
runAnimation();
if (!chatStarted && _input && autoSelectTemplate) {
if (!chatStarted) {
setFakeLoading(true);
if (autoSelectTemplate) {
const { template, title } = await selectStarterTemplate({
message: _input,
model,
provider,
});
if (template !== 'blank') {
const temResp = await getTemplates(template, title).catch((e) => {
if (e.message.includes('rate limit')) {
toast.warning('Rate limit exceeded. Skipping starter template\n Continuing with blank template');
} else {
toast.warning('Failed to import starter template\n Continuing with blank template');
}
return null;
});
if (temResp) {
const { assistantMessage, userMessage } = temResp;
setMessages([
{
id: `${new Date().getTime()}`,
role: 'user',
content: _input,
},
{
id: `${new Date().getTime()}`,
role: 'assistant',
content: assistantMessage,
},
{
id: `${new Date().getTime()}`,
role: 'user',
content: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${userMessage}`,
annotations: ['hidden'],
},
]);
reload();
setFakeLoading(false);
return;
}
}
}
// If autoSelectTemplate is disabled or template selection failed, proceed with normal message
setMessages([
{
id: `${new Date().getTime()}`,
@ -289,103 +325,23 @@ export const ChatImpl = memo(
type: 'image',
image: imageData,
})),
] as any, // Type assertion to bypass compiler check
] as any,
},
]);
reload();
setFakeLoading(false);
// reload();
const { template, title } = await selectStarterTemplate({
message: _input,
model,
provider,
});
if (template !== 'blank') {
const temResp = await getTemplates(template, title).catch((e) => {
if (e.message.includes('rate limit')) {
toast.warning('Rate limit exceeded. Skipping starter template\n Continuing with blank template');
} else {
toast.warning('Failed to import starter template\n Continuing with blank template');
}
return null;
});
if (temResp) {
const { assistantMessage, userMessage } = temResp;
setMessages([
{
id: `${new Date().getTime()}`,
role: 'user',
content: _input,
// annotations: ['hidden'],
},
{
id: `${new Date().getTime()}`,
role: 'assistant',
content: assistantMessage,
},
{
id: `${new Date().getTime()}`,
role: 'user',
content: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${userMessage}`,
annotations: ['hidden'],
},
]);
reload();
setFakeLoading(false);
return;
} else {
setMessages([
{
id: `${new Date().getTime()}`,
role: 'user',
content: [
{
type: 'text',
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}`,
},
...imageDataList.map((imageData) => ({
type: 'image',
image: imageData,
})),
] as any, // Type assertion to bypass compiler check
},
]);
reload();
setFakeLoading(false);
return;
}
} else {
setMessages([
{
id: `${new Date().getTime()}`,
role: 'user',
content: [
{
type: 'text',
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}`,
},
...imageDataList.map((imageData) => ({
type: 'image',
image: imageData,
})),
] as any, // Type assertion to bypass compiler check
},
]);
reload();
setFakeLoading(false);
return;
}
return;
}
if (error != null) {
setMessages(messages.slice(0, -1));
}
const fileModifications = workbenchStore.getFileModifcations();
chatStore.setKey('aborted', false);
if (fileModifications !== undefined) {
/**
* If we have file modifications we append a new user message manually since we have to prefix

View File

@ -385,242 +385,247 @@ export const DeveloperWindow = ({ open, onClose }: DeveloperWindowProps) => {
}, [open]);
return (
<DndProvider backend={HTML5Backend}>
<RadixDialog.Root open={open}>
<RadixDialog.Portal>
<div className="fixed inset-0 flex items-center justify-center z-[100]">
<RadixDialog.Overlay className="fixed inset-0">
<motion.div
className="absolute inset-0 bg-black/50 backdrop-blur-sm"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
/>
</RadixDialog.Overlay>
<RadixDialog.Content
aria-describedby={undefined}
onEscapeKeyDown={onClose}
onPointerDownOutside={onClose}
className="relative z-[101]"
<>
<DropdownMenu.Root>
<DropdownMenu.Portal>
<DropdownMenu.Content
className="min-w-[220px] bg-white dark:bg-gray-800 rounded-lg shadow-lg py-1 z-[200] animate-in fade-in-0 zoom-in-95"
sideOffset={5}
align="end"
>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('profile')}
>
<motion.div
className={classNames(
'w-[1200px] h-[90vh]',
'bg-[#FAFAFA] dark:bg-[#0A0A0A]',
'rounded-2xl shadow-2xl',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
'flex flex-col overflow-hidden',
)}
initial={{ opacity: 0, scale: 0.95, y: 20 }}
animate={{ opacity: developerMode ? 1 : 0, scale: developerMode ? 1 : 0.95, y: developerMode ? 0 : 20 }}
exit={{ opacity: 0, scale: 0.95, y: 20 }}
transition={{ duration: 0.2 }}
>
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center space-x-4">
{activeTab || showTabManagement ? (
<button
onClick={handleBack}
className="flex items-center justify-center w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
>
<div className="i-ph:arrow-left w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</button>
) : (
<motion.div
className="i-ph:lightning-fill w-5 h-5 text-purple-500"
initial={{ rotate: -10 }}
animate={{ rotate: 10 }}
transition={{
repeat: Infinity,
repeatType: 'reverse',
duration: 2,
ease: 'easeInOut',
}}
/>
)}
<DialogTitle className="text-xl font-semibold text-gray-900 dark:text-white">
{showTabManagement ? 'Tab Management' : activeTab ? 'Developer Tools' : 'Developer Settings'}
</DialogTitle>
</div>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:user-circle w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Profile</span>
</DropdownMenu.Item>
<div className="flex items-center space-x-4">
{!activeTab && !showTabManagement && (
<motion.button
onClick={() => setShowTabManagement(true)}
className="flex items-center space-x-2 px-3 py-1.5 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
<div className="i-ph:sliders-horizontal w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
<span className="text-sm text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors">
Manage Tabs
</span>
</motion.button>
)}
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('settings')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:gear w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Settings</span>
</DropdownMenu.Item>
<div className="flex items-center gap-2">
<Switch
checked={developerMode}
onCheckedChange={handleDeveloperModeChange}
className="data-[state=checked]:bg-purple-500"
aria-label="Toggle developer mode"
/>
<label className="text-sm text-gray-500 dark:text-gray-400">Switch to User Mode</label>
</div>
<div className="relative">
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<button className="flex items-center justify-center w-8 h-8 rounded-full overflow-hidden hover:ring-2 ring-gray-300 dark:ring-gray-600 transition-all">
{profile.avatar ? (
<img src={profile.avatar} alt="Profile" className="w-full h-full object-cover" />
) : (
<div className="w-full h-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
<svg
className="w-5 h-5 text-gray-500 dark:text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
/>
</svg>
</div>
)}
</button>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
className="min-w-[220px] bg-white dark:bg-gray-800 rounded-lg shadow-lg py-1 z-[200]"
sideOffset={5}
align="end"
>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('profile')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:user-circle w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Profile</span>
</DropdownMenu.Item>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('settings')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:gear w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Settings</span>
</DropdownMenu.Item>
{profile.notifications && (
<>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('notifications')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:bell w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">
Notifications
{hasUnreadNotifications && (
<span className="ml-2 px-1.5 py-0.5 text-xs bg-purple-500 text-white rounded-full">
{unreadNotifications.length}
</span>
)}
</span>
</DropdownMenu.Item>
<DropdownMenu.Separator className="my-1 h-px bg-gray-200 dark:bg-gray-700" />
</>
)}
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('task-manager')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:activity w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Task Manager</span>
</DropdownMenu.Item>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={onClose}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:sign-out w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Close</span>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
</div>
<button
onClick={onClose}
className="flex items-center justify-center w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
>
<div className="i-ph:x w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</button>
</div>
</div>
{/* Content */}
<div
className={classNames(
'flex-1',
'overflow-y-auto',
'hover:overflow-y-auto',
'scrollbar scrollbar-w-2',
'scrollbar-track-transparent',
'scrollbar-thumb-[#E5E5E5] hover:scrollbar-thumb-[#CCCCCC]',
'dark:scrollbar-thumb-[#333333] dark:hover:scrollbar-thumb-[#444444]',
'will-change-scroll',
'touch-auto',
)}
{profile.notifications && (
<>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('notifications')}
>
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="p-6">
{showTabManagement ? (
<TabManagement />
) : activeTab ? (
getTabComponent()
) : (
<div className="grid grid-cols-4 gap-4">
{visibleDeveloperTabs.map((tab: TabVisibilityConfig, index: number) => (
<DraggableTabTile
key={tab.id}
tab={tab}
index={index}
moveTab={moveTab}
onClick={() => handleTabClick(tab.id)}
isActive={activeTab === tab.id}
hasUpdate={getTabUpdateStatus(tab.id)}
statusMessage={getStatusMessage(tab.id)}
description={TAB_DESCRIPTIONS[tab.id]}
isLoading={loadingTab === tab.id}
/>
))}
</div>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:bell w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">
Notifications
{hasUnreadNotifications && (
<span className="ml-2 px-1.5 py-0.5 text-xs bg-purple-500 text-white rounded-full">
{unreadNotifications.length}
</span>
)}
</span>
</DropdownMenu.Item>
<DropdownMenu.Separator className="my-1 h-px bg-gray-200 dark:bg-gray-700" />
</>
)}
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('task-manager')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:activity w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Task Manager</span>
</DropdownMenu.Item>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={onClose}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:sign-out w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Close</span>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
<DndProvider backend={HTML5Backend}>
<RadixDialog.Root open={open}>
<RadixDialog.Portal>
<div className="fixed inset-0 flex items-center justify-center z-[100]">
<RadixDialog.Overlay className="fixed inset-0">
<motion.div
className="absolute inset-0 bg-black/50 backdrop-blur-sm"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
/>
</RadixDialog.Overlay>
<RadixDialog.Content
aria-describedby={undefined}
onEscapeKeyDown={onClose}
onPointerDownOutside={onClose}
className="relative z-[101]"
>
<motion.div
className={classNames(
'w-[1200px] h-[90vh]',
'bg-[#FAFAFA] dark:bg-[#0A0A0A]',
'rounded-2xl shadow-2xl',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
'flex flex-col overflow-hidden',
)}
initial={{ opacity: 0, scale: 0.95, y: 20 }}
animate={{
opacity: developerMode ? 1 : 0,
scale: developerMode ? 1 : 0.95,
y: developerMode ? 0 : 20,
}}
exit={{ opacity: 0, scale: 0.95, y: 20 }}
transition={{ duration: 0.2 }}
>
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center space-x-4">
{activeTab || showTabManagement ? (
<button
onClick={handleBack}
className="flex items-center justify-center w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
>
<div className="i-ph:arrow-left w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</button>
) : (
<motion.div
className="i-ph:lightning-fill w-5 h-5 text-purple-500"
initial={{ rotate: -10 }}
animate={{ rotate: 10 }}
transition={{
repeat: Infinity,
repeatType: 'reverse',
duration: 2,
ease: 'easeInOut',
}}
/>
)}
<DialogTitle className="text-xl font-semibold text-gray-900 dark:text-white">
{showTabManagement ? 'Tab Management' : activeTab ? 'Developer Tools' : 'Developer Settings'}
</DialogTitle>
</div>
<div className="flex items-center space-x-4">
{!activeTab && !showTabManagement && (
<motion.button
onClick={() => setShowTabManagement(true)}
className="flex items-center space-x-2 px-3 py-1.5 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
<div className="i-ph:sliders-horizontal w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
<span className="text-sm text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors">
Manage Tabs
</span>
</motion.button>
)}
<div className="flex items-center gap-2">
<Switch
checked={developerMode}
onCheckedChange={handleDeveloperModeChange}
className="data-[state=checked]:bg-purple-500"
aria-label="Toggle developer mode"
/>
<label className="text-sm text-gray-500 dark:text-gray-400">Switch to User Mode</label>
</div>
<div className="relative">
<DropdownMenu.Trigger asChild>
<button className="flex items-center justify-center w-8 h-8 rounded-full overflow-hidden hover:ring-2 ring-gray-300 dark:ring-gray-600 transition-all">
{profile.avatar ? (
<img src={profile.avatar} alt="Profile" className="w-full h-full object-cover" />
) : (
<div className="w-full h-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
<svg
className="w-5 h-5 text-gray-500 dark:text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
/>
</svg>
</div>
)}
</button>
</DropdownMenu.Trigger>
</div>
<button
onClick={onClose}
className="flex items-center justify-center w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
>
<div className="i-ph:x w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</button>
</div>
</div>
{/* Content */}
<div
className={classNames(
'flex-1',
'overflow-y-auto',
'hover:overflow-y-auto',
'scrollbar scrollbar-w-2',
'scrollbar-track-transparent',
'scrollbar-thumb-[#E5E5E5] hover:scrollbar-thumb-[#CCCCCC]',
'dark:scrollbar-thumb-[#333333] dark:hover:scrollbar-thumb-[#444444]',
'will-change-scroll',
'touch-auto',
)}
>
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="p-6">
{showTabManagement ? (
<TabManagement />
) : activeTab ? (
getTabComponent()
) : (
<div className="grid grid-cols-4 gap-4">
{visibleDeveloperTabs.map((tab: TabVisibilityConfig, index: number) => (
<DraggableTabTile
key={tab.id}
tab={tab}
index={index}
moveTab={moveTab}
onClick={() => handleTabClick(tab.id)}
isActive={activeTab === tab.id}
hasUpdate={getTabUpdateStatus(tab.id)}
statusMessage={getStatusMessage(tab.id)}
description={TAB_DESCRIPTIONS[tab.id]}
isLoading={loadingTab === tab.id}
/>
))}
</div>
)}
</motion.div>
</div>
</motion.div>
</div>
</motion.div>
</RadixDialog.Content>
</div>
</RadixDialog.Portal>
</RadixDialog.Root>
</DndProvider>
</RadixDialog.Content>
</div>
</RadixDialog.Portal>
</RadixDialog.Root>
</DndProvider>
</DropdownMenu.Root>
</>
);
};

View File

@ -6,13 +6,14 @@ import { classNames } from '~/utils/classNames';
import { toast } from 'react-toastify';
import { PromptLibrary } from '~/lib/common/prompt-library';
import {
isEventLogsEnabled,
latestBranchStore,
autoSelectStarterTemplate,
enableContextOptimizationStore,
isLocalModelsEnabled,
latestBranchStore as latestBranchAtom,
isEventLogsEnabled,
promptStore as promptAtom,
autoSelectStarterTemplate as autoSelectTemplateAtom,
enableContextOptimizationStore as contextOptimizationAtom,
} from '~/lib/stores/settings';
import { logStore } from '~/lib/stores/logs';
interface FeatureToggle {
id: string;
@ -115,14 +116,6 @@ const FeatureSection = memo(
export default function FeaturesTab() {
const { autoSelectTemplate, isLatestBranch, contextOptimizationEnabled, eventLogs, isLocalModel } = useSettings();
// Setup store setters
const setEventLogs = (value: boolean) => isEventLogsEnabled.set(value);
const setLocalModels = (value: boolean) => isLocalModelsEnabled.set(value);
const setLatestBranch = (value: boolean) => latestBranchAtom.set(value);
const setPromptId = (value: string) => promptAtom.set(value);
const setAutoSelectTemplate = (value: boolean) => autoSelectTemplateAtom.set(value);
const setContextOptimization = (value: boolean) => contextOptimizationAtom.set(value);
const getLocalStorageBoolean = (key: string, defaultValue: boolean): boolean => {
const value = localStorage.getItem(key);
@ -137,7 +130,6 @@ export default function FeaturesTab() {
}
};
// Initialize state with proper type handling
const autoSelectTemplateState = getLocalStorageBoolean('autoSelectTemplate', autoSelectTemplate);
const enableLatestBranchState = getLocalStorageBoolean('enableLatestBranch', isLatestBranch);
const contextOptimizationState = getLocalStorageBoolean('contextOptimization', contextOptimizationEnabled);
@ -155,7 +147,6 @@ export default function FeaturesTab() {
const [promptIdLocal, setPromptIdLocal] = useState(promptIdState);
useEffect(() => {
// Update localStorage
localStorage.setItem('autoSelectTemplate', JSON.stringify(autoSelectTemplateLocal));
localStorage.setItem('enableLatestBranch', JSON.stringify(enableLatestBranchLocal));
localStorage.setItem('contextOptimization', JSON.stringify(contextOptimizationLocal));
@ -164,13 +155,12 @@ export default function FeaturesTab() {
localStorage.setItem('promptLibrary', JSON.stringify(promptLibraryLocal));
localStorage.setItem('promptId', promptIdLocal);
// Update global state
setEventLogs(eventLogsLocal);
setLocalModels(experimentalProvidersLocal);
setLatestBranch(enableLatestBranchLocal);
setPromptId(promptIdLocal);
setAutoSelectTemplate(autoSelectTemplateLocal);
setContextOptimization(contextOptimizationLocal);
autoSelectStarterTemplate.set(autoSelectTemplateLocal);
latestBranchStore.set(enableLatestBranchLocal);
enableContextOptimizationStore.set(contextOptimizationLocal);
isEventLogsEnabled.set(eventLogsLocal);
isLocalModelsEnabled.set(experimentalProvidersLocal);
promptAtom.set(promptIdLocal);
}, [
autoSelectTemplateLocal,
enableLatestBranchLocal,
@ -182,27 +172,34 @@ export default function FeaturesTab() {
]);
const handleToggleFeature = (featureId: string, enabled: boolean) => {
logStore.logFeatureToggle(featureId, enabled);
switch (featureId) {
case 'latestBranch':
setEnableLatestBranchLocal(enabled);
latestBranchStore.set(enabled);
toast.success(`Main branch updates ${enabled ? 'enabled' : 'disabled'}`);
break;
case 'autoTemplate':
case 'autoSelectTemplate':
setAutoSelectTemplateLocal(enabled);
autoSelectStarterTemplate.set(enabled);
toast.success(`Auto template selection ${enabled ? 'enabled' : 'disabled'}`);
break;
case 'contextOptimization':
setContextOptimizationLocal(enabled);
enableContextOptimizationStore.set(enabled);
toast.success(`Context optimization ${enabled ? 'enabled' : 'disabled'}`);
break;
case 'localModels':
setExperimentalProvidersLocal(enabled);
isLocalModelsEnabled.set(enabled);
toast.success(`Experimental providers ${enabled ? 'enabled' : 'disabled'}`);
break;
case 'eventLogs':
setEventLogsLocal(enabled);
isEventLogsEnabled.set(enabled);
toast.success(`Event logging ${enabled ? 'enabled' : 'disabled'}`);
break;
case 'experimentalProviders':
setExperimentalProvidersLocal(enabled);
toast.success(`Experimental providers ${enabled ? 'enabled' : 'disabled'}`);
break;
case 'promptLibrary':
setPromptLibraryLocal(enabled);
toast.success(`Prompt Library ${enabled ? 'enabled' : 'disabled'}`);
@ -213,7 +210,7 @@ export default function FeaturesTab() {
const features: Record<'stable' | 'beta' | 'experimental', FeatureToggle[]> = {
stable: [
{
id: 'autoTemplate',
id: 'autoSelectTemplate',
title: 'Auto Select Code Template',
description: 'Let Bolt select the best starter template for your project',
icon: 'i-ph:magic-wand',
@ -245,20 +242,10 @@ export default function FeaturesTab() {
tooltip: 'Enable or disable the prompt library',
},
],
beta: [
{
id: 'latestBranch',
title: 'Use Main Branch',
description: 'Check for updates against the main branch instead of stable',
icon: 'i-ph:git-branch',
enabled: enableLatestBranchLocal,
beta: true,
tooltip: 'Get the latest features and improvements before they are officially released',
},
],
beta: [],
experimental: [
{
id: 'experimentalProviders',
id: 'localModels',
title: 'Experimental Providers',
description: 'Enable experimental providers like Ollama, LMStudio, and OpenAILike',
icon: 'i-ph:robot',

View File

@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { logStore } from '~/lib/stores/logs';
import { useStore } from '@nanostores/react';
@ -21,14 +21,47 @@ const NotificationsTab = () => {
const [filter, setFilter] = useState<FilterType>('all');
const logs = useStore(logStore.logs);
useEffect(() => {
const startTime = performance.now();
return () => {
const duration = performance.now() - startTime;
logStore.logPerformanceMetric('NotificationsTab', 'mount-duration', duration);
};
}, []);
const handleClearNotifications = () => {
const count = Object.keys(logs).length;
logStore.logInfo('Cleared notifications', {
type: 'notification_clear',
message: `Cleared ${count} notifications`,
clearedCount: count,
component: 'notifications',
});
logStore.clearLogs();
};
const handleUpdateAction = (updateUrl: string) => {
logStore.logInfo('Update link clicked', {
type: 'update_click',
message: 'User clicked update link',
updateUrl,
component: 'notifications',
});
window.open(updateUrl, '_blank');
};
const handleFilterChange = (newFilter: FilterType) => {
logStore.logInfo('Notification filter changed', {
type: 'filter_change',
message: `Filter changed to ${newFilter}`,
previousFilter: filter,
newFilter,
component: 'notifications',
});
setFilter(newFilter);
};
const filteredLogs = Object.values(logs)
.filter((log) => {
if (filter === 'all') {
@ -172,7 +205,7 @@ const NotificationsTab = () => {
<DropdownMenu.Item
key={option.id}
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onClick={() => setFilter(option.id)}
onClick={() => handleFilterChange(option.id)}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div

View File

@ -7,20 +7,20 @@ import { logStore } from '~/lib/stores/logs';
import { motion } from 'framer-motion';
import { classNames } from '~/utils/classNames';
import { settingsStyles } from '~/components/settings/settings.styles';
import { toast } from 'react-toastify';
import { BsBox, BsCodeSquare, BsRobot } from 'react-icons/bs';
import { BsRobot } from 'react-icons/bs';
import type { IconType } from 'react-icons';
import { BiChip } from 'react-icons/bi';
import { TbBrandOpenai } from 'react-icons/tb';
import { providerBaseUrlEnvKeys } from '~/utils/constants';
import { useToast } from '~/components/ui/use-toast';
// Add type for provider names to ensure type safety
type ProviderName = 'Ollama' | 'LMStudio' | 'OpenAILike';
// Update the PROVIDER_ICONS type to use the ProviderName type
const PROVIDER_ICONS: Record<ProviderName, IconType> = {
Ollama: BsBox,
LMStudio: BsCodeSquare,
Ollama: BsRobot,
LMStudio: BsRobot,
OpenAILike: TbBrandOpenai,
};
@ -31,6 +31,9 @@ const PROVIDER_DESCRIPTIONS: Record<ProviderName, string> = {
OpenAILike: 'Connect to OpenAI-compatible API endpoints',
};
// Add a constant for the Ollama API base URL
const OLLAMA_API_URL = 'http://127.0.0.1:11434';
interface OllamaModel {
name: string;
digest: string;
@ -51,17 +54,59 @@ interface OllamaModel {
};
}
const LocalProvidersTab = () => {
const settings = useSettings();
interface OllamaServiceStatus {
isRunning: boolean;
lastChecked: Date;
error?: string;
}
interface OllamaPullResponse {
status: string;
completed?: number;
total?: number;
digest?: string;
}
const isOllamaPullResponse = (data: unknown): data is OllamaPullResponse => {
return (
typeof data === 'object' &&
data !== null &&
'status' in data &&
typeof (data as OllamaPullResponse).status === 'string'
);
};
interface ManualInstallState {
isOpen: boolean;
modelString: string;
}
export function LocalProvidersTab() {
const { success, error } = useToast();
const { providers, updateProviderSettings } = useSettings();
const [filteredProviders, setFilteredProviders] = useState<IProviderConfig[]>([]);
const [categoryEnabled, setCategoryEnabled] = useState<boolean>(false);
const [editingProvider, setEditingProvider] = useState<string | null>(null);
const [ollamaModels, setOllamaModels] = useState<OllamaModel[]>([]);
const [isLoadingModels, setIsLoadingModels] = useState(false);
const [serviceStatus, setServiceStatus] = useState<OllamaServiceStatus>({
isRunning: false,
lastChecked: new Date(),
});
const [isInstallingModel, setIsInstallingModel] = useState<string | null>(null);
const [installProgress, setInstallProgress] = useState<{
model: string;
progress: number;
status: string;
} | null>(null);
const [manualInstall, setManualInstall] = useState<ManualInstallState>({
isOpen: false,
modelString: '',
});
// Effect to filter and sort providers
useEffect(() => {
const newFilteredProviders = Object.entries(settings.providers || {})
const newFilteredProviders = Object.entries(providers || {})
.filter(([key]) => [...LOCAL_PROVIDERS, 'OpenAILike'].includes(key))
.map(([key, value]) => {
const provider = value as IProviderConfig;
@ -79,7 +124,7 @@ const LocalProvidersTab = () => {
// If there's an environment URL and no base URL set, update it
if (envUrl && !provider.settings.baseUrl) {
console.log(`Setting base URL for ${key} from env:`, envUrl);
settings.updateProviderSettings(key, {
updateProviderSettings(key, {
...provider.settings,
baseUrl: envUrl,
});
@ -120,7 +165,7 @@ const LocalProvidersTab = () => {
return a.name.localeCompare(b.name);
});
setFilteredProviders(sorted);
}, [settings.providers]);
}, [providers, updateProviderSettings]);
// Helper function to safely get environment URL
const getEnvUrl = (provider: IProviderConfig): string | undefined => {
@ -165,7 +210,7 @@ const LocalProvidersTab = () => {
const updateOllamaModel = async (modelName: string): Promise<{ success: boolean; newDigest?: string }> => {
try {
const response = await fetch('http://127.0.0.1:11434/api/pull', {
const response = await fetch(`${OLLAMA_API_URL}/api/pull`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: modelName }),
@ -192,12 +237,12 @@ const LocalProvidersTab = () => {
const lines = text.split('\n').filter(Boolean);
for (const line of lines) {
const data = JSON.parse(line) as {
status: string;
completed?: number;
total?: number;
digest?: string;
};
const rawData = JSON.parse(line);
if (!isOllamaPullResponse(rawData)) {
console.error('Invalid response format:', rawData);
continue;
}
setOllamaModels((current) =>
current.map((m) =>
@ -205,11 +250,11 @@ const LocalProvidersTab = () => {
? {
...m,
progress: {
current: data.completed || 0,
total: data.total || 0,
status: data.status,
current: rawData.completed || 0,
total: rawData.total || 0,
status: rawData.status,
},
newDigest: data.digest,
newDigest: rawData.digest,
}
: m,
),
@ -232,22 +277,22 @@ const LocalProvidersTab = () => {
(enabled: boolean) => {
setCategoryEnabled(enabled);
filteredProviders.forEach((provider) => {
settings.updateProviderSettings(provider.name, { ...provider.settings, enabled });
updateProviderSettings(provider.name, { ...provider.settings, enabled });
});
toast.success(enabled ? 'All local providers enabled' : 'All local providers disabled');
success(enabled ? 'All local providers enabled' : 'All local providers disabled');
},
[filteredProviders, settings],
[filteredProviders, updateProviderSettings, success],
);
const handleToggleProvider = (provider: IProviderConfig, enabled: boolean) => {
settings.updateProviderSettings(provider.name, { ...provider.settings, enabled });
updateProviderSettings(provider.name, { ...provider.settings, enabled });
if (enabled) {
logStore.logProvider(`Provider ${provider.name} enabled`, { provider: provider.name });
toast.success(`${provider.name} enabled`);
success(`${provider.name} enabled`);
} else {
logStore.logProvider(`Provider ${provider.name} disabled`, { provider: provider.name });
toast.success(`${provider.name} disabled`);
success(`${provider.name} disabled`);
}
};
@ -258,42 +303,193 @@ const LocalProvidersTab = () => {
newBaseUrl = undefined;
}
settings.updateProviderSettings(provider.name, { ...provider.settings, baseUrl: newBaseUrl });
updateProviderSettings(provider.name, { ...provider.settings, baseUrl: newBaseUrl });
logStore.logProvider(`Base URL updated for ${provider.name}`, {
provider: provider.name,
baseUrl: newBaseUrl,
});
toast.success(`${provider.name} base URL updated`);
success(`${provider.name} base URL updated`);
setEditingProvider(null);
};
const handleUpdateOllamaModel = async (modelName: string) => {
setOllamaModels((current) => current.map((m) => (m.name === modelName ? { ...m, status: 'updating' } : m)));
const { success, newDigest } = await updateOllamaModel(modelName);
const { success: updateSuccess, newDigest } = await updateOllamaModel(modelName);
setOllamaModels((current) =>
current.map((m) =>
m.name === modelName
? {
...m,
status: success ? 'updated' : 'error',
error: success ? undefined : 'Update failed',
status: updateSuccess ? 'updated' : 'error',
error: updateSuccess ? undefined : 'Update failed',
newDigest,
}
: m,
),
);
if (success) {
toast.success(`Updated ${modelName}`);
if (updateSuccess) {
success(`Updated ${modelName}`);
} else {
toast.error(`Failed to update ${modelName}`);
error(`Failed to update ${modelName}`);
}
};
const handleDeleteOllamaModel = async (modelName: string) => {
try {
const response = await fetch(`${OLLAMA_API_URL}/api/delete`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: modelName }),
});
if (!response.ok) {
throw new Error(`Failed to delete ${modelName}`);
}
setOllamaModels((current) => current.filter((m) => m.name !== modelName));
success(`Deleted ${modelName}`);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
console.error(`Error deleting ${modelName}:`, errorMessage);
error(`Failed to delete ${modelName}`);
}
};
// Health check function
const checkOllamaHealth = async () => {
try {
// Use the root endpoint instead of /api/health
const response = await fetch(OLLAMA_API_URL);
const text = await response.text();
const isRunning = text.includes('Ollama is running');
setServiceStatus({
isRunning,
lastChecked: new Date(),
});
if (isRunning) {
// If Ollama is running, fetch models
fetchOllamaModels();
}
return isRunning;
} catch (error) {
console.error('Health check error:', error);
setServiceStatus({
isRunning: false,
lastChecked: new Date(),
error: error instanceof Error ? error.message : 'Failed to connect to Ollama service',
});
return false;
}
};
// Update manual installation function
const handleManualInstall = async (modelString: string) => {
try {
setIsInstallingModel(modelString);
setInstallProgress({ model: modelString, progress: 0, status: 'Starting download...' });
setManualInstall((prev) => ({ ...prev, isOpen: false }));
const response = await fetch(`${OLLAMA_API_URL}/api/pull`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: modelString }),
});
if (!response.ok) {
throw new Error(`Failed to install ${modelString}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('No response reader available');
}
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const text = new TextDecoder().decode(value);
const lines = text.split('\n').filter(Boolean);
for (const line of lines) {
const rawData = JSON.parse(line);
if (!isOllamaPullResponse(rawData)) {
console.error('Invalid response format:', rawData);
continue;
}
setInstallProgress({
model: modelString,
progress: rawData.completed && rawData.total ? (rawData.completed / rawData.total) * 100 : 0,
status: rawData.status,
});
}
}
success(`Successfully installed ${modelString}`);
await fetchOllamaModels();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
console.error(`Error installing ${modelString}:`, errorMessage);
error(`Failed to install ${modelString}`);
} finally {
setIsInstallingModel(null);
setInstallProgress(null);
}
};
// Add health check effect
useEffect(() => {
const checkHealth = async () => {
const isHealthy = await checkOllamaHealth();
if (!isHealthy) {
error('Ollama service is not running. Please start the Ollama service.');
}
};
checkHealth();
const interval = setInterval(checkHealth, 50000);
// Check every 30 seconds
return () => clearInterval(interval);
}, []);
return (
<div className="space-y-6">
{/* Service Status Indicator - Move to top */}
<div
className={classNames(
'flex items-center gap-2 p-2 rounded-lg',
serviceStatus.isRunning ? 'bg-green-500/10 text-green-500' : 'bg-red-500/10 text-red-500',
)}
>
<div className={classNames('w-2 h-2 rounded-full', serviceStatus.isRunning ? 'bg-green-500' : 'bg-red-500')} />
<span className="text-sm">
{serviceStatus.isRunning ? 'Ollama service is running' : 'Ollama service is not running'}
</span>
<span className="text-xs text-bolt-elements-textSecondary ml-2">
Last checked: {serviceStatus.lastChecked.toLocaleTimeString()}
</span>
</div>
<motion.div
className="space-y-4"
initial={{ opacity: 0, y: 20 }}
@ -527,21 +723,40 @@ const LocalProvidersTab = () => {
)}
</div>
</div>
<motion.button
onClick={() => handleUpdateOllamaModel(model.name)}
disabled={model.status === 'updating'}
className={classNames(
settingsStyles.button.base,
settingsStyles.button.secondary,
'hover:bg-purple-500/10 hover:text-purple-500',
'dark:bg-[#1A1A1A] dark:hover:bg-purple-500/20 dark:text-bolt-elements-textPrimary dark:hover:text-purple-500',
)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<div className="i-ph:arrows-clockwise" />
Update
</motion.button>
<div className="flex items-center gap-2">
<motion.button
onClick={() => handleUpdateOllamaModel(model.name)}
disabled={model.status === 'updating'}
className={classNames(
settingsStyles.button.base,
settingsStyles.button.secondary,
'hover:bg-purple-500/10 hover:text-purple-500',
)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<div className="i-ph:arrows-clockwise" />
Update
</motion.button>
<motion.button
onClick={() => {
if (window.confirm(`Are you sure you want to delete ${model.name}?`)) {
handleDeleteOllamaModel(model.name);
}
}}
disabled={model.status === 'updating'}
className={classNames(
settingsStyles.button.base,
settingsStyles.button.secondary,
'hover:bg-red-500/10 hover:text-red-500',
)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<div className="i-ph:trash" />
Delete
</motion.button>
</div>
</div>
))}
</div>
@ -560,8 +775,130 @@ const LocalProvidersTab = () => {
))}
</div>
</motion.div>
{/* Manual Installation Section */}
{serviceStatus.isRunning && (
<div className="mt-8 space-y-4">
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary">Install New Model</h3>
<p className="text-sm text-bolt-elements-textSecondary">
Enter the model name exactly as shown (e.g., deepseek-r1:1.5b)
</p>
</div>
</div>
{/* Model Information Section */}
<div className="p-4 rounded-lg bg-bolt-elements-background-depth-2 space-y-3">
<div className="flex items-center gap-2 text-bolt-elements-textPrimary">
<div className="i-ph:info text-purple-500" />
<span className="font-medium">Where to find models?</span>
</div>
<div className="space-y-2 text-sm text-bolt-elements-textSecondary">
<p>
Browse available models at{' '}
<a
href="https://ollama.com/library"
target="_blank"
rel="noopener noreferrer"
className="text-purple-500 hover:underline"
>
ollama.com/library
</a>
</p>
<div className="space-y-1">
<p className="font-medium text-bolt-elements-textPrimary">Popular models:</p>
<ul className="list-disc list-inside space-y-1 ml-2">
<li>deepseek-r1:1.5b - DeepSeek's reasoning model</li>
<li>llama3:8b - Meta's Llama 3 (8B parameters)</li>
<li>mistral:7b - Mistral's 7B model</li>
<li>gemma:2b - Google's Gemma model</li>
<li>qwen2:7b - Alibaba's Qwen2 model</li>
</ul>
</div>
<p className="mt-2">
<span className="text-yellow-500">Note:</span> Copy the exact model name including the tag (e.g.,
'deepseek-r1:1.5b') from the library to ensure successful installation.
</p>
</div>
</div>
<div className="flex gap-4">
<div className="flex-1">
<input
type="text"
className="w-full px-3 py-2 rounded-md bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor text-bolt-elements-textPrimary"
placeholder="deepseek-r1:1.5b"
value={manualInstall.modelString}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setManualInstall((prev) => ({ ...prev, modelString: e.target.value }))
}
/>
</div>
<motion.button
onClick={() => handleManualInstall(manualInstall.modelString)}
disabled={!manualInstall.modelString || !!isInstallingModel}
className={classNames(
settingsStyles.button.base,
settingsStyles.button.primary,
'hover:bg-purple-500/10 hover:text-purple-500',
'min-w-[120px] justify-center',
)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
{isInstallingModel ? (
<div className="flex items-center justify-center gap-2">
<div className="i-ph:spinner-gap-bold animate-spin" />
Installing...
</div>
) : (
<>
<div className="i-ph:download" />
Install Model
</>
)}
</motion.button>
{isInstallingModel && (
<motion.button
onClick={() => {
setIsInstallingModel(null);
setInstallProgress(null);
error('Installation cancelled');
}}
className={classNames(
settingsStyles.button.base,
settingsStyles.button.secondary,
'hover:bg-red-500/10 hover:text-red-500',
'min-w-[100px] justify-center',
)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<div className="i-ph:x" />
Cancel
</motion.button>
)}
</div>
{installProgress && (
<div className="mt-2 space-y-2">
<div className="flex items-center justify-between text-sm text-bolt-elements-textSecondary">
<span>{installProgress.status}</span>
<span>{Math.round(installProgress.progress)}%</span>
</div>
<div className="w-full h-2 bg-bolt-elements-background-depth-3 rounded-full overflow-hidden">
<div
className="h-full bg-purple-500 transition-all duration-200"
style={{ width: `${installProgress.progress}%` }}
/>
</div>
</div>
)}
</div>
)}
</div>
);
};
}
export default LocalProvidersTab;

View File

@ -229,19 +229,42 @@ export default function SettingsTab() {
<div className="space-y-2">
{Object.entries(useStore(shortcutsStore)).map(([name, shortcut]) => (
<div key={name} className="flex items-center justify-between p-2 rounded-lg bg-[#FAFAFA] dark:bg-[#1A1A1A]">
<div
key={name}
className="flex items-center justify-between p-2 rounded-lg bg-[#FAFAFA] dark:bg-[#1A1A1A] hover:bg-purple-50 dark:hover:bg-purple-500/10 transition-colors"
>
<span className="text-sm text-bolt-elements-textPrimary capitalize">
{name.replace(/([A-Z])/g, ' $1').toLowerCase()}
</span>
<div className="flex items-center gap-1">
{shortcut.ctrlOrMetaKey && (
<kbd className="kdb">{navigator.platform.includes('Mac') ? '⌘' : 'Ctrl'}</kbd>
<kbd className="px-2 py-1 text-xs font-semibold text-bolt-elements-textSecondary bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] rounded shadow-sm">
{navigator.platform.includes('Mac') ? '⌘' : 'Ctrl'}
</kbd>
)}
{shortcut.ctrlKey && <kbd className="kdb">Ctrl</kbd>}
{shortcut.metaKey && <kbd className="kdb"></kbd>}
{shortcut.shiftKey && <kbd className="kdb"></kbd>}
{shortcut.altKey && <kbd className="kdb"></kbd>}
<kbd className="kdb">{shortcut.key.toUpperCase()}</kbd>
{shortcut.ctrlKey && (
<kbd className="px-2 py-1 text-xs font-semibold text-bolt-elements-textSecondary bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] rounded shadow-sm">
Ctrl
</kbd>
)}
{shortcut.metaKey && (
<kbd className="px-2 py-1 text-xs font-semibold text-bolt-elements-textSecondary bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] rounded shadow-sm">
</kbd>
)}
{shortcut.altKey && (
<kbd className="px-2 py-1 text-xs font-semibold text-bolt-elements-textSecondary bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] rounded shadow-sm">
{navigator.platform.includes('Mac') ? '⌥' : 'Alt'}
</kbd>
)}
{shortcut.shiftKey && (
<kbd className="px-2 py-1 text-xs font-semibold text-bolt-elements-textSecondary bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] rounded shadow-sm">
</kbd>
)}
<kbd className="px-2 py-1 text-xs font-semibold text-bolt-elements-textSecondary bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] rounded shadow-sm">
{shortcut.key.toUpperCase()}
</kbd>
</div>
</div>
))}

View File

@ -309,7 +309,7 @@ export default function TaskManagerTab() {
try {
setLoading((prev) => ({ ...prev, metrics: true }));
// Get memory info
// Get memory info using Performance API
const memory = performance.memory || {
jsHeapSizeLimit: 0,
totalJSHeapSize: 0,
@ -319,6 +319,9 @@ export default function TaskManagerTab() {
const usedMem = memory.usedJSHeapSize / (1024 * 1024);
const memPercentage = (usedMem / totalMem) * 100;
// Get CPU usage using Performance API
const cpuUsage = await getCPUUsage();
// Get battery info
let batteryInfo: SystemMetrics['battery'] | undefined;
@ -333,7 +336,7 @@ export default function TaskManagerTab() {
console.log('Battery API not available');
}
// Get network info
// Get network info using Network Information API
const connection =
(navigator as any).connection || (navigator as any).mozConnection || (navigator as any).webkitConnection;
const networkInfo = {
@ -343,13 +346,13 @@ export default function TaskManagerTab() {
};
const newMetrics = {
cpu: Math.random() * 100,
cpu: cpuUsage,
memory: {
used: Math.round(usedMem),
total: Math.round(totalMem),
percentage: Math.round(memPercentage),
},
activeProcesses: document.querySelectorAll('[data-process]').length,
activeProcesses: await getActiveProcessCount(),
uptime: performance.now() / 1000,
battery: batteryInfo,
network: networkInfo,
@ -375,60 +378,111 @@ export default function TaskManagerTab() {
}
};
// Get real CPU usage using Performance API
const getCPUUsage = async (): Promise<number> => {
try {
const t0 = performance.now();
const startEntries = performance.getEntriesByType('measure');
// Wait a short time to measure CPU usage
await new Promise((resolve) => setTimeout(resolve, 100));
const t1 = performance.now();
const endEntries = performance.getEntriesByType('measure');
// Calculate CPU usage based on the number of performance entries
const entriesPerMs = (endEntries.length - startEntries.length) / (t1 - t0);
// Normalize to percentage (0-100)
return Math.min(100, entriesPerMs * 1000);
} catch (error) {
console.error('Failed to get CPU usage:', error);
return 0;
}
};
// Get real active process count
const getActiveProcessCount = async (): Promise<number> => {
try {
// Count active network connections
const networkCount = (navigator as any)?.connections?.length || 0;
// Count active service workers
const swCount = (await navigator.serviceWorker?.getRegistrations().then((regs) => regs.length)) || 0;
// Count active animations
const animationCount = document.getAnimations().length;
// Count active fetch requests
const fetchCount = performance
.getEntriesByType('resource')
.filter(
(entry) => (entry as PerformanceResourceTiming).initiatorType === 'fetch' && entry.duration === 0,
).length;
return networkCount + swCount + animationCount + fetchCount;
} catch (error) {
console.error('Failed to get active process count:', error);
return 0;
}
};
const updateProcesses = async () => {
try {
setLoading((prev) => ({ ...prev, processes: true }));
// Enhanced process monitoring
const mockProcesses: ProcessInfo[] = [
{
name: 'Ollama Model Updates',
type: 'Network',
cpuUsage: Math.random() * 5,
memoryUsage: Math.random() * 50,
status: 'idle',
lastUpdate: new Date().toISOString(),
impact: 'high',
},
{
name: 'UI Animations',
type: 'Animation',
cpuUsage: Math.random() * 3,
memoryUsage: Math.random() * 30,
status: 'idle',
lastUpdate: new Date().toISOString(),
impact: 'medium',
},
{
name: 'Background Sync',
type: 'Background',
cpuUsage: Math.random() * 2,
memoryUsage: Math.random() * 20,
status: 'idle',
lastUpdate: new Date().toISOString(),
impact: 'low',
},
{
name: 'IndexedDB Operations',
type: 'Storage',
cpuUsage: Math.random() * 1,
memoryUsage: Math.random() * 15,
status: 'idle',
lastUpdate: new Date().toISOString(),
impact: 'low',
},
{
name: 'WebSocket Connection',
type: 'Network',
cpuUsage: Math.random() * 2,
memoryUsage: Math.random() * 10,
status: 'idle',
lastUpdate: new Date().toISOString(),
impact: 'medium',
},
];
// Get real process information
const processes: ProcessInfo[] = [];
setProcesses(mockProcesses);
// Add network processes
const networkEntries = performance
.getEntriesByType('resource')
.filter((entry) => (entry as PerformanceResourceTiming).initiatorType === 'fetch' && entry.duration === 0)
.slice(-5); // Get last 5 active requests
networkEntries.forEach((entry) => {
processes.push({
name: `Network Request: ${new URL((entry as PerformanceResourceTiming).name).pathname}`,
type: 'Network',
cpuUsage: entry.duration > 0 ? entry.duration / 100 : 0,
memoryUsage: (entry as PerformanceResourceTiming).encodedBodySize / (1024 * 1024), // Convert to MB
status: entry.duration === 0 ? 'active' : 'idle',
lastUpdate: new Date().toISOString(),
impact: entry.duration > 1000 ? 'high' : entry.duration > 500 ? 'medium' : 'low',
});
});
// Add animation processes
document
.getAnimations()
.slice(0, 5)
.forEach((animation) => {
processes.push({
name: `Animation: ${animation.id || 'Unnamed'}`,
type: 'Animation',
cpuUsage: animation.playState === 'running' ? 2 : 0,
memoryUsage: 1, // Approximate memory usage
status: animation.playState === 'running' ? 'active' : 'idle',
lastUpdate: new Date().toISOString(),
impact: 'low',
});
});
// Add service worker processes
const serviceWorkers = (await navigator.serviceWorker?.getRegistrations()) || [];
serviceWorkers.forEach((sw) => {
processes.push({
name: `Service Worker: ${sw.scope}`,
type: 'Background',
cpuUsage: sw.active ? 1 : 0,
memoryUsage: 5, // Approximate memory usage
status: sw.active ? 'active' : 'idle',
lastUpdate: new Date().toISOString(),
impact: 'low',
});
});
setProcesses(processes);
} catch (error) {
console.error('Failed to update process list:', error);
} finally {

View File

@ -379,156 +379,6 @@ export const UsersWindow = ({ open, onClose }: UsersWindowProps) => {
}
};
const renderHeader = () => (
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center space-x-4">
{activeTab ? (
<button
onClick={handleBack}
className="flex items-center justify-center w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
>
<div className="i-ph:arrow-left w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</button>
) : (
<motion.div
className="i-ph:lightning-fill w-5 h-5 text-purple-500"
initial={{ rotate: -10 }}
animate={{ rotate: 10 }}
transition={{
repeat: Infinity,
repeatType: 'reverse',
duration: 2,
ease: 'easeInOut',
}}
/>
)}
<DialogTitle className="text-xl font-semibold text-gray-900 dark:text-white">
{activeTab ? TAB_LABELS[activeTab] : 'Bolt Control Panel'}
</DialogTitle>
</div>
<div className="flex items-center space-x-4">
<div className="flex items-center gap-2">
<Switch
checked={developerMode}
onCheckedChange={handleDeveloperModeChange}
className="data-[state=checked]:bg-purple-500"
aria-label="Toggle developer mode"
/>
<label className="text-sm text-gray-500 dark:text-gray-400">Switch to Developer Mode</label>
</div>
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<button className="flex items-center justify-center w-8 h-8 rounded-full overflow-hidden hover:ring-2 ring-gray-300 dark:ring-gray-600 transition-all">
{profile.avatar ? (
<img src={profile.avatar} alt="Profile" className="w-full h-full object-cover" />
) : (
<div className="w-full h-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
<svg
className="w-5 h-5 text-gray-500 dark:text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
/>
</svg>
</div>
)}
</button>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
className="min-w-[220px] bg-white dark:bg-gray-800 rounded-lg shadow-lg py-1 z-50 animate-in fade-in-0 zoom-in-95"
sideOffset={5}
align="end"
>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('profile')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:user-circle w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Profile</span>
</DropdownMenu.Item>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('settings')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:gear w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Settings</span>
</DropdownMenu.Item>
{profile.notifications && (
<>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('notifications')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:bell w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">
Notifications
{hasUnreadNotifications && (
<span className="ml-2 px-1.5 py-0.5 text-xs bg-purple-500 text-white rounded-full">
{unreadNotifications.length}
</span>
)}
</span>
</DropdownMenu.Item>
<DropdownMenu.Separator className="my-1 h-px bg-gray-200 dark:bg-gray-700" />
</>
)}
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={onClose}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:sign-out w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Close</span>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
<button
onClick={onClose}
className="flex items-center justify-center w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
>
<div className="i-ph:x w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</button>
</div>
</div>
);
// Trap focus when window is open
useEffect(() => {
if (open) {
// Prevent background scrolling
document.body.style.overflow = 'hidden';
} else {
document.body.style.overflow = 'unset';
}
return () => {
document.body.style.overflow = 'unset';
};
}, [open]);
return (
<>
<DeveloperWindow open={showDeveloperWindow} onClose={handleDeveloperWindowClose} />
@ -567,7 +417,139 @@ export const UsersWindow = ({ open, onClose }: UsersWindowProps) => {
transition={{ duration: 0.2 }}
>
{/* Header */}
{renderHeader()}
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center space-x-4">
{activeTab ? (
<button
onClick={handleBack}
className="flex items-center justify-center w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
>
<div className="i-ph:arrow-left w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</button>
) : (
<motion.div
className="i-ph:lightning-fill w-5 h-5 text-purple-500"
initial={{ rotate: -10 }}
animate={{ rotate: 10 }}
transition={{
repeat: Infinity,
repeatType: 'reverse',
duration: 2,
ease: 'easeInOut',
}}
/>
)}
<DialogTitle className="text-xl font-semibold text-gray-900 dark:text-white">
{activeTab ? TAB_LABELS[activeTab] : 'Bolt Control Panel'}
</DialogTitle>
</div>
<div className="flex items-center space-x-4">
<div className="flex items-center gap-2">
<Switch
checked={developerMode}
onCheckedChange={handleDeveloperModeChange}
className="data-[state=checked]:bg-purple-500"
aria-label="Toggle developer mode"
/>
<label className="text-sm text-gray-500 dark:text-gray-400">Switch to Developer Mode</label>
</div>
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<button className="flex items-center justify-center w-8 h-8 rounded-full overflow-hidden hover:ring-2 ring-gray-300 dark:ring-gray-600 transition-all">
{profile.avatar ? (
<img src={profile.avatar} alt="Profile" className="w-full h-full object-cover" />
) : (
<div className="w-full h-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
<svg
className="w-5 h-5 text-gray-500 dark:text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
/>
</svg>
</div>
)}
</button>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
className="min-w-[220px] bg-white dark:bg-gray-800 rounded-lg shadow-lg py-1 z-[200] animate-in fade-in-0 zoom-in-95"
sideOffset={5}
align="end"
>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('profile')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:user-circle w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Profile</span>
</DropdownMenu.Item>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('settings')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:gear w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Settings</span>
</DropdownMenu.Item>
{profile.notifications && (
<>
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={() => handleTabClick('notifications')}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:bell w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">
Notifications
{hasUnreadNotifications && (
<span className="ml-2 px-1.5 py-0.5 text-xs bg-purple-500 text-white rounded-full">
{unreadNotifications.length}
</span>
)}
</span>
</DropdownMenu.Item>
<DropdownMenu.Separator className="my-1 h-px bg-gray-200 dark:bg-gray-700" />
</>
)}
<DropdownMenu.Item
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onSelect={onClose}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div className="i-ph:sign-out w-[18px] h-[18px] text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</div>
<span className="group-hover:text-purple-500 transition-colors">Close</span>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
<button
onClick={onClose}
className="flex items-center justify-center w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
>
<div className="i-ph:x w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</button>
</div>
</div>
{/* Content */}
<div

View File

@ -0,0 +1,44 @@
import { forwardRef } from 'react';
import { cn } from '~/lib/utils';
export interface CardProps extends React.HTMLAttributes<HTMLDivElement> {}
const Card = forwardRef<HTMLDivElement, CardProps>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
className={cn(
'rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 text-bolt-elements-textPrimary shadow-sm',
className,
)}
{...props}
/>
);
});
Card.displayName = 'Card';
const CardHeader = forwardRef<HTMLDivElement, CardProps>(({ className, ...props }, ref) => {
return <div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />;
});
CardHeader.displayName = 'CardHeader';
const CardTitle = forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => {
return <h3 ref={ref} className={cn('text-2xl font-semibold leading-none tracking-tight', className)} {...props} />;
},
);
CardTitle.displayName = 'CardTitle';
const CardDescription = forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => {
return <p ref={ref} className={cn('text-sm text-bolt-elements-textSecondary', className)} {...props} />;
},
);
CardDescription.displayName = 'CardDescription';
const CardContent = forwardRef<HTMLDivElement, CardProps>(({ className, ...props }, ref) => {
return <div ref={ref} className={cn('p-6 pt-0', className)} {...props} />;
});
CardContent.displayName = 'CardContent';
export { Card, CardHeader, CardTitle, CardDescription, CardContent };

View File

@ -0,0 +1,25 @@
import { forwardRef } from 'react';
import { cn } from '~/lib/utils';
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = forwardRef<HTMLInputElement, InputProps>(({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
'flex h-10 w-full rounded-md border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 px-3 py-2 text-sm',
'ring-offset-bolt-elements-background-depth-1 file:border-0 file:bg-transparent file:text-sm file:font-medium',
'placeholder:text-bolt-elements-textTertiary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-purple-500/30',
'focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
ref={ref}
{...props}
/>
);
});
Input.displayName = 'Input';
export { Input };

View File

@ -0,0 +1,22 @@
import { forwardRef } from 'react';
import { cn } from '~/lib/utils';
export interface LabelProps extends React.LabelHTMLAttributes<HTMLLabelElement> {}
const Label = forwardRef<HTMLLabelElement, LabelProps>(({ className, ...props }, ref) => {
return (
<label
ref={ref}
className={cn(
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
'text-bolt-elements-textPrimary',
className,
)}
{...props}
/>
);
});
Label.displayName = 'Label';
export { Label };

View File

@ -0,0 +1,56 @@
import * as TabsPrimitive from '@radix-ui/react-tabs';
import { forwardRef } from 'react';
import { cn } from '~/lib/utils';
const Tabs = TabsPrimitive.Root;
const TabsList = forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
'inline-flex h-10 items-center justify-center rounded-md bg-bolt-elements-background-depth-2 p-1',
'text-bolt-elements-textSecondary',
className,
)}
{...props}
/>
));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
'inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-bolt-elements-background-depth-1',
'transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-purple-500/30 focus-visible:ring-offset-2',
'disabled:pointer-events-none disabled:opacity-50',
'data-[state=active]:bg-bolt-elements-background-depth-1 data-[state=active]:text-bolt-elements-textPrimary data-[state=active]:shadow-sm',
className,
)}
{...props}
/>
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
'mt-2 ring-offset-bolt-elements-background-depth-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-purple-500/30 focus-visible:ring-offset-2',
className,
)}
{...props}
/>
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent };

View File

@ -0,0 +1,40 @@
import { useCallback } from 'react';
import { toast as toastify } from 'react-toastify';
interface ToastOptions {
type?: 'success' | 'error' | 'info' | 'warning';
duration?: number;
}
export function useToast() {
const toast = useCallback((message: string, options: ToastOptions = {}) => {
const { type = 'info', duration = 3000 } = options;
toastify[type](message, {
position: 'bottom-right',
autoClose: duration,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: 'dark',
});
}, []);
const success = useCallback(
(message: string, options: Omit<ToastOptions, 'type'> = {}) => {
toast(message, { ...options, type: 'success' });
},
[toast],
);
const error = useCallback(
(message: string, options: Omit<ToastOptions, 'type'> = {}) => {
toast(message, { ...options, type: 'error' });
},
[toast],
);
return { toast, success, error };
}

View File

@ -126,7 +126,7 @@ export async function selectContext(props: {
---
${filePaths.map((path) => `- ${path}`).join('\n')}
---
You have following code loaded in the context buffer that you can refer to:
CURRENT CONTEXT BUFFER
@ -137,14 +137,14 @@ export async function selectContext(props: {
Now, you are given a task. You need to select the files that are relevant to the task from the list of files above.
RESPONSE FORMAT:
your response shoudl be in following format:
your response should be in following format:
---
<updateContextBuffer>
<includeFile path="path/to/file"/>
<excludeFile path="path/to/file"/>
</updateContextBuffer>
---
* Your should start with <updateContextBuffer> and end with </updateContextBuffer>.
* Your should start with <updateContextBuffer> and end with </updateContextBuffer>.
* You can include multiple <includeFile> and <excludeFile> tags in the response.
* You should not include any other text in the response.
* You should not include any file that is not in the list of files above.

View File

@ -0,0 +1,25 @@
import { useCallback, useState } from 'react';
import type { IProviderConfig } from '~/types/model';
export interface UseLocalProvidersReturn {
localProviders: IProviderConfig[];
refreshLocalProviders: () => void;
}
export function useLocalProviders(): UseLocalProvidersReturn {
const [localProviders, setLocalProviders] = useState<IProviderConfig[]>([]);
const refreshLocalProviders = useCallback(() => {
/*
* Refresh logic for local providers
* This would typically involve checking the status of Ollama and LMStudio
* For now, we'll just return an empty array
*/
setLocalProviders([]);
}, []);
return {
localProviders,
refreshLocalProviders,
};
}

View File

@ -10,24 +10,43 @@ export interface LogEntry {
level: 'info' | 'warning' | 'error' | 'debug';
message: string;
details?: Record<string, any>;
category: 'system' | 'provider' | 'user' | 'error' | 'api' | 'auth' | 'database' | 'network' | 'performance';
category:
| 'system'
| 'provider'
| 'user'
| 'error'
| 'api'
| 'auth'
| 'database'
| 'network'
| 'performance'
| 'settings'
| 'task'
| 'update'
| 'feature';
subCategory?: string;
duration?: number;
statusCode?: number;
source?: string;
stack?: string;
metadata?: {
component?: string;
action?: string;
userId?: string;
sessionId?: string;
previousValue?: any;
newValue?: any;
};
}
interface LogDetails extends Record<string, any> {
type: string;
message: string;
}
const MAX_LOGS = 1000; // Maximum number of logs to keep in memory
class LogStore {
logInfo(message: string, details: { type: string; message: string }) {
return this.addLog(message, 'info', 'system', details);
}
logSuccess(message: string, details: { type: string; message: string }) {
return this.addLog(message, 'info', 'system', { ...details, success: true });
}
private _logs = map<Record<string, LogEntry>>({});
showLogs = atom(true);
private _readLogs = new Set<string>();
@ -106,13 +125,13 @@ class LogStore {
}
}
addLog(
// Base log method for general logging
private _addLog(
message: string,
level: LogEntry['level'] = 'info',
category: LogEntry['category'] = 'system',
level: LogEntry['level'],
category: LogEntry['category'],
details?: Record<string, any>,
statusCode?: number,
duration?: number,
metadata?: LogEntry['metadata'],
) {
const id = this._generateId();
const entry: LogEntry = {
@ -122,8 +141,7 @@ class LogStore {
message,
details,
category,
statusCode,
duration,
metadata,
};
this._logs.setKey(id, entry);
@ -133,19 +151,40 @@ class LogStore {
return id;
}
// Specialized method for API logging
private _addApiLog(
message: string,
method: string,
url: string,
details: {
method: string;
url: string;
statusCode: number;
duration: number;
request: any;
response: any;
},
) {
const statusCode = details.statusCode;
return this._addLog(message, statusCode >= 400 ? 'error' : 'info', 'api', details, {
component: 'api',
action: method,
});
}
// System events
logSystem(message: string, details?: Record<string, any>) {
return this.addLog(message, 'info', 'system', details);
return this._addLog(message, 'info', 'system', details);
}
// Provider events
logProvider(message: string, details?: Record<string, any>) {
return this.addLog(message, 'info', 'provider', details);
return this._addLog(message, 'info', 'provider', details);
}
// User actions
logUserAction(message: string, details?: Record<string, any>) {
return this.addLog(message, 'info', 'user', details);
return this._addLog(message, 'info', 'user', details);
}
// API Connection Logging
@ -153,7 +192,7 @@ class LogStore {
const message = `${method} ${endpoint} - ${statusCode} (${duration}ms)`;
const level = statusCode >= 400 ? 'error' : statusCode >= 300 ? 'warning' : 'info';
return this.addLog(message, level, 'api', {
return this._addLog(message, level, 'api', {
...details,
endpoint,
method,
@ -172,7 +211,7 @@ class LogStore {
const message = `Auth ${action} - ${success ? 'Success' : 'Failed'}`;
const level = success ? 'info' : 'error';
return this.addLog(message, level, 'auth', {
return this._addLog(message, level, 'auth', {
...details,
action,
success,
@ -185,7 +224,7 @@ class LogStore {
const message = `Network ${status}`;
const level = status === 'offline' ? 'error' : status === 'reconnecting' ? 'warning' : 'info';
return this.addLog(message, level, 'network', {
return this._addLog(message, level, 'network', {
...details,
status,
timestamp: new Date().toISOString(),
@ -197,7 +236,7 @@ class LogStore {
const message = `DB ${operation} - ${success ? 'Success' : 'Failed'} (${duration}ms)`;
const level = success ? 'info' : 'error';
return this.addLog(message, level, 'database', {
return this._addLog(message, level, 'database', {
...details,
operation,
success,
@ -218,17 +257,17 @@ class LogStore {
}
: { error, ...details };
return this.addLog(message, 'error', 'error', errorDetails);
return this._addLog(message, 'error', 'error', errorDetails);
}
// Warning events
logWarning(message: string, details?: Record<string, any>) {
return this.addLog(message, 'warning', 'system', details);
return this._addLog(message, 'warning', 'system', details);
}
// Debug events
logDebug(message: string, details?: Record<string, any>) {
return this.addLog(message, 'debug', 'system', details);
return this._addLog(message, 'debug', 'system', details);
}
clearLogs() {
@ -269,7 +308,35 @@ class LogStore {
this._saveReadLogs();
}
// Network request logging
// API interactions
logApiCall(
method: string,
endpoint: string,
statusCode: number,
duration: number,
requestData?: any,
responseData?: any,
) {
return this._addLog(
`API ${method} ${endpoint}`,
statusCode >= 400 ? 'error' : 'info',
'api',
{
method,
endpoint,
statusCode,
duration,
request: requestData,
response: responseData,
},
{
component: 'api',
action: method,
},
);
}
// Network operations
logNetworkRequest(
method: string,
url: string,
@ -278,7 +345,7 @@ class LogStore {
requestData?: any,
responseData?: any,
) {
this.addLog(
return this._addLog(
`${method} ${url}`,
statusCode >= 400 ? 'error' : 'info',
'network',
@ -290,45 +357,30 @@ class LogStore {
request: requestData,
response: responseData,
},
statusCode,
duration,
{
component: 'network',
action: method,
},
);
}
// Authentication events
logAuthEvent(event: string, success: boolean, details?: Record<string, any>) {
this.addLog(`Auth ${event} ${success ? 'succeeded' : 'failed'}`, success ? 'info' : 'error', 'auth', details);
}
// API interactions
logApiCall(
endpoint: string,
method: string,
statusCode: number,
duration: number,
requestData?: any,
responseData?: any,
) {
this.addLog(
`API ${method} ${endpoint}`,
statusCode >= 400 ? 'error' : 'info',
'api',
return this._addLog(
`Auth ${event} ${success ? 'succeeded' : 'failed'}`,
success ? 'info' : 'error',
'auth',
details,
{
endpoint,
method,
statusCode,
duration,
request: requestData,
response: responseData,
component: 'auth',
action: event,
},
statusCode,
duration,
);
}
// Performance monitoring
// Performance tracking
logPerformance(operation: string, duration: number, details?: Record<string, any>) {
this.addLog(
return this._addLog(
`Performance: ${operation}`,
duration > 1000 ? 'warning' : 'info',
'performance',
@ -337,18 +389,29 @@ class LogStore {
duration,
...details,
},
undefined,
duration,
{
component: 'performance',
action: 'metric',
},
);
}
// Error logging with stack trace
// Error handling
logErrorWithStack(error: Error, category: LogEntry['category'] = 'error', details?: Record<string, any>) {
this.addLog(error.message, 'error', category, {
...details,
name: error.name,
stack: error.stack,
});
return this._addLog(
error.message,
'error',
category,
{
...details,
name: error.name,
stack: error.stack,
},
{
component: category,
action: 'error',
},
);
}
// Refresh logs (useful for real-time updates)
@ -356,6 +419,101 @@ class LogStore {
const currentLogs = this._logs.get();
this._logs.set({ ...currentLogs });
}
// Enhanced logging methods
logInfo(message: string, details: LogDetails) {
return this._addLog(message, 'info', 'system', details);
}
logSuccess(message: string, details: LogDetails) {
return this._addLog(message, 'info', 'system', { ...details, success: true });
}
logApiRequest(
method: string,
url: string,
details: {
method: string;
url: string;
statusCode: number;
duration: number;
request: any;
response: any;
},
) {
return this._addApiLog(`API ${method} ${url}`, method, url, details);
}
logSettingsChange(component: string, setting: string, oldValue: any, newValue: any) {
return this._addLog(
`Settings changed in ${component}: ${setting}`,
'info',
'settings',
{
setting,
previousValue: oldValue,
newValue,
},
{
component,
action: 'settings_change',
previousValue: oldValue,
newValue,
},
);
}
logFeatureToggle(featureId: string, enabled: boolean) {
return this._addLog(
`Feature ${featureId} ${enabled ? 'enabled' : 'disabled'}`,
'info',
'feature',
{ featureId, enabled },
{
component: 'features',
action: 'feature_toggle',
},
);
}
logTaskOperation(taskId: string, operation: string, status: string, details?: any) {
return this._addLog(
`Task ${taskId}: ${operation} - ${status}`,
'info',
'task',
{ taskId, operation, status, ...details },
{
component: 'task-manager',
action: 'task_operation',
},
);
}
logProviderAction(provider: string, action: string, success: boolean, details?: any) {
return this._addLog(
`Provider ${provider}: ${action} - ${success ? 'Success' : 'Failed'}`,
success ? 'info' : 'error',
'provider',
{ provider, action, success, ...details },
{
component: 'providers',
action: 'provider_action',
},
);
}
logPerformanceMetric(component: string, operation: string, duration: number, details?: any) {
return this._addLog(
`Performance: ${component} - ${operation} took ${duration}ms`,
duration > 1000 ? 'warning' : 'info',
'performance',
{ component, operation, duration, ...details },
{
component,
action: 'performance_metric',
},
);
}
}
export const logStore = new LogStore();

View File

@ -32,24 +32,25 @@ export type ProviderSetting = Record<string, IProviderConfig>;
export const shortcutsStore = map<Shortcuts>({
toggleTerminal: {
key: 'j',
key: '`',
ctrlOrMetaKey: true,
action: () => workbenchStore.toggleTerminal(),
},
toggleTheme: {
key: 't',
key: 'd',
ctrlOrMetaKey: true,
shiftKey: true,
altKey: true,
action: () => toggleTheme(),
},
toggleChat: {
key: '/',
key: 'k',
ctrlOrMetaKey: true,
action: () => chatStore.setKey('showChat', !chatStore.get().showChat),
},
toggleSettings: {
key: ',',
key: 's',
ctrlOrMetaKey: true,
altKey: true,
action: () => {
// This will be connected to the settings panel toggle
document.dispatchEvent(new CustomEvent('toggle-settings'));

View File

@ -63,13 +63,14 @@
"@phosphor-icons/react": "^2.1.7",
"@radix-ui/react-collapsible": "^1.0.3",
"@radix-ui/react-context-menu": "^2.2.2",
"@radix-ui/react-dialog": "^1.1.2",
"@radix-ui/react-dialog": "^1.1.5",
"@radix-ui/react-dropdown-menu": "^2.1.2",
"@radix-ui/react-popover": "^1.1.5",
"@radix-ui/react-progress": "^1.0.3",
"@radix-ui/react-scroll-area": "^1.2.2",
"@radix-ui/react-separator": "^1.1.0",
"@radix-ui/react-switch": "^1.1.1",
"@radix-ui/react-tabs": "^1.1.2",
"@radix-ui/react-tooltip": "^1.1.4",
"@remix-run/cloudflare": "^2.15.2",
"@remix-run/cloudflare-pages": "^2.15.2",

View File

@ -111,7 +111,7 @@ importers:
specifier: ^2.2.2
version: 2.2.5(@types/react-dom@18.3.5(@types/react@18.3.18))(@types/react@18.3.18)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
'@radix-ui/react-dialog':
specifier: ^1.1.2
specifier: ^1.1.5
version: 1.1.5(@types/react-dom@18.3.5(@types/react@18.3.18))(@types/react@18.3.18)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
'@radix-ui/react-dropdown-menu':
specifier: ^2.1.2
@ -131,6 +131,9 @@ importers:
'@radix-ui/react-switch':
specifier: ^1.1.1
version: 1.1.2(@types/react-dom@18.3.5(@types/react@18.3.18))(@types/react@18.3.18)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
'@radix-ui/react-tabs':
specifier: ^1.1.2
version: 1.1.2(@types/react-dom@18.3.5(@types/react@18.3.18))(@types/react@18.3.18)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
'@radix-ui/react-tooltip':
specifier: ^1.1.4
version: 1.1.7(@types/react-dom@18.3.5(@types/react@18.3.18))(@types/react@18.3.18)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
@ -2164,6 +2167,19 @@ packages:
'@types/react-dom':
optional: true
'@radix-ui/react-tabs@1.1.2':
resolution: {integrity: sha512-9u/tQJMcC2aGq7KXpGivMm1mgq7oRJKXphDwdypPd/j21j/2znamPU8WkXgnhUaTrSFNIt8XhOyCAupg8/GbwQ==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-tooltip@1.1.7':
resolution: {integrity: sha512-ss0s80BC0+g0+Zc53MvilcnTYSOi4mSuFWBPYPuTOFGjx+pUU+ZrmamMNwS56t8MTFlniA5ocjd4jYm/CdhbOg==}
peerDependencies:
@ -8494,6 +8510,22 @@ snapshots:
'@types/react': 18.3.18
'@types/react-dom': 18.3.5(@types/react@18.3.18)
'@radix-ui/react-tabs@1.1.2(@types/react-dom@18.3.5(@types/react@18.3.18))(@types/react@18.3.18)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)':
dependencies:
'@radix-ui/primitive': 1.1.1
'@radix-ui/react-context': 1.1.1(@types/react@18.3.18)(react@18.3.1)
'@radix-ui/react-direction': 1.1.0(@types/react@18.3.18)(react@18.3.1)
'@radix-ui/react-id': 1.1.0(@types/react@18.3.18)(react@18.3.1)
'@radix-ui/react-presence': 1.1.2(@types/react-dom@18.3.5(@types/react@18.3.18))(@types/react@18.3.18)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
'@radix-ui/react-primitive': 2.0.1(@types/react-dom@18.3.5(@types/react@18.3.18))(@types/react@18.3.18)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
'@radix-ui/react-roving-focus': 1.1.1(@types/react-dom@18.3.5(@types/react@18.3.18))(@types/react@18.3.18)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
'@radix-ui/react-use-controllable-state': 1.1.0(@types/react@18.3.18)(react@18.3.1)
react: 18.3.1
react-dom: 18.3.1(react@18.3.1)
optionalDependencies:
'@types/react': 18.3.18
'@types/react-dom': 18.3.5(@types/react@18.3.18)
'@radix-ui/react-tooltip@1.1.7(@types/react-dom@18.3.5(@types/react@18.3.18))(@types/react@18.3.18)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)':
dependencies:
'@radix-ui/primitive': 1.1.1