Spaces:
Sleeping
Sleeping
File size: 25,480 Bytes
5c03d80 0cfd364 5c03d80 039e1ea f881423 0cfd364 f881423 0cfd364 5c03d80 f881423 0cfd364 f881423 0cfd364 5c03d80 f881423 5c03d80 0cfd364 5c03d80 0cfd364 715b529 5c03d80 0cfd364 5c03d80 0cfd364 5c03d80 0cfd364 5c03d80 0cfd364 5c03d80 0cfd364 5c03d80 0cfd364 5c03d80 0cfd364 5c03d80 f881423 039e1ea 5c03d80 039e1ea 5c03d80 f881423 5c03d80 0cfd364 f881423 715b529 f881423 0cfd364 039e1ea f881423 0cfd364 f881423 039e1ea f881423 039e1ea f881423 039e1ea f881423 039e1ea 0cfd364 5c03d80 f881423 039e1ea 0cfd364 f881423 715b529 f881423 039e1ea f881423 039e1ea 0cfd364 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 | import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
Settings as SettingsIcon,
Key,
AlertCircle,
CheckCircle,
Eye,
EyeOff,
Zap,
Server,
Palette,
Bell,
Shield,
Cpu,
Globe,
Wallet,
ChevronRight,
} from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Select, Toggle } from '@/components/ui/Select';
import { Badge } from '@/components/ui/Badge';
import { apiClient } from '@/api/client';
import type { SystemSettings } from '@/types';
import { classNames } from '@/utils/helpers';
interface SettingsProps {
className?: string;
}
interface ApiKeyState {
openai: string;
anthropic: string;
google: string;
groq: string;
}
interface ModelOption {
provider: string;
model: string;
name: string;
description: string;
default?: boolean;
}
interface SettingsData {
api_keys_configured: Record<string, boolean>;
selected_model: { provider: string; model: string };
available_models: ModelOption[];
plugins_installed: string[];
}
type SettingsSection = 'general' | 'api-keys' | 'models' | 'budget' | 'appearance' | 'notifications' | 'advanced';
const sectionConfig: { id: SettingsSection; label: string; icon: React.ElementType; description: string }[] = [
{ id: 'general', label: 'General', icon: SettingsIcon, description: 'Basic application settings' },
{ id: 'api-keys', label: 'API Keys', icon: Key, description: 'Configure provider API keys' },
{ id: 'models', label: 'Models', icon: Cpu, description: 'AI model selection' },
{ id: 'budget', label: 'Budget & Limits', icon: Wallet, description: 'API usage limits' },
{ id: 'appearance', label: 'Appearance', icon: Palette, description: 'UI customization' },
{ id: 'notifications', label: 'Notifications', icon: Bell, description: 'Alert preferences' },
{ id: 'advanced', label: 'Advanced', icon: Shield, description: 'Advanced settings' },
];
export const Settings: React.FC<SettingsProps> = ({ className }) => {
const queryClient = useQueryClient();
const [activeSection, setActiveSection] = useState<SettingsSection>('general');
const [localSettings, setLocalSettings] = useState<Partial<SystemSettings>>({});
const [showKeys, setShowKeys] = useState<Record<string, boolean>>({});
const [budgetEnabled, setBudgetEnabled] = useState(false);
const [apiKeys, setApiKeys] = useState<ApiKeyState>({
openai: '',
anthropic: '',
google: '',
groq: '',
});
// Fetch settings from new API
const { data: settingsData, isLoading: settingsLoading } = useQuery<SettingsData>({
queryKey: ['client-settings'],
queryFn: async () => {
const res = await fetch('/api/settings/');
return res.json();
},
});
// Fetch API key requirement status
const { data: keyRequired } = useQuery({
queryKey: ['api-key-required'],
queryFn: async () => {
const res = await fetch('/api/settings/api-key/required');
return res.json();
},
refetchInterval: 5000,
});
const { data: health } = useQuery({
queryKey: ['health'],
queryFn: () => apiClient.healthCheck(),
refetchInterval: 10000,
});
const normalizedHealthStatus = typeof health?.status === 'string'
? health.status.toLowerCase()
: '';
const isBackendOnline =
normalizedHealthStatus === 'healthy'
|| normalizedHealthStatus === 'ok'
|| normalizedHealthStatus === 'ready';
// Mutation to update API key
const updateApiKeyMutation = useMutation({
mutationFn: async ({ provider, api_key }: { provider: string; api_key: string }) => {
const res = await fetch('/api/settings/api-key', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ provider, api_key }),
});
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['client-settings'] });
queryClient.invalidateQueries({ queryKey: ['api-key-required'] });
},
});
// Mutation to select model
const selectModelMutation = useMutation({
mutationFn: async ({ provider, model }: { provider: string; model: string }) => {
const res = await fetch('/api/settings/model', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ provider, model }),
});
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['client-settings'] });
queryClient.invalidateQueries({ queryKey: ['api-key-required'] });
},
});
const handleSaveApiKey = (provider: string) => {
const key = apiKeys[provider as keyof ApiKeyState];
if (key) {
updateApiKeyMutation.mutate({ provider, api_key: key });
}
};
const handleModelChange = (value: string) => {
const [provider, model] = value.split('/');
selectModelMutation.mutate({ provider, model });
};
const toggleShowKey = (provider: string) => {
setShowKeys((prev) => ({ ...prev, [provider]: !prev[provider] }));
};
const providers = [
{ id: 'groq', name: 'Groq', icon: '⚡', description: 'Fast inference (Recommended)' },
{ id: 'google', name: 'Google', icon: '🔮', description: 'Gemini models' },
{ id: 'openai', name: 'OpenAI', icon: '🤖', description: 'GPT-4 models' },
{ id: 'anthropic', name: 'Anthropic', icon: '🧠', description: 'Claude models' },
];
const modelOptions = (settingsData?.available_models ?? []).map((m) => ({
value: `${m.provider}/${m.model}`,
label: `${m.name}${m.default ? ' (Default)' : ''}`,
}));
const currentModel = settingsData?.selected_model
? `${settingsData.selected_model.provider}/${settingsData.selected_model.model}`
: 'groq/gpt-oss-120b';
const renderSectionContent = () => {
switch (activeSection) {
case 'general':
return (
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold text-white mb-1">General Settings</h3>
<p className="text-sm text-gray-400">Configure basic application behavior</p>
</div>
{/* API Key Required Warning */}
{keyRequired?.required && (
<div className="flex items-center gap-3 p-4 bg-amber-500/10 border border-amber-500/30 rounded-xl">
<AlertCircle className="w-5 h-5 text-amber-400 flex-shrink-0" />
<div>
<p className="text-sm font-medium text-amber-400">API Key Required</p>
<p className="text-xs text-amber-400/70">{keyRequired.message}</p>
</div>
</div>
)}
<div className="space-y-4">
<Toggle
label="WebSocket Updates"
description="Enable real-time episode updates via WebSocket connection"
checked={localSettings.enableWebSocket ?? true}
onChange={(checked) => setLocalSettings((prev) => ({ ...prev, enableWebSocket: checked }))}
/>
<Toggle
label="Memory Persistence"
description="Persist memory data across episodes for better context retention"
checked={localSettings.memoryPersistence ?? false}
onChange={(checked) => setLocalSettings((prev) => ({ ...prev, memoryPersistence: checked }))}
/>
<Toggle
label="Auto-save Episodes"
description="Automatically save episode data when completed"
checked={localSettings.autoSave ?? true}
onChange={(checked) => setLocalSettings((prev) => ({ ...prev, autoSave: checked }))}
/>
<Toggle
label="Debug Mode"
description="Enable verbose logging and debugging information"
checked={localSettings.debugMode ?? false}
onChange={(checked) => setLocalSettings((prev) => ({ ...prev, debugMode: checked }))}
/>
</div>
{/* System Status */}
<div className="pt-4 border-t border-gray-700/50">
<h4 className="text-sm font-medium text-gray-300 mb-3">System Status</h4>
<div className="grid grid-cols-2 gap-3">
<div className="p-3 bg-gray-900/50 rounded-lg">
<div className="flex items-center gap-2">
<Server className="w-4 h-4 text-emerald-400" />
<span className="text-xs text-gray-400">Backend</span>
</div>
<p className="text-sm font-medium text-white mt-1">
{isBackendOnline ? 'Connected' : 'Disconnected'}
</p>
</div>
<div className="p-3 bg-gray-900/50 rounded-lg">
<div className="flex items-center gap-2">
<Globe className="w-4 h-4 text-cyan-400" />
<span className="text-xs text-gray-400">Version</span>
</div>
<p className="text-sm font-medium text-white mt-1">{health?.version || 'v0.1.0'}</p>
</div>
</div>
</div>
</div>
);
case 'api-keys':
return (
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold text-white mb-1">API Keys</h3>
<p className="text-sm text-gray-400">
Configure your provider API keys. Server keys are used by default, but you can override them here.
</p>
</div>
<div className="space-y-4">
{providers.map((provider) => {
const isConfigured = settingsData?.api_keys_configured?.[provider.id] ?? false;
return (
<div key={provider.id} className="p-4 bg-gray-900/50 border border-gray-700/30 rounded-xl">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-3">
<span className="text-2xl">{provider.icon}</span>
<div>
<span className="text-sm font-medium text-white">{provider.name}</span>
<p className="text-xs text-gray-500">{provider.description}</p>
</div>
</div>
<Badge variant={isConfigured ? 'success' : 'warning'} size="sm">
{isConfigured ? 'Active' : 'Not Set'}
</Badge>
</div>
<div className="flex gap-2">
<div className="flex-1 relative">
<Input
type={showKeys[provider.id] ? 'text' : 'password'}
placeholder={`Enter ${provider.name} API key...`}
value={apiKeys[provider.id as keyof ApiKeyState]}
onChange={(e) =>
setApiKeys((prev) => ({
...prev,
[provider.id]: e.target.value,
}))
}
className="pr-10"
/>
<button
type="button"
onClick={() => toggleShowKey(provider.id)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300 transition-colors"
>
{showKeys[provider.id] ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
<Button
size="sm"
variant="primary"
onClick={() => handleSaveApiKey(provider.id)}
disabled={!apiKeys[provider.id as keyof ApiKeyState]}
>
Save
</Button>
</div>
</div>
);
})}
</div>
{updateApiKeyMutation.isSuccess && (
<div className="flex items-center gap-2 p-3 bg-emerald-500/10 border border-emerald-500/30 rounded-lg">
<CheckCircle className="w-4 h-4 text-emerald-400" />
<span className="text-sm text-emerald-400">API key saved successfully</span>
</div>
)}
</div>
);
case 'models':
return (
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold text-white mb-1">AI Models</h3>
<p className="text-sm text-gray-400">Select the AI model to use for scraping tasks</p>
</div>
<div className="p-4 bg-gray-900/50 border border-gray-700/30 rounded-xl">
<div className="flex items-center gap-2 text-sm font-medium text-white mb-3">
<Zap className="w-4 h-4 text-emerald-400" />
Active Model
</div>
<Select
label=""
options={modelOptions}
value={currentModel}
onChange={(e) => handleModelChange(e.target.value)}
placeholder="Select model"
/>
{selectModelMutation.isPending && (
<p className="text-xs text-gray-400 mt-2">Switching model...</p>
)}
</div>
{/* Model Categories */}
<div className="grid grid-cols-2 gap-3">
<div className="p-4 bg-cyan-500/10 border border-cyan-500/30 rounded-xl">
<h4 className="text-sm font-medium text-cyan-400 mb-2">Text Models</h4>
<p className="text-xs text-gray-400">GPT-4, Claude, Gemini for text generation</p>
</div>
<div className="p-4 bg-purple-500/10 border border-purple-500/30 rounded-xl">
<h4 className="text-sm font-medium text-purple-400 mb-2">Vision Models</h4>
<p className="text-xs text-gray-400">GPT-4V, Gemini Pro Vision for image analysis</p>
</div>
<div className="p-4 bg-amber-500/10 border border-amber-500/30 rounded-xl">
<h4 className="text-sm font-medium text-amber-400 mb-2">Embedding Models</h4>
<p className="text-xs text-gray-400">Text embeddings for semantic search</p>
</div>
<div className="p-4 bg-emerald-500/10 border border-emerald-500/30 rounded-xl">
<h4 className="text-sm font-medium text-emerald-400 mb-2">Fast Models</h4>
<p className="text-xs text-gray-400">Groq, Mistral for fast inference</p>
</div>
</div>
</div>
);
case 'budget':
return (
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold text-white mb-1">Budget & Limits</h3>
<p className="text-sm text-gray-400">Configure API usage limits and budget controls</p>
</div>
<div className="p-4 bg-gray-900/50 border border-gray-700/30 rounded-xl">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-3">
<Wallet className="w-5 h-5 text-amber-400" />
<div>
<h4 className="text-sm font-medium text-white">Enable Budget Limits</h4>
<p className="text-xs text-gray-500">Control API spending with usage limits</p>
</div>
</div>
<button
onClick={() => setBudgetEnabled(!budgetEnabled)}
className={classNames(
'relative w-12 h-6 rounded-full transition-colors',
budgetEnabled ? 'bg-emerald-500' : 'bg-gray-600'
)}
>
<span
className={classNames(
'absolute top-1 w-4 h-4 bg-white rounded-full transition-transform',
budgetEnabled ? 'translate-x-7' : 'translate-x-1'
)}
/>
</button>
</div>
{budgetEnabled ? (
<div className="space-y-4 pt-4 border-t border-gray-700/50">
<div>
<label className="text-xs text-gray-400 mb-2 block">Daily Limit ($)</label>
<Input type="number" placeholder="10.00" className="bg-gray-800/50" />
</div>
<div>
<label className="text-xs text-gray-400 mb-2 block">Monthly Limit ($)</label>
<Input type="number" placeholder="100.00" className="bg-gray-800/50" />
</div>
<div>
<label className="text-xs text-gray-400 mb-2 block">Max Tokens per Request</label>
<Input type="number" placeholder="4096" className="bg-gray-800/50" />
</div>
<Toggle
label="Alert at 80% usage"
description="Receive notification when approaching limit"
checked={true}
onChange={() => {}}
/>
</div>
) : (
<div className="pt-4 border-t border-gray-700/50">
<p className="text-sm text-gray-500 text-center py-4">
Budget limits are disabled. Enable to control API spending.
</p>
</div>
)}
</div>
</div>
);
case 'appearance':
return (
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold text-white mb-1">Appearance</h3>
<p className="text-sm text-gray-400">Customize the look and feel of ScrapeRL</p>
</div>
<div className="space-y-4">
<div className="p-4 bg-gray-900/50 border border-gray-700/30 rounded-xl">
<h4 className="text-sm font-medium text-white mb-3">Theme</h4>
<div className="grid grid-cols-3 gap-3">
<button className="p-3 bg-gray-800 border-2 border-emerald-500 rounded-lg text-center">
<div className="w-8 h-8 bg-gray-900 rounded mx-auto mb-2" />
<span className="text-xs text-white">Dark</span>
</button>
<button className="p-3 bg-gray-800 border border-gray-600 rounded-lg text-center opacity-50">
<div className="w-8 h-8 bg-white rounded mx-auto mb-2" />
<span className="text-xs text-gray-400">Light</span>
</button>
<button className="p-3 bg-gray-800 border border-gray-600 rounded-lg text-center opacity-50">
<div className="w-8 h-8 bg-gradient-to-b from-white to-gray-900 rounded mx-auto mb-2" />
<span className="text-xs text-gray-400">Auto</span>
</button>
</div>
</div>
<Toggle
label="Compact Mode"
description="Reduce padding and spacing for more content"
checked={false}
onChange={() => {}}
/>
<Toggle
label="Show Animations"
description="Enable UI animations and transitions"
checked={true}
onChange={() => {}}
/>
</div>
</div>
);
case 'notifications':
return (
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold text-white mb-1">Notifications</h3>
<p className="text-sm text-gray-400">Configure when and how you receive alerts</p>
</div>
<div className="space-y-4">
<Toggle
label="Episode Completion"
description="Notify when an episode finishes"
checked={true}
onChange={() => {}}
/>
<Toggle
label="Error Alerts"
description="Alert on scraping errors"
checked={true}
onChange={() => {}}
/>
<Toggle
label="Budget Warnings"
description="Warn when approaching budget limits"
checked={true}
onChange={() => {}}
/>
<Toggle
label="System Updates"
description="Notify about new features and updates"
checked={false}
onChange={() => {}}
/>
</div>
</div>
);
case 'advanced':
return (
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold text-white mb-1">Advanced Settings</h3>
<p className="text-sm text-gray-400">For power users and developers</p>
</div>
<div className="space-y-4">
<Toggle
label="Developer Mode"
description="Enable advanced debugging tools"
checked={false}
onChange={() => {}}
/>
<Toggle
label="Experimental Features"
description="Try new features before release"
checked={false}
onChange={() => {}}
/>
<Toggle
label="Verbose Logging"
description="Log all API requests and responses"
checked={false}
onChange={() => {}}
/>
<div className="pt-4 border-t border-gray-700/50">
<h4 className="text-sm font-medium text-white mb-3">Data Management</h4>
<div className="flex gap-3">
<Button variant="secondary" size="sm">
Export Data
</Button>
<Button variant="ghost" size="sm" className="text-red-400 hover:text-red-300">
Clear Cache
</Button>
</div>
</div>
</div>
</div>
);
default:
return null;
}
};
return (
<div className={classNames('flex h-[calc(100vh-120px)]', className)}>
{/* Left Sidebar */}
<div className="w-64 bg-gray-800/30 border-r border-gray-700/50 flex flex-col">
<div className="p-4 border-b border-gray-700/50">
<h2 className="text-lg font-semibold text-white flex items-center gap-2">
<SettingsIcon className="w-5 h-5 text-purple-400" />
Settings
</h2>
<p className="text-xs text-gray-500 mt-1">Configure your environment</p>
</div>
<nav className="flex-1 p-3 space-y-1 overflow-y-auto">
{sectionConfig.map((section) => {
const Icon = section.icon;
const isActive = activeSection === section.id;
return (
<button
key={section.id}
onClick={() => setActiveSection(section.id)}
className={classNames(
'w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-all group',
isActive
? 'bg-emerald-500/20 border border-emerald-500/30 text-emerald-400'
: 'hover:bg-gray-700/50 text-gray-400 hover:text-gray-200'
)}
>
<Icon className={classNames('w-4 h-4', isActive ? 'text-emerald-400' : 'text-gray-500 group-hover:text-gray-300')} />
<span className="text-sm font-medium">{section.label}</span>
<ChevronRight className={classNames('w-4 h-4 ml-auto transition-transform', isActive ? 'rotate-90' : '')} />
</button>
);
})}
</nav>
{/* Status Footer */}
<div className="p-4 border-t border-gray-700/50">
<div className="flex items-center gap-2">
<div className={classNames('w-2 h-2 rounded-full', isBackendOnline ? 'bg-emerald-400' : 'bg-red-400')} />
<span className="text-xs text-gray-400">{isBackendOnline ? 'System Online' : 'System Offline'}</span>
</div>
</div>
</div>
{/* Main Content */}
<div className="flex-1 overflow-y-auto">
<div className="p-6">
{settingsLoading ? (
<div className="flex items-center justify-center py-16">
<div className="flex flex-col items-center gap-3">
<SettingsIcon className="w-8 h-8 text-gray-500 animate-spin" />
<p className="text-gray-400">Loading settings...</p>
</div>
</div>
) : (
renderSectionContent()
)}
</div>
</div>
</div>
);
};
export default Settings;
|