Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor: decompose CredentialsModal monolith into config-driven modules
trohitge8ab0cfd99a7
diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsxindex d6d4549d..cbf926c3 100644--- a/client/src/components/CredentialsModal.tsx+++ b/client/src/components/CredentialsModal.tsx@@ -1,3151 +1 @@-/**- * CredentialsModal - Two-panel credentials management- * Left: Category list with items- * Right: Detail/configuration panel for selected item (including QR pairing)- */--import React, { useState, useEffect, useCallback } from 'react';-import { Button, Tag, Alert, Descriptions, Space, InputNumber, Switch, Input, Collapse, Statistic, Spin, Select } from 'antd';-import {- CheckCircleOutlined,- SafetyOutlined,- ReloadOutlined,- DollarOutlined,- SettingOutlined,- TwitterOutlined,- GoogleOutlined,-} from '@ant-design/icons';-import Modal from './ui/Modal';-import QRCodeDisplay from './ui/QRCodeDisplay';-import ApiKeyInput from './ui/ApiKeyInput';-import { useApiKeys, ProviderDefaults, ProviderUsageSummary, APIUsageSummary, ModelConstraints } from '../hooks/useApiKeys';-import { useAppTheme } from '../hooks/useAppTheme';-import { useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useGoogleStatus, useTelegramStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';-import { useWhatsApp } from '../hooks/useWhatsApp';-import {- OpenAIIcon, ClaudeIcon, GeminiIcon, GroqIcon, OpenRouterIcon, CerebrasIcon,- DeepSeekIcon, KimiIcon, MistralIcon, AI_PROVIDER_META,-} from './icons/AIProviderIcons';-import { ApifyIcons } from '../assets/icons/apify';-import { SearchIcons } from '../assets/icons/search';-import { TelegramIcons } from '../assets/icons/telegram';-import { EmailIcons } from '../assets/icons/email';--// ============================================================================-// SERVICE ICONS-// ============================================================================--const GoogleMapsIcon = () => (- <svg width="20" height="20" viewBox="0 0 24 24" fill="none">- <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" fill="#EA4335"/>- <circle cx="12" cy="9" r="2.5" fill="#fff"/>- </svg>-);--const AndroidIcon = () => (- <svg width="20" height="20" viewBox="0 0 24 24" fill="#3DDC84">- <path d="M6 18c0 .55.45 1 1 1h1v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h2v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h1c.55 0 1-.45 1-1V8H6v10zM3.5 8C2.67 8 2 8.67 2 9.5v7c0 .83.67 1.5 1.5 1.5S5 17.33 5 16.5v-7C5 8.67 4.33 8 3.5 8zm17 0c-.83 0-1.5.67-1.5 1.5v7c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5v-7c0-.83-.67-1.5-1.5-1.5zm-4.97-5.84l1.3-1.3c.2-.2.2-.51 0-.71-.2-.2-.51-.2-.71 0l-1.48 1.48C13.85 1.23 12.95 1 12 1c-.96 0-1.86.23-2.66.63L7.85.15c-.2-.2-.51-.2-.71 0-.2.2-.2.51 0 .71l1.31 1.31C6.97 3.26 6 5.01 6 7h12c0-1.99-.97-3.75-2.47-4.84zM10 5H9V4h1v1zm5 0h-1V4h1v1z"/>- </svg>-);--const WhatsAppIcon = () => (- <svg width="20" height="20" viewBox="0 0 24 24" fill="#25D366">- <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>- </svg>-);--const XIcon = () => (- <TwitterOutlined style={{ fontSize: 20, color: '#000000' }} />-);--const TelegramIcon = () => (- <div- dangerouslySetInnerHTML={{ __html: TelegramIcons.telegram }}- style={{ width: 20, height: 20 }}- />-);--const EmailIcon = () => (- <div- dangerouslySetInnerHTML={{ __html: EmailIcons.read }}- style={{ width: 20, height: 20 }}- />-);--const GoogleWorkspaceIcon = () => (- <GoogleOutlined style={{ fontSize: 20, color: '#4285F4' }} />-);--const ApifyIcon = () => {- // Replace the raw SVG to ensure it scales to container- const scaledSvg = ApifyIcons.apify.replace('<svg', '<svg width="100%" height="100%"');- return (- <div- dangerouslySetInnerHTML={{ __html: scaledSvg }}- style={{ width: 20, height: 20 }}- />- );-};--const BraveSearchIcon = () => {- const ref = React.useRef<HTMLDivElement>(null);- React.useEffect(() => { if (ref.current) ref.current.innerHTML = SearchIcons.brave; }, []);- return <div ref={ref} style={{ width: 20, height: 20 }} />;-};--const SerperSearchIcon = () => {- const ref = React.useRef<HTMLDivElement>(null);- React.useEffect(() => { if (ref.current) ref.current.innerHTML = SearchIcons.serper; }, []);- return <div ref={ref} style={{ width: 20, height: 20 }} />;-};--const PerplexitySearchIcon = () => {- const ref = React.useRef<HTMLDivElement>(null);- React.useEffect(() => { if (ref.current) ref.current.innerHTML = SearchIcons.perplexity; }, []);- return <div ref={ref} style={{ width: 20, height: 20 }} />-};--// ============================================================================-// TYPES & DATA-// ============================================================================--interface CredentialItem {- id: string;- name: string;- placeholder: string;- color: string;- desc: string;- Icon?: React.FC<{ size?: number }>;- CustomIcon?: React.FC;- isSpecial?: boolean;- panelType?: 'whatsapp' | 'android' | 'twitter' | 'telegram' | 'gmail' | 'google_maps' | 'search' | 'email';-}--interface Category {- key: string;- label: string;- items: CredentialItem[];-}--const CATEGORIES: Category[] = [- {- key: 'ai',- label: 'AI Providers',- items: [- { id: 'openai', name: 'OpenAI', placeholder: 'sk-...', color: AI_PROVIDER_META.openai.color, desc: 'GPT-4o, GPT-4, GPT-3.5', Icon: OpenAIIcon },- { id: 'anthropic', name: 'Anthropic', placeholder: 'sk-ant-...', color: AI_PROVIDER_META.anthropic.color, desc: 'Claude 3.5 Sonnet, Opus', Icon: ClaudeIcon },- { id: 'gemini', name: 'Gemini', placeholder: 'AIza...', color: AI_PROVIDER_META.gemini.color, desc: 'Gemini 2.0, 1.5 Pro/Flash', Icon: GeminiIcon },- { id: 'groq', name: 'Groq', placeholder: 'gsk_...', color: AI_PROVIDER_META.groq.color, desc: 'Llama, Mixtral - Ultra-fast', Icon: GroqIcon },- { id: 'cerebras', name: 'Cerebras', placeholder: 'csk-...', color: AI_PROVIDER_META.cerebras.color, desc: 'Llama, Qwen - Ultra-fast', Icon: CerebrasIcon },- { id: 'openrouter', name: 'OpenRouter', placeholder: 'sk-or-...', color: AI_PROVIDER_META.openrouter.color, desc: 'Unified API - 200+ models', Icon: OpenRouterIcon },- { id: 'deepseek', name: 'DeepSeek', placeholder: 'sk-...', color: AI_PROVIDER_META.deepseek.color, desc: 'DeepSeek V3, Reasoner', Icon: DeepSeekIcon },- { id: 'kimi', name: 'Kimi', placeholder: 'sk-...', color: AI_PROVIDER_META.kimi.color, desc: 'Kimi K2.5 - Moonshot AI', Icon: KimiIcon },- { id: 'mistral', name: 'Mistral', placeholder: 'sk-...', color: AI_PROVIDER_META.mistral.color, desc: 'Mistral Large, Small, Codestral', Icon: MistralIcon },- ],- },- {- key: 'social',- label: 'Social Media',- items: [- { id: 'whatsapp_personal', name: 'WhatsApp Personal', placeholder: '', color: '#25D366', desc: 'Connect via QR code pairing', CustomIcon: WhatsAppIcon, isSpecial: true, panelType: 'whatsapp' },- { id: 'twitter', name: 'Twitter/X', placeholder: '', color: '#000000', desc: 'Post tweets, search, user lookup', CustomIcon: XIcon, isSpecial: true, panelType: 'twitter' },- { id: 'telegram', name: 'Telegram Bot', placeholder: '', color: '#0088CC', desc: 'Send messages via Telegram bot', CustomIcon: TelegramIcon, isSpecial: true, panelType: 'telegram' },- ],- },- {- key: 'productivity',- label: 'Productivity',- items: [- { id: 'gmail', name: 'Google Workspace', placeholder: '', color: '#4285F4', desc: 'Gmail, Calendar, Drive, Sheets, Tasks, Contacts', CustomIcon: GoogleWorkspaceIcon, isSpecial: true, panelType: 'gmail' },- ],- },- {- key: 'email',- label: 'Email',- items: [- { id: 'email_himalaya', name: 'Email (IMAP/SMTP)', placeholder: '', color: '#268bd2', desc: 'Gmail, Outlook, Yahoo, iCloud, Fastmail, ProtonMail, custom', CustomIcon: EmailIcon, isSpecial: true, panelType: 'email' },- ],- },- {- key: 'android',- label: 'Android',- items: [- { id: 'android_remote', name: 'Android Device', placeholder: 'your-api-key...', color: '#3DDC84', desc: 'API key + QR code pairing', CustomIcon: AndroidIcon, isSpecial: true, panelType: 'android' },- ],- },- {- key: 'search',- label: 'Search',- items: [- { id: 'brave_search', name: 'Brave Search', placeholder: 'BSA...', color: '#FB542B', desc: 'Web search via Brave Search API', CustomIcon: BraveSearchIcon },- { id: 'perplexity', name: 'Perplexity', placeholder: 'pplx-...', color: '#20808D', desc: 'AI-powered search with citations', CustomIcon: PerplexitySearchIcon },- ],- },- {- key: 'scrapers',- label: 'Scrapers',- items: [- { id: 'apify', name: 'Apify', placeholder: 'apify_api_...', color: '#246DFF', desc: 'Web scraping, social media extraction', CustomIcon: ApifyIcon },- { id: 'serper', name: 'Serper', placeholder: '', color: '#4285F4', desc: 'Google SERP scraping via Serper API', CustomIcon: SerperSearchIcon },- ],- },- {- key: 'services',- label: 'Services',- items: [- { id: 'google_maps', name: 'Google Maps', placeholder: 'AIza...', color: '#EA4335', desc: 'Geocoding, Places, Directions', CustomIcon: GoogleMapsIcon, panelType: 'google_maps' },- ],- },-];---// ============================================================================-// MAIN COMPONENT-// ============================================================================--interface Props {- visible: boolean;- onClose: () => void;-}--const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {- const theme = useAppTheme();-const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, validateGoogleMapsKey, validateApifyKey, getProviderDefaults, saveProviderDefaults, getProviderUsageSummary, getAPIUsageSummary, getStoredModels, getModelConstraints, isConnected } = useApiKeys();- const whatsappStatus = useWhatsAppStatus();- const androidStatus = useAndroidStatus();- const twitterStatus = useTwitterStatus();- const googleStatus = useGoogleStatus();- const telegramStatus = useTelegramStatus();--- // Tag style helper - consistent theming for status tags- const getTagStyle = (type: 'success' | 'error' | 'warning'): React.CSSProperties => {- const color = type === 'success' ? theme.dracula.green- : type === 'error' ? theme.dracula.pink- : theme.dracula.orange;- return {- backgroundColor: `${color}25`,- borderColor: `${color}60`,- color: color,- };- };-- const [validKeys, setValidKeys] = useState<Record<string, boolean>>({});- const [loading, setLoading] = useState<Record<string, boolean>>({});- const [models, setModels] = useState<Record<string, string[]>>({});- const [keys, setKeys] = useState<Record<string, string>>({});- // const [proxyUrls, setProxyUrls] = useState<Record<string, string>>({}); // Proxy disabled for now- const [selectedItem, setSelectedItem] = useState<CredentialItem | null>(null);-- // Provider defaults state- const [providerDefaults, setProviderDefaults] = useState<Record<string, ProviderDefaults>>({});- const [defaultsLoading, setDefaultsLoading] = useState<Record<string, boolean>>({});- const [defaultsDirty, setDefaultsDirty] = useState<Record<string, boolean>>({});-- // Model constraints per provider (fetched from model registry when default model changes)- const [modelConstraints, setModelConstraints] = useState<Record<string, ModelConstraints>>({});-- // Usage & Costs state (LLM providers)- const [usageSummary, setUsageSummary] = useState<ProviderUsageSummary[]>([]);- const [usageLoading, setUsageLoading] = useState(false);- const [usageExpanded, setUsageExpanded] = useState(false);-- // API usage state (for Twitter, Google Maps, etc.)- const [apiUsage, setApiUsage] = useState<Record<string, APIUsageSummary | null>>({});- const [apiUsageLoading, setApiUsageLoading] = useState<Record<string, boolean>>({});-- // Load stored keys and proxy URLs- const loadKeys = useCallback(async () => {- const allItems = CATEGORIES.flatMap(c => c.items);- const newKeys: Record<string, string> = {};- const newValid: Record<string, boolean> = {};- for (const item of allItems) {- if (item.isSpecial) continue;- if (await hasStoredKey(item.id)) {- const key = await getStoredApiKey(item.id);- if (key) {- newKeys[item.id] = key;- newValid[item.id] = true;- }- }- }- setKeys(newKeys);- setValidKeys(newValid);- }, [hasStoredKey, getStoredApiKey]);-- useEffect(() => {- if (visible && isConnected) {- loadKeys();- // Select first item by default- const firstItem = CATEGORIES[0]?.items[0];- if (firstItem) setSelectedItem(firstItem);- }- }, [visible, isConnected, loadKeys]);-- // Load provider defaults and models when AI provider is selected- useEffect(() => {- const isAIProvider = CATEGORIES.find(c => c.key === 'ai')?.items.some(i => i.id === selectedItem?.id);- if (selectedItem && !selectedItem.isSpecial && isAIProvider && isConnected) {- // Load defaults if not already loaded- if (!providerDefaults[selectedItem.id]) {- const loadDefaults = async () => {- setDefaultsLoading(l => ({ ...l, [selectedItem.id]: true }));- const defaults = await getProviderDefaults(selectedItem.id);- setProviderDefaults(p => ({ ...p, [selectedItem.id]: defaults }));- setDefaultsLoading(l => ({ ...l, [selectedItem.id]: false }));- };- loadDefaults();- }- // Load models if not already loaded- if (!models[selectedItem.id]) {- const loadModels = async () => {- const storedModels = await getStoredModels(selectedItem.id);- if (storedModels && storedModels.length > 0) {- setModels(m => ({ ...m, [selectedItem.id]: storedModels }));- }- };- loadModels();- }- }- }, [selectedItem, isConnected, getProviderDefaults, providerDefaults, getStoredModels, models]);-- // Fetch model constraints when provider defaults are loaded (for the default model)- useEffect(() => {- if (!selectedItem || !isConnected) return;- const provider = selectedItem.id;- const defaults = providerDefaults[provider];- if (!defaults?.default_model || modelConstraints[provider]) return;- getModelConstraints(defaults.default_model, provider).then(constraints => {- setModelConstraints(c => ({ ...c, [provider]: constraints }));- });- }, [selectedItem, isConnected, providerDefaults, modelConstraints, getModelConstraints]);-- // Handler to update a single default value- const updateProviderDefault = (provider: string, key: keyof ProviderDefaults, value: number | boolean | string) => {- // When model changes, fetch new constraints and update max_tokens to model max- if (key === 'default_model' && typeof value === 'string' && value) {- getModelConstraints(value, provider).then(constraints => {- setModelConstraints(c => ({ ...c, [provider]: constraints }));- if (constraints.max_output_tokens) {- setProviderDefaults(p => ({- ...p,- [provider]: { ...p[provider], max_tokens: constraints.max_output_tokens } as ProviderDefaults,- }));- }- });- }- setProviderDefaults(p => ({- ...p,- [provider]: { ...(p[provider] || {}), [key]: value } as ProviderDefaults- }));- setDefaultsDirty(d => ({ ...d, [provider]: true }));- };-- // Handler to save provider defaults- const handleSaveProviderDefaults = async (provider: string) => {- setDefaultsLoading(l => ({ ...l, [provider]: true }));- const success = await saveProviderDefaults(provider, providerDefaults[provider]);- if (success) {- setDefaultsDirty(d => ({ ...d, [provider]: false }));- }- setDefaultsLoading(l => ({ ...l, [provider]: false }));- };-- // Load usage summary when expanded- const loadUsageSummary = useCallback(async () => {- if (!isConnected) return;- setUsageLoading(true);- try {- const summary = await getProviderUsageSummary();- setUsageSummary(summary);- } catch (error) {- console.warn('Error loading usage summary:', error);- } finally {- setUsageLoading(false);- }- }, [getProviderUsageSummary, isConnected]);-- // Load usage when section is expanded- useEffect(() => {- if (usageExpanded && isConnected) {- loadUsageSummary();- }- }, [usageExpanded, isConnected, loadUsageSummary]);-- // Load API usage for services (Twitter, Google Maps, etc.)- const loadApiUsage = useCallback(async (service: string) => {- if (!isConnected) return;- setApiUsageLoading(l => ({ ...l, [service]: true }));- try {- const services = await getAPIUsageSummary(service);- const usage = services.find(s => s.service === service) || null;- setApiUsage(u => ({ ...u, [service]: usage }));- } catch (error) {- console.warn(`Error loading ${service} usage:`, error);- } finally {- setApiUsageLoading(l => ({ ...l, [service]: false }));- }- }, [getAPIUsageSummary, isConnected]);-- useEffect(() => {- const panelType = selectedItem?.panelType;- if (panelType === 'twitter' && isConnected) {- loadApiUsage('twitter');- } else if (panelType === 'gmail' && isConnected) {- loadApiUsage('gmail');- } else if (panelType === 'google_maps' && isConnected) {- loadApiUsage('google_maps');- }- }, [selectedItem, isConnected, loadApiUsage]);-- const handleValidate = async (id: string) => {- const key = keys[id];- if (!key?.trim()) return;-- setLoading(l => ({ ...l, [id]: true }));- const result = id === 'google_maps'- ? await validateGoogleMapsKey(key)- : id === 'apify'- ? await validateApifyKey(key)- : id === 'android_remote'- ? await saveApiKey(id, key)- : await validateApiKey(id, key);- setLoading(l => ({ ...l, [id]: false }));-- if (result.isValid) {- setValidKeys(v => ({ ...v, [id]: true }));- if (result.models) setModels(m => ({ ...m, [id]: result.models! }));- }- };-- const handleRemove = async (id: string) => {- await removeApiKey(id);- setKeys(k => ({ ...k, [id]: '' }));- setValidKeys(v => ({ ...v, [id]: false }));- setModels(m => ({ ...m, [id]: [] }));- };-- // Get status for special items- const getSpecialStatus = (item: CredentialItem) => {- if (item.panelType === 'whatsapp') {- return { connected: whatsappStatus.connected, label: whatsappStatus.connected ? 'Connected' : 'Not Connected' };- }- if (item.panelType === 'android') {- return { connected: androidStatus.paired, label: androidStatus.paired ? 'Paired' : 'Not Paired' };- }- if (item.panelType === 'twitter') {- return { connected: twitterStatus.connected, label: twitterStatus.connected ? `@${twitterStatus.username}` : 'Not Connected' };- }- if (item.panelType === 'gmail') {- return { connected: googleStatus.connected, label: googleStatus.connected ? googleStatus.email : 'Not Connected' };- }- if (item.panelType === 'telegram') {- return { connected: telegramStatus.connected, label: telegramStatus.connected ? `@${telegramStatus.bot_username}` : 'Not Connected' };- }- if (item.panelType === 'email') {- return {- connected: !!emailStored,- label: emailStored && emailAddress ? emailAddress : 'Not configured',- };- }- return null;- };-- // Count configured items- const totalConfigured = Object.values(validKeys).filter(Boolean).length;-- // Header actions- const headerActions = (- <div style={{- display: 'flex',- gap: theme.spacing.lg,- alignItems: 'center',- }}>- <div style={{- display: 'flex',- alignItems: 'center',- gap: theme.spacing.sm,- fontSize: theme.fontSize.base,- fontWeight: theme.fontWeight.semibold,- color: theme.colors.text,- }}>- <SafetyOutlined style={{ fontSize: 18, color: theme.dracula.yellow }} />- <span>API Credentials</span>- </div>- <Tag- style={{- margin: 0,- fontSize: theme.fontSize.xs,- ...(totalConfigured > 0 ? getTagStyle('success') : {}),- }}- >- {totalConfigured} configured- </Tag>- </div>- );-- // Render left sidebar item- const renderSidebarItem = (item: CredentialItem) => {- const isSelected = selectedItem?.id === item.id;- const isValid = validKeys[item.id];- const specialStatus = item.isSpecial ? getSpecialStatus(item) : null;- const Icon = item.Icon;- const CustomIcon = item.CustomIcon;-- return (- <div- key={item.id}- onClick={() => setSelectedItem(item)}- style={{- display: 'flex',- alignItems: 'center',- gap: theme.spacing.md,- padding: `${theme.spacing.md} ${theme.spacing.lg}`,- cursor: 'pointer',- backgroundColor: isSelected ? `${item.color}15` : 'transparent',- borderLeft: isSelected ? `3px solid ${item.color}` : '3px solid transparent',- transition: 'all 0.15s ease',- }}- onMouseEnter={(e) => {- if (!isSelected) {- e.currentTarget.style.backgroundColor = theme.colors.backgroundHover;- }- }}- onMouseLeave={(e) => {- if (!isSelected) {- e.currentTarget.style.backgroundColor = 'transparent';- }- }}- >- {/* Icon */}- <div style={{- width: 32,- height: 32,- borderRadius: theme.borderRadius.md,- backgroundColor: `${item.color}15`,- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- flexShrink: 0,- }}>- {CustomIcon ? <CustomIcon /> : Icon ? <Icon size={18} /> : null}- </div>-- {/* Name */}- <div style={{ flex: 1, minWidth: 0 }}>- <div style={{- fontSize: theme.fontSize.sm,- fontWeight: theme.fontWeight.medium,- color: theme.colors.text,- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',- }}>- {item.name}- </div>- </div>-- {/* Status dot */}- {(isValid || specialStatus?.connected) && (- <div style={{- width: 8,- height: 8,- borderRadius: '50%',- backgroundColor: theme.dracula.green,- flexShrink: 0,- }} />- )}- </div>- );- };-- // WhatsApp actions- const { getStatus: getWhatsAppStatus, startConnection, restartConnection } = useWhatsApp();- const { sendRequest, setAndroidStatus, getWhatsAppRateLimitConfig, setWhatsAppRateLimitConfig, unpauseWhatsAppRateLimit } = useWebSocket();-- // Android state- const [androidApiKey, setAndroidApiKey] = useState('');- const [androidApiKeyStored, setAndroidApiKeyStored] = useState<boolean | null>(null);- const [androidLoading, setAndroidLoading] = useState<string | null>(null);- const [androidError, setAndroidError] = useState<string | null>(null);- const [whatsappLoading, setWhatsappLoading] = useState<string | null>(null);- const [whatsappError, setWhatsappError] = useState<string | null>(null);-- // Twitter state- const [twitterClientId, setTwitterClientId] = useState('');- const [twitterClientSecret, setTwitterClientSecret] = useState('');- const [twitterCredentialsStored, setTwitterCredentialsStored] = useState<boolean | null>(null);- const [twitterLoading, setTwitterLoading] = useState<string | null>(null);- const [twitterError, setTwitterError] = useState<string | null>(null);-- // Gmail state- const [gmailClientId, setGmailClientId] = useState('');- const [gmailClientSecret, setGmailClientSecret] = useState('');- const [gmailCredentialsStored, setGmailCredentialsStored] = useState<boolean | null>(null);- const [gmailLoading, setGmailLoading] = useState<string | null>(null);- const [gmailError, setGmailError] = useState<string | null>(null);-- // Telegram state- const [telegramToken, setTelegramToken] = useState('');- const [telegramTokenStored, setTelegramTokenStored] = useState<boolean | null>(null);- const [telegramLoading, setTelegramLoading] = useState<string | null>(null);- const [telegramError, setTelegramError] = useState<string | null>(null);-- // Email (Himalaya IMAP/SMTP) state- const [emailProvider, setEmailProvider] = useState<string>('gmail');- const [emailAddress, setEmailAddress] = useState<string>('');- const [emailPassword, setEmailPassword] = useState<string>('');- const [emailImapHost, setEmailImapHost] = useState<string>('');- const [emailImapPort, setEmailImapPort] = useState<number>(993);- const [emailSmtpHost, setEmailSmtpHost] = useState<string>('');- const [emailSmtpPort, setEmailSmtpPort] = useState<number>(465);- const [emailStored, setEmailStored] = useState<boolean | null>(null);- const [emailLoading, setEmailLoading] = useState<string | null>(null);- const [emailError, setEmailError] = useState<string | null>(null);-- // Rate limit state- const [rateLimitConfig, setRateLimitConfig] = useState<RateLimitConfig | null>(null);- const [rateLimitStats, setRateLimitStats] = useState<RateLimitStats | null>(null);- const [rateLimitExpanded, setRateLimitExpanded] = useState(false);- const [rateLimitLoading, setRateLimitLoading] = useState(false);- const [rateLimitDirty, setRateLimitDirty] = useState(false);-- // Load Android API key on mount- useEffect(() => {- if (visible) {- hasStoredKey('android_remote').then(async (has) => {- setAndroidApiKeyStored(has);- if (has) {- const key = await getStoredApiKey('android_remote');- if (key) setAndroidApiKey(key);- }- });- }- }, [visible, hasStoredKey, getStoredApiKey]);-- // Load Twitter credentials on mount- useEffect(() => {- if (visible) {- // Check if client_id is stored- hasStoredKey('twitter_client_id').then(async (has) => {- setTwitterCredentialsStored(has);- if (has) {- const clientId = await getStoredApiKey('twitter_client_id');- const clientSecret = await getStoredApiKey('twitter_client_secret');- if (clientId) setTwitterClientId(clientId);- if (clientSecret) setTwitterClientSecret(clientSecret);- }- });- }- }, [visible, hasStoredKey, getStoredApiKey]);-- // Load Google Workspace credentials on mount- useEffect(() => {- if (visible) {- hasStoredKey('google_client_id').then(async (has) => {- setGmailCredentialsStored(has);- if (has) {- const clientId = await getStoredApiKey('google_client_id');- const clientSecret = await getStoredApiKey('google_client_secret');- if (clientId) setGmailClientId(clientId);- if (clientSecret) setGmailClientSecret(clientSecret);- }- });- }- }, [visible, hasStoredKey, getStoredApiKey]);-- // Load Telegram token status on mount- useEffect(() => {- if (visible) {- hasStoredKey('telegram_bot_token').then((has) => {- setTelegramTokenStored(has);- });- }- }, [visible, hasStoredKey]);-- // Load Email credentials on mount- useEffect(() => {- if (!visible) return;- (async () => {- try {- const [provider, address, hasPassword, imapHost, imapPort, smtpHost, smtpPort] = await Promise.all([- getStoredApiKey('email_provider'),- getStoredApiKey('email_address'),- hasStoredKey('email_password'),- getStoredApiKey('email_imap_host'),- getStoredApiKey('email_imap_port'),- getStoredApiKey('email_smtp_host'),- getStoredApiKey('email_smtp_port'),- ]);- if (provider) setEmailProvider(provider);- if (address) setEmailAddress(address);- if (imapHost) setEmailImapHost(imapHost);- if (imapPort) setEmailImapPort(parseInt(imapPort, 10));- if (smtpHost) setEmailSmtpHost(smtpHost);- if (smtpPort) setEmailSmtpPort(parseInt(smtpPort, 10));- setEmailStored(!!hasPassword);- } catch {- setEmailStored(false);- }- })();- }, [visible, getStoredApiKey, hasStoredKey]);-- // Twitter handlers- const handleTwitterSaveCredentials = async () => {- if (!twitterClientId.trim()) {- setTwitterError('Client ID is required');- return;- }- setTwitterLoading('save');- setTwitterError(null);- try {- await saveApiKey('twitter_client_id', twitterClientId.trim());- if (twitterClientSecret.trim()) {- await saveApiKey('twitter_client_secret', twitterClientSecret.trim());- }- setTwitterCredentialsStored(true);- } catch (err: any) {- setTwitterError(err.message || 'Failed to save credentials');- } finally {- setTwitterLoading(null);- }- };-- const handleTwitterLogin = async () => {- setTwitterLoading('login');- setTwitterError(null);- try {- const response = await sendRequest('twitter_oauth_login', {});- if (response.success && response.url) {- window.open(response.url, '_blank');- } else if (!response.success) {- setTwitterError(response.error || 'Failed to start OAuth');- }- } catch (err: any) {- setTwitterError(err.message || 'Failed to start OAuth');- } finally {- setTwitterLoading(null);- }- };-- const handleTwitterLogout = async () => {- setTwitterLoading('logout');- setTwitterError(null);- try {- const response = await sendRequest('twitter_logout', {});- if (!response.success) {- setTwitterError(response.error || 'Failed to disconnect');- }- } catch (err: any) {- setTwitterError(err.message || 'Failed to disconnect');- } finally {- setTwitterLoading(null);- }- };-- const handleTwitterRefreshStatus = async () => {- setTwitterLoading('refresh');- setTwitterError(null);- try {- await sendRequest('twitter_oauth_status', {});- } catch (err: any) {- setTwitterError(err.message || 'Failed to refresh status');- } finally {- setTwitterLoading(null);- }- };-- // Gmail handlers- const handleGmailSaveCredentials = async () => {- if (!gmailClientId.trim()) {- setGmailError('Client ID is required');- return;- }- if (!gmailClientSecret.trim()) {- setGmailError('Client Secret is required');- return;- }- setGmailLoading('save');- setGmailError(null);- try {- // Save with google_ prefix (new standard)- await saveApiKey('google_client_id', gmailClientId.trim());- await saveApiKey('google_client_secret', gmailClientSecret.trim());- setGmailCredentialsStored(true);- } catch (err: any) {- setGmailError(err.message || 'Failed to save credentials');- } finally {- setGmailLoading(null);- }- };-- const handleGmailLogin = async () => {- setGmailLoading('login');- setGmailError(null);- try {- const response = await sendRequest('google_oauth_login', {});- if (response.success && response.url) {- window.open(response.url, '_blank');- } else if (!response.success) {- setGmailError(response.error || 'Failed to start OAuth');- }- } catch (err: any) {- setGmailError(err.message || 'Failed to start OAuth');- } finally {- setGmailLoading(null);- }- };-- const handleGmailLogout = async () => {- setGmailLoading('logout');- setGmailError(null);- try {- const response = await sendRequest('google_logout', {});- if (!response.success) {- setGmailError(response.error || 'Failed to disconnect');- }- } catch (err: any) {- setGmailError(err.message || 'Failed to disconnect');- } finally {- setGmailLoading(null);- }- };-- const handleGmailRefreshStatus = async () => {- setGmailLoading('refresh');- setGmailError(null);- try {- await sendRequest('google_oauth_status', {});- } catch (err: any) {- setGmailError(err.message || 'Failed to refresh status');- } finally {- setGmailLoading(null);- }- };-- // Telegram handlers- const handleTelegramConnect = async () => {- if (!telegramToken.trim()) {- setTelegramError('Bot token is required');- return;- }- setTelegramLoading('connect');- setTelegramError(null);- try {- const response = await sendRequest('telegram_connect', { token: telegramToken.trim() });- if (response.success) {- setTelegramTokenStored(true);- } else {- setTelegramError(response.error || 'Failed to connect');- }- } catch (err: any) {- setTelegramError(err.message || 'Failed to connect');- } finally {- setTelegramLoading(null);- }- };-- const handleTelegramDisconnect = async () => {- setTelegramLoading('disconnect');- setTelegramError(null);- try {- const response = await sendRequest('telegram_disconnect', {});- if (response.success) {- setTelegramTokenStored(false);- setTelegramToken('');- } else {- setTelegramError(response.error || 'Failed to disconnect');- }- } catch (err: any) {- setTelegramError(err.message || 'Failed to disconnect');- } finally {- setTelegramLoading(null);- }- };-- const handleTelegramReconnect = async () => {- setTelegramLoading('reconnect');- setTelegramError(null);- try {- const response = await sendRequest('telegram_reconnect', {});- if (!response.success) {- setTelegramError(response.error || 'Failed to reconnect');- }- } catch (err: any) {- setTelegramError(err.message || 'Failed to reconnect');- } finally {- setTelegramLoading(null);- }- };-- const handleTelegramSave = async () => {- if (!telegramToken.trim()) {- setTelegramError('Bot token is required');- return;- }- setTelegramLoading('save');- setTelegramError(null);- try {- await saveApiKey('telegram_bot_token', telegramToken.trim());- setTelegramTokenStored(true);- } catch (err: any) {- setTelegramError(err.message || 'Failed to save token');- } finally {- setTelegramLoading(null);- }- };-- // Email handlers (Himalaya IMAP/SMTP)- const handleEmailSave = async () => {- if (!emailAddress.trim()) {- setEmailError('Email address is required');- return;- }- if (!emailPassword.trim() && !emailStored) {- setEmailError('Password is required');- return;- }- if (emailProvider === 'custom') {- if (!emailImapHost.trim() || !emailSmtpHost.trim()) {- setEmailError('IMAP and SMTP host are required for custom provider');- return;- }- }- setEmailLoading('save');- setEmailError(null);- try {- await saveApiKey('email_provider', emailProvider);- await saveApiKey('email_address', emailAddress.trim());- if (emailPassword.trim()) {- await saveApiKey('email_password', emailPassword.trim());- }- if (emailProvider === 'custom') {- await saveApiKey('email_imap_host', emailImapHost.trim());- await saveApiKey('email_imap_port', String(emailImapPort));- await saveApiKey('email_smtp_host', emailSmtpHost.trim());- await saveApiKey('email_smtp_port', String(emailSmtpPort));- }- setEmailStored(true);- setEmailPassword('');- } catch (err: any) {- setEmailError(err.message || 'Failed to save email credentials');- } finally {- setEmailLoading(null);- }- };-- const handleEmailRemove = async () => {- setEmailLoading('remove');- setEmailError(null);- try {- await removeApiKey('email_password');- await removeApiKey('email_address');- await removeApiKey('email_provider');- await removeApiKey('email_imap_host');- await removeApiKey('email_imap_port');- await removeApiKey('email_smtp_host');- await removeApiKey('email_smtp_port');- setEmailStored(false);- setEmailAddress('');- setEmailPassword('');- setEmailImapHost('');- setEmailSmtpHost('');- } catch (err: any) {- setEmailError(err.message || 'Failed to remove credentials');- } finally {- setEmailLoading(null);- }- };-- const handleTelegramRefreshStatus = async () => {- setTelegramLoading('refresh');- setTelegramError(null);- try {- await sendRequest('telegram_status', {});- } catch (err: any) {- setTelegramError(err.message || 'Failed to refresh status');- } finally {- setTelegramLoading(null);- }- };-- // Android handlers- const handleAndroidSaveKey = async () => {- if (!androidApiKey.trim()) return;- setAndroidLoading('save');- try {- await saveApiKey('android_remote', androidApiKey);- setAndroidApiKeyStored(true);- } catch (err: any) {- setAndroidError(err.message || 'Failed to save API key');- } finally {- setAndroidLoading(null);- }- };-- const handleAndroidConnect = async () => {- setAndroidLoading('connect');- setAndroidError(null);- try {- const key = await getStoredApiKey('android_remote');- if (!key) {- setAndroidError('No API key configured');- setAndroidLoading(null);- return;- }- const response = await sendRequest('android_relay_connect', {- url: import.meta.env.VITE_ANDROID_RELAY_URL || '',- api_key: key,- });- console.log('[Android] Connect response:', response);- if (!response.success) {- setAndroidError(response.error || 'Failed to connect');- } else if (response.qr_data) {- console.log('[Android] Setting QR data from response');- // Use response data directly - don't rely on broadcast timing- setAndroidStatus(prev => ({- ...prev,- connected: true,- paired: false,- qr_data: response.qr_data,- session_token: response.session_token || prev.session_token,- }));- }- } catch (err: any) {- setAndroidError(err.message || 'Failed to connect');- } finally {- setAndroidLoading(null);- }- };-- const handleAndroidDisconnect = async () => {- setAndroidLoading('disconnect');- setAndroidError(null);- try {- const response = await sendRequest('android_relay_disconnect', {});- if (!response.success) {- setAndroidError(response.error || 'Failed to disconnect');- }- } catch (err: any) {- setAndroidError(err.message || 'Failed to disconnect');- } finally {- setAndroidLoading(null);- }- };-- // WhatsApp handlers- const handleWhatsAppStart = async () => {- setWhatsappLoading('start');- setWhatsappError(null);- try {- const result = await startConnection();- if (!result.success && result.message) {- setWhatsappError(result.message);- }- } catch (err: any) {- setWhatsappError(err.message || 'Failed to start');- } finally {- setWhatsappLoading(null);- }- };-- const handleWhatsAppRestart = async () => {- setWhatsappLoading('restart');- setWhatsappError(null);- try {- const result = await restartConnection();- if (!result.success && result.message) {- setWhatsappError(result.message);- }- } catch (err: any) {- setWhatsappError(err.message || 'Failed to restart');- } finally {- setWhatsappLoading(null);- }- };-- const handleWhatsAppRefresh = async () => {- setWhatsappLoading('refresh');- setWhatsappError(null);- try {- await getWhatsAppStatus();- } catch (err: any) {- setWhatsappError(err.message || 'Failed to refresh');- } finally {- setWhatsappLoading(null);- }- };-- // Rate limit handlers- const loadRateLimits = useCallback(async () => {- setRateLimitLoading(true);- try {- const result = await getWhatsAppRateLimitConfig();- if (result.success) {- setRateLimitConfig(result.config || null);- setRateLimitStats(result.stats || null);- setRateLimitDirty(false);- }- } catch (err) {- console.error('Failed to load rate limits:', err);- } finally {- setRateLimitLoading(false);- }- }, [getWhatsAppRateLimitConfig]);-- const handleRateLimitSave = async () => {- if (!rateLimitConfig) return;- setRateLimitLoading(true);- try {- const result = await setWhatsAppRateLimitConfig(rateLimitConfig);- if (result.success && result.config) {- setRateLimitConfig(result.config);- setRateLimitDirty(false);- }- } catch (err) {- console.error('Failed to save rate limits:', err);- } finally {- setRateLimitLoading(false);- }- };-- const handleRateLimitUnpause = async () => {- setRateLimitLoading(true);- try {- const result = await unpauseWhatsAppRateLimit();- if (result.success && result.stats) {- setRateLimitStats(result.stats);- }- } catch (err) {- console.error('Failed to unpause rate limit:', err);- } finally {- setRateLimitLoading(false);- }- };-- const updateRateLimitConfig = (key: keyof RateLimitConfig, value: any) => {- if (!rateLimitConfig) return;- setRateLimitConfig({ ...rateLimitConfig, [key]: value });- setRateLimitDirty(true);- };-- // Load rate limits when WhatsApp panel is selected and connected- useEffect(() => {- if (selectedItem?.panelType === 'whatsapp' && whatsappStatus.connected && rateLimitExpanded) {- loadRateLimits();- }- }, [selectedItem, whatsappStatus.connected, rateLimitExpanded, loadRateLimits]);-- // Render API usage panel for services (Twitter, Google Maps, etc.)- const renderApiUsagePanel = (service: string, serviceName: string) => (- <Collapse- style={{ marginBottom: theme.spacing.lg, background: 'transparent' }}- items={[{- key: `${service}-usage`,- label: (- <Space>- <DollarOutlined style={{ color: theme.dracula.yellow }} />- <span>API Usage & Costs</span>- {apiUsage[service] && (- <Tag style={{- backgroundColor: `${theme.dracula.green}25`,- borderColor: `${theme.dracula.green}60`,- color: theme.dracula.green,- }}>- ${apiUsage[service]!.total_cost.toFixed(4)}- </Tag>- )}- </Space>- ),- children: apiUsageLoading[service] ? (- <div style={{ textAlign: 'center', padding: 16 }}><Spin size="small" /></div>- ) : apiUsage[service] ? (- <div>- <div style={{- display: 'grid',- gridTemplateColumns: 'repeat(3, 1fr)',- gap: theme.spacing.md,- marginBottom: theme.spacing.md,- }}>- <Statistic- title="Total Cost"- value={apiUsage[service]!.total_cost}- precision={4}- prefix="$"- valueStyle={{ color: theme.dracula.green, fontSize: 18 }}- />- <Statistic- title="API Calls"- value={apiUsage[service]!.execution_count}- valueStyle={{ color: theme.dracula.cyan, fontSize: 18 }}- />- <Statistic- title="Resources"- value={apiUsage[service]!.total_resources}- valueStyle={{ color: theme.dracula.purple, fontSize: 18 }}- />- </div>- {apiUsage[service]!.operations?.length > 0 && (- <div style={{- borderTop: `1px solid ${theme.colors.border}`,- paddingTop: theme.spacing.md,- }}>- <div style={{- fontSize: theme.fontSize.xs,- color: theme.colors.textSecondary,- marginBottom: theme.spacing.sm,- }}>- Operations Breakdown- </div>- {apiUsage[service]!.operations.map(op => (- <div- key={op.operation}- style={{- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- padding: '4px 0',- borderBottom: `1px solid ${theme.colors.border}`,- }}- >- <span style={{ fontFamily: 'monospace', fontSize: 12 }}>{op.operation}</span>- <Space size="small">- <Tag style={{ margin: 0 }}>{op.resource_count} resources</Tag>- <Tag style={{- margin: 0,- backgroundColor: `${theme.dracula.green}15`,- color: theme.dracula.green,- border: 'none',- }}>- ${op.total_cost.toFixed(4)}- </Tag>- </Space>- </div>- ))}- </div>- )}- <Button- size="small"- icon={<ReloadOutlined />}- onClick={() => loadApiUsage(service)}- style={{ marginTop: theme.spacing.md }}- >- Refresh- </Button>- </div>- ) : (- <div style={{ color: theme.colors.textSecondary, textAlign: 'center', padding: 16 }}>- No usage data yet. Use {serviceName} nodes in your workflows to track costs.- </div>- ),- }]}- />- );-- // Render detail panel for selected item- const renderDetailPanel = () => {- if (!selectedItem) {- return (- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- height: '100%',- color: theme.colors.textMuted,- fontSize: theme.fontSize.sm,- }}>- Select a credential to configure- </div>- );- }-- // WhatsApp panel- if (selectedItem.panelType === 'whatsapp') {- return (- <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>- {/* Scrollable content area */}- <div style={{ flex: 1, overflow: 'auto', padding: theme.spacing.xl }}>- <Descriptions- title={<Space><WhatsAppIcon /> WhatsApp Personal</Space>}- bordered- column={1}- size="small"- style={{- marginBottom: theme.spacing.lg,- background: theme.colors.backgroundAlt,- borderRadius: theme.borderRadius.md,- }}- styles={{- label: {- backgroundColor: theme.colors.backgroundPanel,- color: theme.colors.textSecondary,- fontWeight: theme.fontWeight.medium,- },- content: {- backgroundColor: theme.colors.background,- color: theme.colors.text,- },- }}- >- <Descriptions.Item label="Status">- <Tag style={getTagStyle(whatsappStatus.connected ? 'success' : 'error')}>- {whatsappStatus.connected ? 'Connected' : 'Disconnected'}- </Tag>- </Descriptions.Item>- <Descriptions.Item label="Session">- <Tag style={getTagStyle(whatsappStatus.has_session ? 'success' : 'error')}>- {whatsappStatus.has_session ? 'Active' : 'Inactive'}- </Tag>- </Descriptions.Item>- <Descriptions.Item label="Service">- <Tag style={getTagStyle(whatsappStatus.running ? 'success' : 'error')}>- {whatsappStatus.running ? 'Running' : 'Stopped'}- </Tag>- </Descriptions.Item>- {whatsappStatus.device_id && (- <Descriptions.Item label="Device">- <span style={{ fontFamily: 'monospace', fontSize: theme.fontSize.xs }}>- {whatsappStatus.device_id.slice(0, 24)}...- </span>- </Descriptions.Item>- )}- </Descriptions>-- {/* QR Code */}- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- backgroundColor: theme.colors.backgroundAlt,- borderRadius: theme.borderRadius.lg,- marginBottom: theme.spacing.lg,- padding: theme.spacing.xl,- }}>- <QRCodeDisplay- value={whatsappStatus.qr}- isConnected={whatsappStatus.connected}- size={280}- connectedTitle="Already Connected!"- connectedSubtitle="No QR code needed"- loading={whatsappStatus.running && !whatsappStatus.qr && !whatsappStatus.connected}- emptyText={whatsappStatus.running ? 'Waiting for QR code...' : 'Start service to get QR code'}- />- {!whatsappStatus.connected && whatsappStatus.qr && (- <div style={{ marginTop: theme.spacing.md, color: theme.colors.textSecondary, fontSize: theme.fontSize.sm }}>- Scan with WhatsApp mobile app- </div>- )}- </div>-- {/* Rate Limits Section */}- {whatsappStatus.connected && (- <div style={{- marginBottom: theme.spacing.lg,- border: `1px solid ${theme.colors.border}`,- borderRadius: theme.borderRadius.md,- overflow: 'hidden'- }}>- <div- onClick={() => setRateLimitExpanded(!rateLimitExpanded)}- style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- padding: theme.spacing.sm,- backgroundColor: theme.colors.backgroundAlt,- cursor: 'pointer',- }}- >- <span style={{ fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, color: theme.colors.text }}>- {rateLimitExpanded ? '▼' : '▶'} Rate Limits- </span>- <span onClick={(e) => e.stopPropagation()}>- <Switch- size="small"- checked={rateLimitConfig?.enabled ?? true}- onChange={(checked) => updateRateLimitConfig('enabled', checked)}- />- </span>- </div>- {rateLimitExpanded && (- <div style={{ padding: theme.spacing.md }}>- {rateLimitLoading && !rateLimitConfig ? (- <div style={{ textAlign: 'center', color: theme.colors.textSecondary, fontSize: theme.fontSize.sm }}>Loading...</div>- ) : rateLimitConfig ? (- <>- {/* Stats Section */}- {rateLimitStats && (- <div style={{- display: 'grid',- gridTemplateColumns: 'repeat(3, 1fr)',- gap: theme.spacing.sm,- marginBottom: theme.spacing.md,- padding: theme.spacing.sm,- backgroundColor: theme.colors.backgroundPanel,- borderRadius: theme.borderRadius.sm- }}>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Last Minute</div>- <div style={{ fontSize: theme.fontSize.lg, color: theme.colors.text, fontWeight: theme.fontWeight.semibold }}>{rateLimitStats.messages_sent_last_minute}</div>- </div>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Last Hour</div>- <div style={{ fontSize: theme.fontSize.lg, color: theme.colors.text, fontWeight: theme.fontWeight.semibold }}>{rateLimitStats.messages_sent_last_hour}</div>- </div>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Today</div>- <div style={{ fontSize: theme.fontSize.lg, color: theme.colors.text, fontWeight: theme.fontWeight.semibold }}>{rateLimitStats.messages_sent_today}</div>- </div>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>New Contacts</div>- <div style={{ fontSize: theme.fontSize.lg, color: theme.colors.text, fontWeight: theme.fontWeight.semibold }}>{rateLimitStats.new_contacts_today}</div>- </div>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Responses</div>- <div style={{ fontSize: theme.fontSize.lg, color: theme.colors.text, fontWeight: theme.fontWeight.semibold }}>{rateLimitStats.responses_received}</div>- </div>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Response Rate</div>- <div style={{ fontSize: theme.fontSize.lg, color: theme.colors.text, fontWeight: theme.fontWeight.semibold }}>{Math.round((rateLimitStats.response_rate || 0) * 100)}%</div>- </div>- </div>- )}- {rateLimitStats?.is_paused && (- <Alert type="warning" message={rateLimitStats.pause_reason || 'Paused'} action={<Button size="small" onClick={handleRateLimitUnpause}>Unpause</Button>} style={{ marginBottom: theme.spacing.md }} />- )}-- {/* Delays Section */}- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs, fontWeight: theme.fontWeight.medium }}>- Message Delays (milliseconds)- </div>- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: theme.spacing.sm, marginBottom: theme.spacing.md }}>- <div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>Min Delay</div>- <InputNumber size="small" value={rateLimitConfig.min_delay_ms} onChange={(v) => updateRateLimitConfig('min_delay_ms', v ?? 3000)} style={{ width: '100%' }} />- </div>- <div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>Max Delay</div>- <InputNumber size="small" value={rateLimitConfig.max_delay_ms} onChange={(v) => updateRateLimitConfig('max_delay_ms', v ?? 8000)} style={{ width: '100%' }} />- </div>- <div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>Typing Duration</div>- <InputNumber size="small" value={rateLimitConfig.typing_delay_ms} onChange={(v) => updateRateLimitConfig('typing_delay_ms', v ?? 2000)} style={{ width: '100%' }} />- </div>- <div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>Link Extra Delay</div>- <InputNumber size="small" value={rateLimitConfig.link_extra_delay_ms} onChange={(v) => updateRateLimitConfig('link_extra_delay_ms', v ?? 5000)} style={{ width: '100%' }} />- </div>- </div>-- {/* Limits Section */}- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs, fontWeight: theme.fontWeight.medium }}>- Message Limits- </div>- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: theme.spacing.sm, marginBottom: theme.spacing.md }}>- <div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>Per Minute</div>- <InputNumber size="small" value={rateLimitConfig.max_messages_per_minute} onChange={(v) => updateRateLimitConfig('max_messages_per_minute', v ?? 10)} style={{ width: '100%' }} />- </div>- <div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>Per Hour</div>- <InputNumber size="small" value={rateLimitConfig.max_messages_per_hour} onChange={(v) => updateRateLimitConfig('max_messages_per_hour', v ?? 60)} style={{ width: '100%' }} />- </div>- <div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>New Contacts/Day</div>- <InputNumber size="small" value={rateLimitConfig.max_new_contacts_per_day} onChange={(v) => updateRateLimitConfig('max_new_contacts_per_day', v ?? 20)} style={{ width: '100%' }} />- </div>- </div>-- {/* Behavior Section */}- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs, fontWeight: theme.fontWeight.medium }}>- Behavior- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: theme.spacing.sm, marginBottom: theme.spacing.md }}>- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>- <div>- <div style={{ fontSize: theme.fontSize.sm, color: theme.colors.text }}>Simulate Typing</div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Show typing indicator before sending</div>- </div>- <Switch size="small" checked={rateLimitConfig.simulate_typing} onChange={(v) => updateRateLimitConfig('simulate_typing', v)} />- </div>- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>- <div>- <div style={{ fontSize: theme.fontSize.sm, color: theme.colors.text }}>Randomize Delays</div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Add variance between min/max delay</div>- </div>- <Switch size="small" checked={rateLimitConfig.randomize_delays} onChange={(v) => updateRateLimitConfig('randomize_delays', v)} />- </div>- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>- <div>- <div style={{ fontSize: theme.fontSize.sm, color: theme.colors.text }}>Pause on Low Response</div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Auto-pause if response rate drops below threshold</div>- </div>- <Switch size="small" checked={rateLimitConfig.pause_on_low_response} onChange={(v) => updateRateLimitConfig('pause_on_low_response', v)} />- </div>- {rateLimitConfig.pause_on_low_response && (- <div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>Response Rate Threshold (%)</div>- <InputNumber- size="small"- value={Math.round((rateLimitConfig.response_rate_threshold || 0.3) * 100)}- onChange={(v) => updateRateLimitConfig('response_rate_threshold', (v ?? 30) / 100)}- min={0}- max={100}- style={{ width: '100%' }}- />- </div>- )}- </div>-- <Button- size="small"- onClick={handleRateLimitSave}- loading={rateLimitLoading}- disabled={!rateLimitDirty}- block- style={{- backgroundColor: rateLimitDirty ? `${theme.dracula.green}25` : undefined,- borderColor: rateLimitDirty ? `${theme.dracula.green}60` : undefined,- color: rateLimitDirty ? theme.dracula.green : undefined,- }}- >- Save Changes- </Button>- </>- ) : (- <div style={{ textAlign: 'center', color: theme.colors.textSecondary, fontSize: theme.fontSize.sm }}>Failed to load</div>- )}- </div>- )}- </div>- )}-- {whatsappError && (- <Alert type="error" message={whatsappError} showIcon style={{ marginBottom: theme.spacing.lg }} />- )}- </div>-- {/* Actions - Fixed at bottom */}- <div style={{- display: 'flex',- gap: theme.spacing.sm,- justifyContent: 'center',- padding: theme.spacing.md,- borderTop: `1px solid ${theme.colors.border}`,- backgroundColor: theme.colors.background,- flexShrink: 0,- }}>- <Button- onClick={handleWhatsAppStart}- loading={whatsappLoading === 'start'}- style={{- backgroundColor: `${theme.dracula.green}25`,- borderColor: `${theme.dracula.green}60`,- color: theme.dracula.green,- }}- >- Start- </Button>- <Button- onClick={handleWhatsAppRestart}- loading={whatsappLoading === 'restart'}- style={{- backgroundColor: `${theme.dracula.orange}25`,- borderColor: `${theme.dracula.orange}60`,- color: theme.dracula.orange,- }}- >- Restart- </Button>- <Button- onClick={handleWhatsAppRefresh}- loading={whatsappLoading === 'refresh'}- style={{- backgroundColor: `${theme.dracula.cyan}25`,- borderColor: `${theme.dracula.cyan}60`,- color: theme.dracula.cyan,- }}- >- Refresh- </Button>- </div>- </div>- );- }-- // Android panel- if (selectedItem.panelType === 'android') {- return (- <div style={{ padding: theme.spacing.xl, display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>- {/* API Key Input */}- <div style={{ marginBottom: theme.spacing.lg }}>- <ApiKeyInput- value={androidApiKey}- onChange={setAndroidApiKey}- onSave={handleAndroidSaveKey}- onDelete={async () => {- await removeApiKey('android_remote');- setAndroidApiKey('');- setAndroidApiKeyStored(false);- }}- placeholder="Enter Android Relay API key..."- loading={androidLoading === 'save'}- isStored={androidApiKeyStored}- />- </div>-- <Descriptions- title={<Space><AndroidIcon /> Android Device</Space>}- bordered- column={1}- size="small"- style={{- marginBottom: theme.spacing.xl,- background: theme.colors.backgroundAlt,- borderRadius: theme.borderRadius.md,- }}- styles={{- label: {- backgroundColor: theme.colors.backgroundPanel,- color: theme.colors.textSecondary,- fontWeight: theme.fontWeight.medium,- },- content: {- backgroundColor: theme.colors.background,- color: theme.colors.text,- },- }}- >- <Descriptions.Item label="API Key">- <Tag style={getTagStyle((androidApiKeyStored || androidStatus.connected) ? 'success' : 'error')}>- {androidApiKeyStored === null ? 'Checking...' : (androidApiKeyStored || androidStatus.connected) ? 'Configured' : 'Not configured'}- </Tag>- </Descriptions.Item>- <Descriptions.Item label="Relay">- <Tag style={getTagStyle(androidStatus.connected ? 'success' : 'error')}>- {androidStatus.connected ? 'Connected' : 'Disconnected'}- </Tag>- </Descriptions.Item>- <Descriptions.Item label="Device">- <Tag style={getTagStyle(androidStatus.paired ? 'success' : (androidStatus.connected ? 'warning' : 'error'))}>- {androidStatus.paired ? 'Paired' : (androidStatus.connected ? 'Waiting for pairing' : 'Not connected')}- </Tag>- </Descriptions.Item>- {androidStatus.device_name && (- <Descriptions.Item label="Device Name">- {androidStatus.device_name}- </Descriptions.Item>- )}- </Descriptions>-- {/* QR Code */}- <div style={{- flex: 1,- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- backgroundColor: theme.colors.backgroundAlt,- borderRadius: theme.borderRadius.lg,- marginBottom: theme.spacing.xl,- minHeight: 300,- }}>- <QRCodeDisplay- value={androidStatus.qr_data}- isConnected={androidStatus.paired}- size={280}- connectedTitle="Device Paired!"- connectedSubtitle={androidStatus.device_name || androidStatus.device_id || 'Android Device'}- loading={androidStatus.connected && !androidStatus.qr_data && !androidStatus.paired}- emptyText={androidApiKeyStored ? (androidStatus.connected ? 'Waiting for QR code...' : 'Click Connect to start') : 'Add API key first'}- />- {!androidStatus.paired && androidStatus.qr_data && (- <div style={{ marginTop: theme.spacing.md, color: theme.colors.textSecondary }}>- Scan with Android companion app- </div>- )}- </div>-- {!androidApiKeyStored && !androidStatus.connected && (- <Alert- type="warning"- message="API key required"- description="Configure your Android Relay API key above before connecting."- showIcon- style={{ marginBottom: theme.spacing.lg }}- />- )}-- {androidError && (- <Alert type="error" message={androidError} showIcon style={{ marginBottom: theme.spacing.lg }} />- )}-- {/* Actions - Fixed at bottom */}- <div style={{- display: 'flex',- gap: theme.spacing.sm,- justifyContent: 'center',- paddingTop: theme.spacing.md,- borderTop: `1px solid ${theme.colors.border}`,- }}>- <Button- onClick={handleAndroidConnect}- loading={androidLoading === 'connect'}- disabled={androidStatus.connected || !androidApiKeyStored}- style={{- backgroundColor: `${theme.dracula.green}25`,- borderColor: `${theme.dracula.green}60`,- color: theme.dracula.green,- }}- >- Connect- </Button>- <Button- onClick={async () => {- setAndroidLoading('reconnect');- setAndroidError(null);- try {- const key = await getStoredApiKey('android_remote');- if (!key) {- setAndroidError('No API key configured');- setAndroidLoading(null);- return;- }- const response = await sendRequest('android_relay_reconnect', {- url: import.meta.env.VITE_ANDROID_RELAY_URL || '',- api_key: key,- });- if (!response.success) {- setAndroidError(response.error || 'Failed to reconnect');- }- } catch (err: any) {- setAndroidError(err.message || 'Failed to reconnect');- } finally {- setAndroidLoading(null);- }- }}- loading={androidLoading === 'reconnect'}- disabled={!androidStatus.connected || !androidApiKeyStored}- style={{- backgroundColor: `${theme.dracula.orange}25`,- borderColor: `${theme.dracula.orange}60`,- color: theme.dracula.orange,- }}- >- Reconnect- </Button>- <Button- onClick={handleAndroidDisconnect}- loading={androidLoading === 'disconnect'}- disabled={!androidStatus.connected}- style={{- backgroundColor: `${theme.dracula.pink}25`,- borderColor: `${theme.dracula.pink}60`,- color: theme.dracula.pink,- }}- >- Disconnect- </Button>- </div>-- {androidStatus.connected && (- <div style={{ marginTop: theme.spacing.sm, fontSize: theme.fontSize.xs, color: theme.colors.textMuted, textAlign: 'center' }}>- Use Reconnect to get a new QR code if pairing fails- </div>- )}- </div>- );- }-- // Twitter panel- if (selectedItem.panelType === 'twitter') {- return (- <div style={{ padding: theme.spacing.xl, display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>- <Descriptions- title={<Space><XIcon /> Twitter/X</Space>}- bordered- column={1}- size="small"- style={{- marginBottom: theme.spacing.xl,- background: theme.colors.backgroundAlt,- borderRadius: theme.borderRadius.md,- }}- styles={{- label: {- backgroundColor: theme.colors.backgroundPanel,- color: theme.colors.textSecondary,- fontWeight: theme.fontWeight.medium,- },- content: {- backgroundColor: theme.colors.background,- color: theme.colors.text,- },- }}- >- <Descriptions.Item label="Status">- <Tag style={getTagStyle(twitterStatus.connected ? 'success' : 'error')}>- {twitterStatus.connected ? 'Connected' : 'Not Connected'}- </Tag>- </Descriptions.Item>- <Descriptions.Item label="API Credentials">- <Tag style={getTagStyle(twitterCredentialsStored ? 'success' : 'error')}>- {twitterCredentialsStored === null ? 'Checking...' : twitterCredentialsStored ? 'Configured' : 'Not configured'}- </Tag>- </Descriptions.Item>- {twitterStatus.connected && twitterStatus.username && (- <Descriptions.Item label="Account">- <Space>- {twitterStatus.profile_image_url && (- <img- src={twitterStatus.profile_image_url}- alt={twitterStatus.username}- style={{ width: 24, height: 24, borderRadius: '50%' }}- />- )}- <span style={{ fontFamily: 'monospace', fontSize: theme.fontSize.sm }}>@{twitterStatus.username}</span>- {twitterStatus.name && <span style={{ color: theme.colors.textSecondary }}>({twitterStatus.name})</span>}- </Space>- </Descriptions.Item>- )}- </Descriptions>-- {/* API Credentials Input - Only show if not connected */}- {!twitterStatus.connected && (- <div style={{ marginBottom: theme.spacing.xl }}>- <label style={{- display: 'block',- fontSize: theme.fontSize.sm,- fontWeight: theme.fontWeight.medium,- color: theme.colors.text,- marginBottom: theme.spacing.sm,- }}>- Twitter API Credentials- </label>- <div style={{ marginBottom: theme.spacing.md }}>- <Input- value={twitterClientId}- onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTwitterClientId(e.target.value)}- placeholder="Client ID (from X Developer Portal)"- style={{- marginBottom: theme.spacing.sm,- backgroundColor: theme.colors.background,- borderColor: theme.colors.border,- color: theme.colors.text,- fontFamily: 'monospace',- fontSize: theme.fontSize.sm,- }}- />- <Input.Password- value={twitterClientSecret}- onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTwitterClientSecret(e.target.value)}- placeholder="Client Secret (optional for PKCE)"- style={{- backgroundColor: theme.colors.background,- borderColor: theme.colors.border,- color: theme.colors.text,- fontFamily: 'monospace',- fontSize: theme.fontSize.sm,- }}- />- </div>- <Button- onClick={handleTwitterSaveCredentials}- loading={twitterLoading === 'save'}- disabled={!twitterClientId.trim()}- style={{- backgroundColor: `${theme.dracula.purple}25`,- borderColor: `${theme.dracula.purple}60`,- color: theme.dracula.purple,- }}- >- Save Credentials- </Button>- <div style={{- fontSize: theme.fontSize.xs,- color: theme.colors.textMuted,- marginTop: theme.spacing.sm,- lineHeight: 1.5,- }}>- Get credentials from the X Developer Portal. Create an app with OAuth 2.0 enabled.- <br />- Callback URL: <code style={{ fontSize: theme.fontSize.xs, color: theme.dracula.cyan }}>http://localhost:3010/api/twitter/callback</code>- </div>- </div>- )}-- {twitterError && (- <Alert type="error" message={twitterError} showIcon style={{ marginBottom: theme.spacing.lg }} />- )}-- {/* API Usage Stats */}- {renderApiUsagePanel('twitter', 'Twitter')}-- {/* Info box */}- <div style={{- padding: theme.spacing.md,- borderRadius: theme.borderRadius.md,- backgroundColor: `${theme.dracula.cyan}10`,- border: `1px solid ${theme.dracula.cyan}30`,- marginBottom: theme.spacing.xl,- flex: 1,- }}>- <div style={{- fontSize: theme.fontSize.sm,- color: theme.colors.textSecondary,- lineHeight: 1.5,- }}>- {twitterStatus.connected ? (- <>Your Twitter account is connected. You can now use Twitter nodes in your workflows.</>- ) : twitterCredentialsStored ? (- <>Click Login with Twitter to authorize. A browser window will open for authentication.</>- ) : (- <>Enter your Twitter API credentials above to get started.</>- )}- </div>- </div>-- {/* Actions */}- <div style={{- display: 'flex',- gap: theme.spacing.sm,- justifyContent: 'center',- paddingTop: theme.spacing.md,- borderTop: `1px solid ${theme.colors.border}`,- }}>- {!twitterStatus.connected ? (- <Button- onClick={handleTwitterLogin}- loading={twitterLoading === 'login'}- disabled={!twitterCredentialsStored}- style={{- backgroundColor: `${theme.dracula.green}25`,- borderColor: `${theme.dracula.green}60`,- color: theme.dracula.green,- }}- >- Login with Twitter- </Button>- ) : (- <Button- onClick={handleTwitterLogout}- loading={twitterLoading === 'logout'}- style={{- backgroundColor: `${theme.dracula.pink}25`,- borderColor: `${theme.dracula.pink}60`,- color: theme.dracula.pink,- }}- >- Disconnect- </Button>- )}- <Button- onClick={handleTwitterRefreshStatus}- loading={twitterLoading === 'refresh'}- icon={<ReloadOutlined />}- style={{- backgroundColor: `${theme.dracula.cyan}25`,- borderColor: `${theme.dracula.cyan}60`,- color: theme.dracula.cyan,- }}- >- Refresh- </Button>- </div>- </div>- );- }-- // Telegram panel- if (selectedItem.panelType === 'telegram') {- return (- <div style={{ padding: theme.spacing.xl, display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>- <Descriptions- title={<Space><TelegramIcon /> Telegram Bot</Space>}- bordered- column={1}- size="small"- style={{- marginBottom: theme.spacing.xl,- background: theme.colors.backgroundAlt,- borderRadius: theme.borderRadius.md,- }}- styles={{- label: {- backgroundColor: theme.colors.backgroundPanel,- color: theme.colors.textSecondary,- fontWeight: theme.fontWeight.medium,- },- content: {- backgroundColor: theme.colors.background,- color: theme.colors.text,- },- }}- >- <Descriptions.Item label="Status">- <Tag style={getTagStyle(telegramStatus.connected ? 'success' : 'error')}>- {telegramStatus.connected ? 'Connected' : 'Not Connected'}- </Tag>- </Descriptions.Item>- <Descriptions.Item label="Token">- <Tag style={getTagStyle(telegramTokenStored ? 'success' : 'error')}>- {telegramTokenStored === null ? 'Checking...' : telegramTokenStored ? 'Stored' : 'Not configured'}- </Tag>- </Descriptions.Item>- {telegramStatus.connected && telegramStatus.bot_username && (- <Descriptions.Item label="Bot">- <span style={{ fontFamily: 'monospace', fontSize: theme.fontSize.sm }}>@{telegramStatus.bot_username}</span>- {telegramStatus.bot_name && <span style={{ color: theme.colors.textSecondary }}> ({telegramStatus.bot_name})</span>}- </Descriptions.Item>- )}- {telegramStatus.connected && telegramStatus.owner_chat_id && (- <Descriptions.Item label="Owner">- <span style={{ fontFamily: 'monospace', fontSize: theme.fontSize.sm }}>{telegramStatus.owner_chat_id}</span>- </Descriptions.Item>- )}- </Descriptions>-- {/* Bot Token Input - Only show if not connected */}- {!telegramStatus.connected && (- <div style={{ marginBottom: theme.spacing.xl }}>- <label style={{- display: 'block',- fontSize: theme.fontSize.sm,- fontWeight: theme.fontWeight.medium,- color: theme.colors.text,- marginBottom: theme.spacing.sm,- }}>- Bot Token- </label>- <Input.Password- value={telegramToken}- onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTelegramToken(e.target.value)}- placeholder="123456789:ABCdefGHIjklMNOpqrSTUvwxYZ"- style={{- marginBottom: theme.spacing.md,- backgroundColor: theme.colors.background,- borderColor: theme.colors.border,- color: theme.colors.text,- fontFamily: 'monospace',- fontSize: theme.fontSize.sm,- }}- />- <div style={{- fontSize: theme.fontSize.xs,- color: theme.colors.textMuted,- lineHeight: 1.5,- }}>- Get a bot token from <span style={{ color: theme.dracula.cyan }}>@BotFather</span> on Telegram.- After connecting, send any message to your bot to register as the owner.- </div>- </div>- )}-- {telegramError && (- <Alert type="error" message={telegramError} showIcon style={{ marginBottom: theme.spacing.lg }} />- )}-- {/* Info box */}- <div style={{- padding: theme.spacing.md,- borderRadius: theme.borderRadius.md,- backgroundColor: `${theme.dracula.cyan}10`,- border: `1px solid ${theme.dracula.cyan}30`,- marginBottom: theme.spacing.xl,- flex: 1,- }}>- <div style={{- fontSize: theme.fontSize.sm,- color: theme.colors.textSecondary,- lineHeight: 1.5,- }}>- {telegramStatus.connected ? (- <>Your Telegram bot is connected and polling for messages. Use Telegram nodes in your workflows.</>- ) : telegramTokenStored ? (- <>A bot token is stored. Click Reconnect to connect using the stored token.</>- ) : (- <>Enter your bot token from @BotFather to get started.</>- )}- </div>- </div>-- {/* Actions */}- <div style={{- display: 'flex',- gap: theme.spacing.sm,- justifyContent: 'center',- paddingTop: theme.spacing.md,- borderTop: `1px solid ${theme.colors.border}`,- }}>- {!telegramStatus.connected ? (- <>- <Button- onClick={handleTelegramConnect}- loading={telegramLoading === 'connect'}- disabled={!telegramToken.trim()}- style={{- backgroundColor: `${theme.dracula.green}25`,- borderColor: `${theme.dracula.green}60`,- color: theme.dracula.green,- }}- >- Connect- </Button>- {telegramToken.trim() && (- <Button- onClick={handleTelegramSave}- loading={telegramLoading === 'save'}- style={{- backgroundColor: `${theme.dracula.yellow}25`,- borderColor: `${theme.dracula.yellow}60`,- color: theme.dracula.yellow,- }}- >- Save- </Button>- )}- {telegramTokenStored && (- <Button- onClick={handleTelegramReconnect}- loading={telegramLoading === 'reconnect'}- style={{- backgroundColor: `${theme.dracula.purple}25`,- borderColor: `${theme.dracula.purple}60`,- color: theme.dracula.purple,- }}- >- Reconnect- </Button>- )}- </>- ) : (- <Button- onClick={handleTelegramDisconnect}- loading={telegramLoading === 'disconnect'}- style={{- backgroundColor: `${theme.dracula.pink}25`,- borderColor: `${theme.dracula.pink}60`,- color: theme.dracula.pink,- }}- >- Disconnect- </Button>- )}- <Button- onClick={handleTelegramRefreshStatus}- loading={telegramLoading === 'refresh'}- icon={<ReloadOutlined />}- style={{- backgroundColor: `${theme.dracula.cyan}25`,- borderColor: `${theme.dracula.cyan}60`,- color: theme.dracula.cyan,- }}- >- Refresh- </Button>- </div>- </div>- );- }-- // Email (Himalaya IMAP/SMTP) panel- if (selectedItem.panelType === 'email') {- const PROVIDER_OPTIONS = [- { label: 'Gmail', value: 'gmail' },- { label: 'Outlook / Office 365', value: 'outlook' },- { label: 'Yahoo Mail', value: 'yahoo' },- { label: 'iCloud Mail', value: 'icloud' },- { label: 'ProtonMail (Bridge)', value: 'protonmail' },- { label: 'Fastmail', value: 'fastmail' },- { label: 'Custom / Self-hosted', value: 'custom' },- ];- const AUTH_NOTES: Record<string, string> = {- gmail: 'Use an App Password from Google Account > Security > 2-Step Verification.',- outlook: 'Use your account password or an App Password.',- yahoo: 'Use an App Password from Yahoo Account Security.',- icloud: 'Use an App-Specific Password from your Apple ID.',- protonmail: 'Requires ProtonMail Bridge running locally (127.0.0.1).',- fastmail: 'Use an App Password from Settings > Privacy & Security.',- custom: 'Enter credentials for your self-hosted IMAP/SMTP server below.',- };- return (- <div style={{ padding: theme.spacing.xl, display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>- <Descriptions- title={<Space><EmailIcon /> Email (IMAP/SMTP via Himalaya)</Space>}- bordered- column={1}- size="small"- style={{- marginBottom: theme.spacing.xl,- background: theme.colors.backgroundAlt,- borderRadius: theme.borderRadius.md,- }}- styles={{- label: {- backgroundColor: theme.colors.backgroundPanel,- color: theme.colors.textSecondary,- fontWeight: theme.fontWeight.medium,- },- content: {- backgroundColor: theme.colors.background,- color: theme.colors.text,- },- }}- >- <Descriptions.Item label="Status">- <Tag style={getTagStyle(emailStored ? 'success' : 'error')}>- {emailStored === null ? 'Checking...' : emailStored ? 'Configured' : 'Not configured'}- </Tag>- </Descriptions.Item>- {emailStored && emailAddress && (- <Descriptions.Item label="Account">- <span style={{ fontFamily: 'monospace', fontSize: theme.fontSize.sm }}>{emailAddress}</span>- </Descriptions.Item>- )}- </Descriptions>-- <div style={{ marginBottom: theme.spacing.lg }}>- <label style={{- display: 'block',- fontSize: theme.fontSize.sm,- fontWeight: theme.fontWeight.medium,- color: theme.colors.text,- marginBottom: theme.spacing.sm,- }}>- Provider- </label>- <Select- value={emailProvider}- onChange={setEmailProvider}- options={PROVIDER_OPTIONS}- style={{ width: '100%' }}- />- </div>-- <div style={{ marginBottom: theme.spacing.lg }}>- <label style={{- display: 'block',- fontSize: theme.fontSize.sm,- fontWeight: theme.fontWeight.medium,- color: theme.colors.text,- marginBottom: theme.spacing.sm,- }}>- Email Address- </label>- <Input- value={emailAddress}- onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmailAddress(e.target.value)}- placeholder="[email protected]"- style={{- backgroundColor: theme.colors.background,- borderColor: theme.colors.border,- color: theme.colors.text,- }}- />- </div>-- <div style={{ marginBottom: theme.spacing.lg }}>- <label style={{- display: 'block',- fontSize: theme.fontSize.sm,- fontWeight: theme.fontWeight.medium,- color: theme.colors.text,- marginBottom: theme.spacing.sm,- }}>- Password {emailStored && (- <span style={{ color: theme.colors.textMuted, fontWeight: theme.fontWeight.normal }}>- (leave blank to keep existing)- </span>- )}- </label>- <Input.Password- value={emailPassword}- onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmailPassword(e.target.value)}- placeholder={emailStored ? '••••••••' : 'App password or account password'}- style={{- backgroundColor: theme.colors.background,- borderColor: theme.colors.border,- color: theme.colors.text,- fontFamily: 'monospace',- }}- />- <div style={{- fontSize: theme.fontSize.xs,- color: theme.colors.textMuted,- marginTop: theme.spacing.sm,- lineHeight: 1.5,- }}>- {AUTH_NOTES[emailProvider]}- </div>- </div>-- {emailProvider === 'custom' && (- <div style={{- padding: theme.spacing.md,- marginBottom: theme.spacing.lg,- border: `1px solid ${theme.colors.border}`,- borderRadius: theme.borderRadius.md,- backgroundColor: theme.colors.backgroundAlt,- }}>- <div style={{- fontSize: theme.fontSize.sm,- fontWeight: theme.fontWeight.medium,- color: theme.colors.text,- marginBottom: theme.spacing.md,- }}>- Custom IMAP / SMTP- </div>-- <div style={{ display: 'flex', gap: theme.spacing.md, marginBottom: theme.spacing.md }}>- <div style={{ flex: 2 }}>- <label style={{ display: 'block', fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>- IMAP Host- </label>- <Input- value={emailImapHost}- onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmailImapHost(e.target.value)}- placeholder="imap.example.com"- style={{ backgroundColor: theme.colors.background, borderColor: theme.colors.border, color: theme.colors.text }}- />- </div>- <div style={{ flex: 1 }}>- <label style={{ display: 'block', fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>- IMAP Port- </label>- <InputNumber- value={emailImapPort}- onChange={(v) => setEmailImapPort(typeof v === 'number' ? v : 993)}- min={1}- max={65535}- style={{ width: '100%' }}- />- </div>- </div>-- <div style={{ display: 'flex', gap: theme.spacing.md }}>- <div style={{ flex: 2 }}>- <label style={{ display: 'block', fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>- SMTP Host- </label>- <Input- value={emailSmtpHost}- onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmailSmtpHost(e.target.value)}- placeholder="smtp.example.com"- style={{ backgroundColor: theme.colors.background, borderColor: theme.colors.border, color: theme.colors.text }}- />- </div>- <div style={{ flex: 1 }}>- <label style={{ display: 'block', fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>- SMTP Port- </label>- <InputNumber- value={emailSmtpPort}- onChange={(v) => setEmailSmtpPort(typeof v === 'number' ? v : 465)}- min={1}- max={65535}- style={{ width: '100%' }}- />- </div>- </div>- </div>- )}-- {emailError && (- <Alert type="error" message={emailError} showIcon style={{ marginBottom: theme.spacing.lg }} />- )}-- <div style={{ flex: 1 }} />-- <div style={{- display: 'flex',- gap: theme.spacing.sm,- justifyContent: 'center',- paddingTop: theme.spacing.md,- borderTop: `1px solid ${theme.colors.border}`,- }}>- <Button- onClick={handleEmailSave}- loading={emailLoading === 'save'}- disabled={!emailAddress.trim() || (!emailPassword.trim() && !emailStored)}- style={{- backgroundColor: `${theme.dracula.green}25`,- borderColor: `${theme.dracula.green}60`,- color: theme.dracula.green,- }}- >- Save- </Button>- {emailStored && (- <Button- onClick={handleEmailRemove}- loading={emailLoading === 'remove'}- style={{- backgroundColor: `${theme.dracula.pink}25`,- borderColor: `${theme.dracula.pink}60`,- color: theme.dracula.pink,- }}- >- Remove- </Button>- )}- </div>- </div>- );- }-- // Google Workspace panel (Gmail, Calendar, Drive, Sheets, Tasks, Contacts)- if (selectedItem.panelType === 'gmail') {- return (- <div style={{ padding: theme.spacing.xl, display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>- <Descriptions- title={<Space><GoogleWorkspaceIcon /> Google Workspace</Space>}- bordered- column={1}- size="small"- style={{- marginBottom: theme.spacing.lg,- borderRadius: theme.borderRadius.md,- }}- styles={{- label: {- backgroundColor: theme.colors.backgroundPanel,- color: theme.colors.textSecondary,- fontWeight: theme.fontWeight.medium,- },- content: {- backgroundColor: theme.colors.background,- color: theme.colors.text,- },- }}- >- <Descriptions.Item label="Status">- <Tag style={getTagStyle(googleStatus.connected ? 'success' : 'error')}>- {googleStatus.connected ? 'Connected' : 'Not Connected'}- </Tag>- </Descriptions.Item>- <Descriptions.Item label="API Credentials">- <Tag style={getTagStyle(gmailCredentialsStored ? 'success' : 'error')}>- {gmailCredentialsStored === null ? 'Checking...' : gmailCredentialsStored ? 'Configured' : 'Not configured'}- </Tag>- </Descriptions.Item>- {googleStatus.connected && googleStatus.email && (- <Descriptions.Item label="Account">- <Space>- {googleStatus.profile_image_url && (- <img- src={googleStatus.profile_image_url}- alt={googleStatus.email}- style={{ width: 24, height: 24, borderRadius: '50%' }}- />- )}- <span style={{ fontFamily: theme.fontFamily.mono, fontSize: theme.fontSize.sm }}>{googleStatus.email}</span>- {googleStatus.name && <span style={{ color: theme.colors.textSecondary }}>({googleStatus.name})</span>}- </Space>- </Descriptions.Item>- )}- {googleStatus.connected && (- <Descriptions.Item label="Services">- <Space wrap size={[4, 4]}>- <Tag style={{ backgroundColor: `${theme.dracula.green}15`, borderColor: `${theme.dracula.green}40`, color: theme.dracula.green }}>Gmail</Tag>- <Tag style={{ backgroundColor: `${theme.dracula.cyan}15`, borderColor: `${theme.dracula.cyan}40`, color: theme.dracula.cyan }}>Calendar</Tag>- <Tag style={{ backgroundColor: `${theme.dracula.purple}15`, borderColor: `${theme.dracula.purple}40`, color: theme.dracula.purple }}>Drive</Tag>- <Tag style={{ backgroundColor: `${theme.dracula.orange}15`, borderColor: `${theme.dracula.orange}40`, color: theme.dracula.orange }}>Sheets</Tag>- <Tag style={{ backgroundColor: `${theme.dracula.pink}15`, borderColor: `${theme.dracula.pink}40`, color: theme.dracula.pink }}>Tasks</Tag>- <Tag style={{ backgroundColor: `${theme.dracula.yellow}15`, borderColor: `${theme.dracula.yellow}40`, color: theme.dracula.yellow }}>Contacts</Tag>- </Space>- </Descriptions.Item>- )}- </Descriptions>-- {/* API Credentials Input - Only show if not connected */}- {!googleStatus.connected && (- <div style={{ marginBottom: theme.spacing.xl }}>- <label style={{- display: 'block',- fontSize: theme.fontSize.sm,- fontWeight: theme.fontWeight.medium,- color: theme.colors.text,- marginBottom: theme.spacing.sm,- }}>- Google Workspace API Credentials- </label>- <div style={{ marginBottom: theme.spacing.md }}>- <Input- value={gmailClientId}- onChange={(e: React.ChangeEvent<HTMLInputElement>) => setGmailClientId(e.target.value)}- placeholder="Client ID (from Google Cloud Console)"- style={{- marginBottom: theme.spacing.sm,- backgroundColor: theme.colors.background,- borderColor: theme.colors.border,- color: theme.colors.text,- fontFamily: theme.fontFamily.mono,- fontSize: theme.fontSize.sm,- }}- />- <Input.Password- value={gmailClientSecret}- onChange={(e: React.ChangeEvent<HTMLInputElement>) => setGmailClientSecret(e.target.value)}- placeholder="Client Secret (required)"- style={{- backgroundColor: theme.colors.background,- borderColor: theme.colors.border,- color: theme.colors.text,- fontFamily: theme.fontFamily.mono,- fontSize: theme.fontSize.sm,- }}- />- </div>- <Button- onClick={handleGmailSaveCredentials}- loading={gmailLoading === 'save'}- disabled={!gmailClientId.trim() || !gmailClientSecret.trim()}- style={{- backgroundColor: `${theme.dracula.purple}25`,- borderColor: `${theme.dracula.purple}60`,- color: theme.dracula.purple,- }}- >- Save Credentials- </Button>- <div style={{- fontSize: theme.fontSize.xs,- color: theme.colors.textMuted,- marginTop: theme.spacing.sm,- lineHeight: 1.5,- }}>- Get credentials from Google Cloud Console. Enable Gmail, Calendar, Drive, Sheets, Tasks, and People APIs.- <br />- Callback URL: <code style={{ fontSize: theme.fontSize.xs, color: theme.dracula.cyan }}>http://localhost:3010/api/google/callback</code>- </div>- </div>- )}-- {gmailError && (- <Alert type="error" message={gmailError} showIcon style={{ marginBottom: theme.spacing.lg }} />- )}-- {/* API Usage Stats */}- {renderApiUsagePanel('google_workspace', 'Google Workspace')}-- {/* Info box */}- <div style={{- padding: theme.spacing.md,- borderRadius: theme.borderRadius.md,- backgroundColor: `${theme.dracula.cyan}10`,- border: `1px solid ${theme.dracula.cyan}30`,- marginBottom: theme.spacing.xl,- flex: 1,- }}>- <div style={{- fontSize: theme.fontSize.sm,- color: theme.colors.textSecondary,- lineHeight: 1.5,- }}>- {googleStatus.connected ? (- <>Your Google Workspace account is connected. You can now use Gmail, Calendar, Drive, Sheets, Tasks, and Contacts nodes in your workflows.</>- ) : gmailCredentialsStored ? (- <>Click Login with Google to authorize. A browser window will open for authentication.</>- ) : (- <>Enter your Google Workspace API credentials above to get started.</>- )}- </div>- </div>-- {/* Actions */}- <div style={{- display: 'flex',- gap: theme.spacing.sm,- justifyContent: 'center',- paddingTop: theme.spacing.md,- borderTop: `1px solid ${theme.colors.border}`,- }}>- {!googleStatus.connected ? (- <Button- onClick={handleGmailLogin}- loading={gmailLoading === 'login'}- disabled={!gmailCredentialsStored}- style={{- backgroundColor: `${theme.dracula.green}25`,- borderColor: `${theme.dracula.green}60`,- color: theme.dracula.green,- }}- >- Login with Google- </Button>- ) : (- <Button- onClick={handleGmailLogout}- loading={gmailLoading === 'logout'}- style={{- backgroundColor: `${theme.dracula.pink}25`,- borderColor: `${theme.dracula.pink}60`,- color: theme.dracula.pink,- }}- >- Disconnect- </Button>- )}- <Button- onClick={handleGmailRefreshStatus}- loading={gmailLoading === 'refresh'}- icon={<ReloadOutlined />}- style={{- backgroundColor: `${theme.dracula.cyan}25`,- borderColor: `${theme.dracula.cyan}60`,- color: theme.dracula.cyan,- }}- >- Refresh- </Button>- </div>- </div>- );- }-- const item = selectedItem;- const isValid = validKeys[item.id];- const Icon = item.Icon;- const CustomIcon = item.CustomIcon;-- return (- <div style={{ padding: theme.spacing.xl }}>- {/* Header */}- <div style={{- display: 'flex',- alignItems: 'center',- gap: theme.spacing.lg,- marginBottom: theme.spacing.xl,- paddingBottom: theme.spacing.lg,- borderBottom: `1px solid ${theme.colors.border}`,- }}>- <div style={{- width: 48,- height: 48,- borderRadius: theme.borderRadius.lg,- backgroundColor: `${item.color}15`,- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- }}>- {CustomIcon ? <CustomIcon /> : Icon ? <Icon size={24} /> : null}- </div>- <div>- <div style={{- fontSize: theme.fontSize.lg,- fontWeight: theme.fontWeight.semibold,- color: theme.colors.text,- marginBottom: 4,- }}>- {item.name}- </div>- <div style={{- fontSize: theme.fontSize.sm,- color: theme.colors.textSecondary,- }}>- {item.desc}- </div>- </div>- {isValid && (- <Tag- icon={<CheckCircleOutlined />}- style={{- marginLeft: 'auto',- backgroundColor: `${theme.dracula.green}25`,- borderColor: `${theme.dracula.green}60`,- color: theme.dracula.green,- }}- >- Connected- </Tag>- )}- </div>-- {/* API Key Input */}- <div style={{ marginBottom: theme.spacing.xl }}>- <label style={{- display: 'block',- fontSize: theme.fontSize.sm,- fontWeight: theme.fontWeight.medium,- color: theme.colors.text,- marginBottom: theme.spacing.sm,- }}>- API Key- </label>- <ApiKeyInput- value={keys[item.id] || ''}- onChange={(value) => {- setKeys(k => ({ ...k, [item.id]: value }));- setValidKeys(v => ({ ...v, [item.id]: false }));- }}- onSave={() => handleValidate(item.id)}- onDelete={isValid ? () => handleRemove(item.id) : undefined}- placeholder={item.placeholder}- loading={loading[item.id]}- isStored={isValid}- />- </div>-- {/* Proxy URL Input - Disabled for now */}-- {/* Default Parameters Section - Only for AI providers */}- {CATEGORIES.find(c => c.key === 'ai')?.items.some(i => i.id === item.id) && (- <div style={{ marginBottom: theme.spacing.xl }}>- <Collapse- ghost- defaultActiveKey={['defaults']}- items={[{- key: 'defaults',- label: (- <span style={{ fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, color: theme.colors.text }}>- <SettingOutlined style={{ marginRight: theme.spacing.sm }} />- Default Parameters- </span>- ),- children: (() => {- const mc = modelConstraints[item.id];- const tempMin = mc?.temperature_range?.[0] ?? 0;- const tempMax = mc?.temperature_range?.[1] ?? 2;- const maxOut = mc?.max_output_tokens;- const thinkType = mc?.thinking_type;- const canThink = mc?.supports_thinking;- const fixedTemp = mc?.is_reasoning_model && tempMin === tempMax;- const defaults = providerDefaults[item.id];- const rowStyle: React.CSSProperties = {- display: 'flex', alignItems: 'center', justifyContent: 'space-between',- padding: `${theme.spacing.sm} 0`,- };- const dividerStyle: React.CSSProperties = {- borderBottom: `1px solid ${theme.colors.border}40`,- marginBottom: 0,- };- const labelStyle: React.CSSProperties = {- fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, color: theme.colors.text,- };- const descStyle: React.CSSProperties = {- fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginTop: 2,- };-- return (- <div style={{- opacity: defaultsLoading[item.id] ? 0.6 : 1,- }}>- {/* Default Model */}- <div style={{ ...rowStyle, paddingTop: 0 }}>- <div style={{ flex: 1, minWidth: 0 }}>- <div style={labelStyle}>Default Model</div>- <div style={descStyle}>Model used when none specified</div>- </div>- <Select- size="small"- showSearch- value={defaults?.default_model || undefined}- onChange={(v) => updateProviderDefault(item.id, 'default_model', v)}- placeholder="Select model"- style={{ width: 220, flexShrink: 0 }}- options={(models[item.id] || []).map(m => ({ label: m, value: m }))}- filterOption={(input, option) =>- (option?.label ?? '').toLowerCase().includes(input.toLowerCase())- }- notFoundContent={models[item.id] ? 'No models found' : 'Validate API key first'}- virtual={false}- popupMatchSelectWidth={false}- getPopupContainer={(trigger) => trigger.parentElement || document.body}- listHeight={300}- />- </div>-- {/* Model capabilities from backend */}- {mc && (- <div style={{- display: 'flex', gap: 6, flexWrap: 'wrap',- padding: `${theme.spacing.sm} ${theme.spacing.md}`,- backgroundColor: `${theme.colors.backgroundAlt}`,- borderRadius: theme.borderRadius.sm,- marginBottom: theme.spacing.sm,- border: `1px solid ${theme.colors.border}30`,- }}>- {maxOut != null && (- <Tag style={{ ...getTagStyle('success'), margin: 0, fontSize: 11 }}>- Max Output: {maxOut.toLocaleString()}- </Tag>- )}- {mc.context_length != null && (- <Tag style={{ margin: 0, fontSize: 11, backgroundColor: `${theme.dracula.cyan}20`, borderColor: `${theme.dracula.cyan}50`, color: theme.dracula.cyan }}>- Context: {mc.context_length.toLocaleString()}- </Tag>- )}- <Tag style={{ margin: 0, fontSize: 11, backgroundColor: `${theme.dracula.purple}20`, borderColor: `${theme.dracula.purple}50`, color: theme.dracula.purple }}>- Temp: {tempMin}-{tempMax}- </Tag>- {canThink && (- <Tag style={{ ...getTagStyle('warning'), margin: 0, fontSize: 11 }}>- Thinking: {thinkType}- </Tag>- )}- {mc.is_reasoning_model && (- <Tag style={{ margin: 0, fontSize: 11, backgroundColor: `${theme.dracula.pink}20`, borderColor: `${theme.dracula.pink}50`, color: theme.dracula.pink }}>- Reasoning- </Tag>- )}- </div>- )}-- {/* Temperature - hide when backend says fixed */}- {!fixedTemp && (- <>- <div style={dividerStyle} />- <div style={rowStyle}>- <div>- <div style={labelStyle}>Temperature</div>- <div style={descStyle}>Controls randomness ({tempMin}-{tempMax})</div>- </div>- <InputNumber- size="small"- value={defaults?.temperature}- onChange={(v) => updateProviderDefault(item.id, 'temperature', v ?? 0.7)}- min={tempMin}- max={tempMax}- step={0.1}- style={{ width: 80 }}- />- </div>- </>- )}-- {/* Max Tokens - range from backend */}- <div style={dividerStyle} />- <div style={rowStyle}>- <div>- <div style={labelStyle}>Max Tokens</div>- <div style={descStyle}>- {maxOut != null ? `Up to ${maxOut.toLocaleString()}` : 'Maximum response length'}- </div>- </div>- <InputNumber- size="small"- value={defaults?.max_tokens}- onChange={(v) => updateProviderDefault(item.id, 'max_tokens', v ?? (maxOut || 4096))}- min={1}- max={maxOut || undefined}- style={{ width: 120 }}- />- </div>-- {/* Thinking toggle - only when backend says model supports it */}- {canThink && (- <>- <div style={dividerStyle} />- <div style={rowStyle}>- <div>- <div style={labelStyle}>Thinking/Reasoning</div>- <div style={descStyle}>Extended thinking ({thinkType})</div>- </div>- <Switch- size="small"- checked={defaults?.thinking_enabled ?? false}- onChange={(v) => updateProviderDefault(item.id, 'thinking_enabled', v)}- />- </div>- </>- )}-- {/* Thinking Budget - budget type from backend (Claude, Gemini) */}- {canThink && thinkType === 'budget' && defaults?.thinking_enabled && (- <>- <div style={dividerStyle} />- <div style={rowStyle}>- <div>- <div style={labelStyle}>Thinking Budget</div>- <div style={descStyle}>Token budget (1024-16000)</div>- </div>- <InputNumber- size="small"- value={defaults?.thinking_budget ?? 2048}- onChange={(v) => updateProviderDefault(item.id, 'thinking_budget', v ?? 2048)}- min={1024}- max={16000}- style={{ width: 100 }}- />- </div>- </>- )}-- {/* Reasoning Effort - effort type from backend (OpenAI o-series, GPT-5) */}- {canThink && thinkType === 'effort' && defaults?.thinking_enabled && (- <>- <div style={dividerStyle} />- <div style={rowStyle}>- <div>- <div style={labelStyle}>Reasoning Effort</div>- <div style={descStyle}>Low, medium, or high</div>- </div>- <Select- size="small"- value={defaults?.reasoning_effort ?? 'medium'}- onChange={(v) => updateProviderDefault(item.id, 'reasoning_effort', v)}- style={{ width: 110 }}- options={[- { label: 'Low', value: 'low' },- { label: 'Medium', value: 'medium' },- { label: 'High', value: 'high' },- ]}- getPopupContainer={(trigger) => trigger.parentElement || document.body}- />- </div>- </>- )}-- {/* Reasoning Format - format type from backend (Groq Qwen3, Cerebras Qwen) */}- {canThink && thinkType === 'format' && defaults?.thinking_enabled && (- <>- <div style={dividerStyle} />- <div style={rowStyle}>- <div>- <div style={labelStyle}>Reasoning Format</div>- <div style={descStyle}>Parsed or hidden</div>- </div>- <Select- size="small"- value={defaults?.reasoning_format ?? 'parsed'}- onChange={(v) => updateProviderDefault(item.id, 'reasoning_format', v)}- style={{ width: 110 }}- options={[- { label: 'Parsed', value: 'parsed' },- { label: 'Hidden', value: 'hidden' },- ]}- getPopupContainer={(trigger) => trigger.parentElement || document.body}- />- </div>- </>- )}-- {/* Save Button */}- <div style={{ marginTop: theme.spacing.md }}>- <Button- size="small"- onClick={() => handleSaveProviderDefaults(item.id)}- loading={defaultsLoading[item.id]}- disabled={!defaultsDirty[item.id]}- block- style={{- backgroundColor: defaultsDirty[item.id] ? `${theme.dracula.green}25` : undefined,- borderColor: defaultsDirty[item.id] ? `${theme.dracula.green}60` : undefined,- color: defaultsDirty[item.id] ? theme.dracula.green : undefined,- }}- >- Save Defaults- </Button>- </div>- </div>- );- })(),- }]}- />- </div>- )}-- {/* Usage & Costs Section - Only for AI providers */}- {CATEGORIES.find(c => c.key === 'ai')?.items.some(i => i.id === item.id) && (- <div style={{ marginBottom: theme.spacing.xl }}>- <Collapse- ghost- defaultActiveKey={['usage']}- onChange={(keys) => setUsageExpanded(keys.includes('usage'))}- items={[{- key: 'usage',- label: (- <span style={{ fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, color: theme.colors.text }}>- <DollarOutlined style={{ marginRight: theme.spacing.sm }} />- Usage & Costs- </span>- ),- children: usageLoading ? (- <div style={{ textAlign: 'center', padding: theme.spacing.lg }}>- <Spin size="small" />- </div>- ) : (() => {- const providerData = usageSummary.find(p => p.provider === item.id);- if (!providerData || providerData.execution_count === 0) {- return (- <Alert- message={`No usage data yet for ${item.name}`}- type="info"- showIcon- style={{ marginBottom: theme.spacing.md }}- />- );- }- return (- <Space direction="vertical" size="middle" style={{ width: '100%' }}>- {/* Summary Stats */}- <div style={{ display: 'flex', gap: theme.spacing.lg, flexWrap: 'wrap' }}>- <Statistic- title="Total Tokens"- value={providerData.total_tokens}- valueStyle={{ color: theme.dracula.cyan, fontSize: theme.fontSize.lg }}- />- <Statistic- title="Total Cost"- value={providerData.total_cost}- precision={4}- prefix="$"- valueStyle={{ color: theme.dracula.green, fontSize: theme.fontSize.lg }}- />- <Statistic- title="Executions"- value={providerData.execution_count}- valueStyle={{ color: theme.dracula.purple, fontSize: theme.fontSize.lg }}- />- </div>-- {/* Token Breakdown */}- <Descriptions size="small" column={2} bordered>- <Descriptions.Item label="Input Tokens">- {providerData.total_input_tokens.toLocaleString()}- <span style={{ color: theme.dracula.green, marginLeft: 8 }}>- (${providerData.total_input_cost.toFixed(4)})- </span>- </Descriptions.Item>- <Descriptions.Item label="Output Tokens">- {providerData.total_output_tokens.toLocaleString()}- <span style={{ color: theme.dracula.green, marginLeft: 8 }}>- (${providerData.total_output_cost.toFixed(4)})- </span>- </Descriptions.Item>- {providerData.total_cache_cost > 0 && (- <Descriptions.Item label="Cache Cost" span={2}>- <span style={{ color: theme.dracula.green }}>- ${providerData.total_cache_cost.toFixed(4)}- </span>- </Descriptions.Item>- )}- </Descriptions>-- {/* Model Breakdown */}- {providerData.models.length > 1 && (- <div>- <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textMuted, marginBottom: theme.spacing.sm }}>- By Model- </div>- <div style={{- maxHeight: 120,- overflow: 'auto',- backgroundColor: theme.colors.backgroundAlt,- borderRadius: theme.borderRadius.sm,- padding: theme.spacing.sm,- }}>- {providerData.models.map((model, idx) => (- <div key={idx} style={{- display: 'flex',- justifyContent: 'space-between',- padding: `${theme.spacing.xs} 0`,- fontSize: theme.fontSize.sm,- borderBottom: idx < providerData.models.length - 1 ? `1px solid ${theme.colors.border}` : 'none',- }}>- <span style={{ fontFamily: 'monospace', fontSize: theme.fontSize.xs, color: theme.colors.text }}>- {model.model}- </span>- <span style={{ color: theme.dracula.green }}>- ${model.total_cost.toFixed(4)}- </span>- </div>- ))}- </div>- </div>- )}-- <Button- size="small"- icon={<ReloadOutlined />}- onClick={loadUsageSummary}- loading={usageLoading}- >- Refresh- </Button>- </Space>- );- })()- }]}- />- </div>- )}-- {/* Usage & Costs Section - For Google Maps */}- {item.id === 'google_maps' && renderApiUsagePanel('google_maps', 'Google Maps')}-- {/* Info box */}- <div style={{- marginTop: theme.spacing.lg,- padding: `${theme.spacing.sm} ${theme.spacing.md}`,- borderRadius: theme.borderRadius.sm,- backgroundColor: `${theme.colors.backgroundAlt}`,- borderLeft: `3px solid ${theme.dracula.cyan}60`,- }}>- <div style={{- fontSize: theme.fontSize.xs,- color: theme.colors.textMuted,- lineHeight: 1.5,- }}>- API key stored securely. Auto-injected when using {item.name} nodes.- </div>- </div>- </div>- );- };-- return (- <Modal isOpen={visible} onClose={onClose} maxWidth="95vw" maxHeight="95vh" headerActions={headerActions}>- <div style={{- display: 'flex',- height: '100%',- overflow: 'hidden',- }}>- {/* Left sidebar */}- <div style={{- width: 280,- borderRight: `1px solid ${theme.colors.border}`,- overflow: 'auto',- flexShrink: 0,- }}>- {CATEGORIES.map(category => (- <div key={category.key}>- {/* Category header */}- <div style={{- padding: `${theme.spacing.md} ${theme.spacing.lg}`,- fontSize: theme.fontSize.xs,- fontWeight: theme.fontWeight.semibold,- color: theme.colors.textMuted,- textTransform: 'uppercase',- letterSpacing: '0.05em',- backgroundColor: theme.colors.backgroundPanel,- borderBottom: `1px solid ${theme.colors.border}`,- position: 'sticky',- top: 0,- zIndex: 1,- }}>- {category.label}- </div>- {/* Category items */}- {category.items.map(renderSidebarItem)}- </div>- ))}- </div>-- {/* Right detail panel */}- <div style={{- flex: 1,- overflow: 'auto',- backgroundColor: theme.colors.background,- display: 'flex',- flexDirection: 'column',- }}>- {renderDetailPanel()}- </div>- </div>- </Modal>- );-};--export default CredentialsModal;+export { default } from './credentials';diff --git a/client/src/components/credentials/CredentialsModal.tsx b/client/src/components/credentials/CredentialsModal.tsxnew file mode 100644index 00000000..5a264817--- /dev/null+++ b/client/src/components/credentials/CredentialsModal.tsx@@ -0,0 +1,82 @@+/**+ * CredentialsModal — thin shell.+ * antd Menu sidebar (grouped by category) + PanelRenderer on the right.+ * All rendering logic lives in panels/ and primitives/.+ */++import React, { useMemo, useState } from 'react';+import { Menu, Tag, Flex, type MenuProps } from 'antd';+import { SafetyOutlined } from '@ant-design/icons';+import Modal from '../ui/Modal';+import { useAppTheme } from '../../hooks/useAppTheme';+import { CATEGORIES, PROVIDERS } from './providers';+import PanelRenderer from './PanelRenderer';++interface Props {+ visible: boolean;+ onClose: () => void;+}++const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {+ const theme = useAppTheme();+ const [selectedId, setSelectedId] = useState<string>(PROVIDERS[0]?.id ?? '');+ const selected = PROVIDERS.find(p => p.id === selectedId) ?? null;++ // Build antd Menu items from CATEGORIES — each category becomes an itemGroup+ const menuItems: MenuProps['items'] = useMemo(() =>+ CATEGORIES.map(cat => ({+ type: 'group' as const,+ key: cat.key,+ label: cat.label,+ children: cat.items.map(p => ({+ key: p.id,+ icon: <p.icon size={parseInt(theme.iconSize.sm)} />,+ label: p.name,+ })),+ })),+ [theme.iconSize.sm]);++ const headerActions = (+ <Flex align="center" gap={theme.spacing.md}>+ <Flex align="center" gap={theme.spacing.sm}+ style={{ fontSize: theme.fontSize.base, fontWeight: theme.fontWeight.semibold, color: theme.colors.text }}>+ <SafetyOutlined style={{ color: theme.dracula.yellow }} />+ <span>API Credentials</span>+ </Flex>+ <Tag style={{+ margin: 0, fontSize: theme.fontSize.xs,+ backgroundColor: `${theme.dracula.green}25`,+ borderColor: `${theme.dracula.green}60`,+ color: theme.dracula.green,+ }}>+ {PROVIDERS.length} providers+ </Tag>+ </Flex>+ );++ return (+ <Modal isOpen={visible} onClose={onClose} maxWidth="95vw" maxHeight="95vh" headerActions={headerActions}>+ <Flex style={{ height: '100%', overflow: 'hidden' }}>+ <div style={{+ width: parseInt(theme.layout?.parameterPanelWidth ?? '280px'),+ borderRight: `1px solid ${theme.colors.border}`,+ overflow: 'auto',+ flexShrink: 0,+ }}>+ <Menu+ mode="inline"+ selectedKeys={[selectedId]}+ onClick={({ key }) => setSelectedId(key as string)}+ items={menuItems}+ style={{ border: 'none', background: 'transparent' }}+ />+ </div>+ <div style={{ flex: 1, overflow: 'auto', backgroundColor: theme.colors.background, display: 'flex', flexDirection: 'column' }}>+ <PanelRenderer config={selected} visible={visible} />+ </div>+ </Flex>+ </Modal>+ );+};++export default CredentialsModal;diff --git a/client/src/components/credentials/PanelRenderer.tsx b/client/src/components/credentials/PanelRenderer.tsxnew file mode 100644index 00000000..2639e0c9--- /dev/null+++ b/client/src/components/credentials/PanelRenderer.tsx@@ -0,0 +1,29 @@+/**+ * PanelRenderer — dispatches to the right panel by config.kind.+ * 10 lines of logic. All panel implementations in panels/ directory.+ */++import React from 'react';+import { Result } from 'antd';+import ApiKeyPanel from './panels/ApiKeyPanel';+import OAuthPanel from './panels/OAuthPanel';+import QrPairingPanel from './panels/QrPairingPanel';+import EmailPanel from './panels/EmailPanel';+import type { ProviderConfig } from './types';++const PANEL_MAP: Record<string, React.FC<any>> = {+ apiKey: ApiKeyPanel,+ oauth: OAuthPanel,+ qrPairing: QrPairingPanel,+ email: EmailPanel,+};++interface Props { config: ProviderConfig | null; visible: boolean }++const PanelRenderer: React.FC<Props> = ({ config, visible }) => {+ if (!config) return <Result status="info" subTitle="Select a credential to configure" />;+ const Panel = PANEL_MAP[config.kind];+ return Panel ? <Panel config={config} visible={visible} /> : null;+};++export default PanelRenderer;diff --git a/client/src/components/credentials/hooks.ts b/client/src/components/credentials/hooks.tsnew file mode 100644index 00000000..e485dcd0--- /dev/null+++ b/client/src/components/credentials/hooks.ts@@ -0,0 +1,15 @@+/**+ * Shared hooks for credential panels.+ */++import {+ useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useGoogleStatus, useTelegramStatus,+} from '../../contexts/WebSocketContext';++/** Resolves config.statusHook string to the actual hook value. */+export function useProviderStatus(hook?: string) {+ const w = useWhatsAppStatus(), a = useAndroidStatus(), t = useTwitterStatus(),+ g = useGoogleStatus(), tg = useTelegramStatus();+ if (!hook) return null;+ return ({ whatsapp: w, android: a, twitter: t, google: g, telegram: tg } as Record<string, any>)[hook] ?? null;+}diff --git a/client/src/components/credentials/index.ts b/client/src/components/credentials/index.tsnew file mode 100644index 00000000..0a7b6470--- /dev/null+++ b/client/src/components/credentials/index.ts@@ -0,0 +1,3 @@+export { default } from './CredentialsModal';+export { default as CredentialsModal } from './CredentialsModal';+export type { ProviderConfig, FieldDef, StatusRowDef, ActionDef, QrPairingDef, PanelKind, CategoryGroup } from './types';diff --git a/client/src/components/credentials/panels/ApiKeyPanel.tsx b/client/src/components/credentials/panels/ApiKeyPanel.tsxnew file mode 100644index 00000000..73d3401b--- /dev/null+++ b/client/src/components/credentials/panels/ApiKeyPanel.tsx@@ -0,0 +1,52 @@+/**+ * ApiKeyPanel — generic API key panel for AI providers, search, scrapers, services.+ * Composes: Card header + ApiKeyInput. Config-driven, zero per-provider JSX.+ */++import React from 'react';+import { Alert, Card, Tag, Flex } from 'antd';+import { CheckCircleOutlined } from '@ant-design/icons';+import ApiKeyInput from '../../ui/ApiKeyInput';+import { useAppTheme } from '../../../hooks/useAppTheme';+import { useCredentialPanel } from '../useCredentialPanel';+import { ProviderDefaultsSection, LlmUsageSection, ApiUsageSection } from '../sections';+import type { ProviderConfig } from '../types';++const ApiKeyPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ config, visible }) => {+ const theme = useAppTheme();+ const panel = useCredentialPanel(config, visible);+ const color = (theme.colors as any)[config.color] ?? config.color;+ const field = config.fields?.[0];+ const iconSize = parseInt(theme.iconSize.md);+ const tagOk = { backgroundColor: `${theme.dracula.green}25`, borderColor: `${theme.dracula.green}60`, color: theme.dracula.green };++ return (+ <Flex vertical gap={theme.spacing.xl} style={{ padding: theme.spacing.xl }}>+ <Card size="small" styles={{ body: { padding: theme.spacing.lg } }}+ title={+ <Flex align="center" gap={theme.spacing.md}>+ <Flex align="center" justify="center" style={{ width: 48, height: 48, borderRadius: theme.borderRadius.lg, backgroundColor: `${color}15` }}>+ <config.icon size={iconSize} />+ </Flex>+ <span style={{ fontSize: theme.fontSize.lg, fontWeight: theme.fontWeight.semibold, color: theme.colors.text }}>{config.name}</span>+ </Flex>}+ extra={panel.stored ? <Tag icon={<CheckCircleOutlined />} style={tagOk}>Connected</Tag> : null}>+ {field && <ApiKeyInput+ value={panel.form.getFieldValue(field.key) || ''}+ onChange={v => { panel.form.setFieldValue(field.key, v); panel.setStored(false); }}+ onSave={() => panel.actions.validate(config.id, panel.form.getFieldValue(field.key)?.trim()).then(r => { if (r?.isValid) panel.setStored(true); })}+ onDelete={panel.stored ? () => panel.actions.remove(config.id) : undefined}+ placeholder={field.placeholder}+ loading={panel.loading === 'validate'}+ isStored={panel.stored}+ />}+ </Card>+ {panel.error && <Alert type="error" message={panel.error} showIcon />}+ {config.hasDefaults && <ProviderDefaultsSection providerId={config.id} />}+ {config.hasDefaults && <LlmUsageSection providerId={config.id} providerName={config.name} />}+ {config.usageService && <ApiUsageSection service={config.usageService} serviceName={config.name} />}+ </Flex>+ );+};++export default ApiKeyPanel;diff --git a/client/src/components/credentials/panels/EmailPanel.tsx b/client/src/components/credentials/panels/EmailPanel.tsxnew file mode 100644index 00000000..6a2bae23--- /dev/null+++ b/client/src/components/credentials/panels/EmailPanel.tsx@@ -0,0 +1,234 @@+/**+ * EmailPanel — Himalaya IMAP/SMTP credentials.+ *+ * antd Form with:+ * - Select (provider preset) + per-provider AUTH_NOTES+ * - Email/Password inputs with "leave blank to keep existing" hint+ * - Conditional custom IMAP/SMTP block via Form.useWatch('provider')+ *+ * Credentials stored via saveApiKey/removeApiKey as individual keys.+ */++import React, { useState, useEffect, useCallback } from 'react';+import { Form, Select, Input, InputNumber, Button, Alert, Flex, Space } from 'antd';+import { useAppTheme } from '../../../hooks/useAppTheme';+import { useApiKeys } from '../../../hooks/useApiKeys';+import { StatusCard } from '../primitives';+import type { ProviderConfig } from '../types';++const PROVIDER_OPTIONS = [+ { label: 'Gmail', value: 'gmail' },+ { label: 'Outlook / Office 365', value: 'outlook' },+ { label: 'Yahoo Mail', value: 'yahoo' },+ { label: 'iCloud Mail', value: 'icloud' },+ { label: 'ProtonMail (Bridge)', value: 'protonmail' },+ { label: 'Fastmail', value: 'fastmail' },+ { label: 'Custom / Self-hosted', value: 'custom' },+];++const AUTH_NOTES: Record<string, string> = {+ gmail: 'Use an App Password from Google Account > Security > 2-Step Verification.',+ outlook: 'Use your account password or an App Password.',+ yahoo: 'Use an App Password from Yahoo Account Security.',+ icloud: 'Use an App-Specific Password from your Apple ID.',+ protonmail: 'Requires ProtonMail Bridge running locally (127.0.0.1).',+ fastmail: 'Use an App Password from Settings > Privacy & Security.',+ custom: 'Enter credentials for your self-hosted IMAP/SMTP server below.',+};++interface EmailForm {+ provider: string;+ address: string;+ password: string;+ imapHost: string;+ imapPort: number;+ smtpHost: string;+ smtpPort: number;+}++const EmailPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ config, visible }) => {+ const theme = useAppTheme();+ const { saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, isConnected } = useApiKeys();++ const [form] = Form.useForm<EmailForm>();+ const provider = Form.useWatch('provider', form) ?? 'gmail';+ const [stored, setStored] = useState(false);+ const [address, setAddress] = useState('');+ const [loading, setLoading] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ // Load credentials on mount+ useEffect(() => {+ if (!visible || !isConnected) return;+ let cancelled = false;+ (async () => {+ try {+ const [provider, addr, hasPassword, imapHost, imapPort, smtpHost, smtpPort] = await Promise.all([+ getStoredApiKey('email_provider'),+ getStoredApiKey('email_address'),+ hasStoredKey('email_password'),+ getStoredApiKey('email_imap_host'),+ getStoredApiKey('email_imap_port'),+ getStoredApiKey('email_smtp_host'),+ getStoredApiKey('email_smtp_port'),+ ]);+ if (cancelled) return;+ form.setFieldsValue({+ provider: provider || 'gmail',+ address: addr || '',+ password: '',+ imapHost: imapHost || '',+ imapPort: imapPort ? parseInt(imapPort, 10) : 993,+ smtpHost: smtpHost || '',+ smtpPort: smtpPort ? parseInt(smtpPort, 10) : 465,+ });+ setAddress(addr || '');+ setStored(hasPassword);+ } catch {+ if (!cancelled) setStored(false);+ }+ })();+ return () => { cancelled = true; };+ }, [visible, isConnected]);++ const handleSave = useCallback(async () => {+ const values = form.getFieldsValue();+ if (!values.address?.trim()) { setError('Email address is required'); return; }+ if (!values.password?.trim() && !stored) { setError('Password is required'); return; }+ if (values.provider === 'custom') {+ if (!values.imapHost?.trim() || !values.smtpHost?.trim()) {+ setError('IMAP and SMTP host are required for custom provider');+ return;+ }+ }+ setLoading('save');+ setError(null);+ try {+ await saveApiKey('email_provider', values.provider);+ await saveApiKey('email_address', values.address.trim());+ if (values.password?.trim()) await saveApiKey('email_password', values.password.trim());+ if (values.provider === 'custom') {+ await saveApiKey('email_imap_host', values.imapHost.trim());+ await saveApiKey('email_imap_port', String(values.imapPort));+ await saveApiKey('email_smtp_host', values.smtpHost.trim());+ await saveApiKey('email_smtp_port', String(values.smtpPort));+ }+ setStored(true);+ setAddress(values.address.trim());+ form.setFieldValue('password', '');+ } catch (err: any) {+ setError(err.message || 'Failed to save email credentials');+ } finally {+ setLoading(null);+ }+ }, [form, stored, saveApiKey]);++ const handleRemove = useCallback(async () => {+ setLoading('remove');+ setError(null);+ try {+ await Promise.all([+ removeApiKey('email_password'),+ removeApiKey('email_address'),+ removeApiKey('email_provider'),+ removeApiKey('email_imap_host'),+ removeApiKey('email_imap_port'),+ removeApiKey('email_smtp_host'),+ removeApiKey('email_smtp_port'),+ ]);+ setStored(false);+ setAddress('');+ form.resetFields();+ } catch (err: any) {+ setError(err.message || 'Failed to remove credentials');+ } finally {+ setLoading(null);+ }+ }, [form, removeApiKey]);++ const iconSize = parseInt(theme.iconSize.md);++ return (+ <Flex vertical gap={theme.spacing.lg} style={{ padding: theme.spacing.xl, flex: 1, minHeight: 0 }}>+ <StatusCard icon={<config.icon size={iconSize} />} title={config.name} status={{ stored, address }}+ rows={[+ { label: 'Status', ok: s => s.stored, trueText: 'Configured', falseText: 'Not configured' },+ ...(stored && address ? [{+ label: 'Account',+ ok: () => true,+ trueText: address,+ falseText: '',+ }] : []),+ ]} />++ <Form form={form} layout="vertical" size="middle" initialValues={{ provider: 'gmail', imapPort: 993, smtpPort: 465 }}>+ <Form.Item label="Provider" name="provider">+ <Select options={PROVIDER_OPTIONS} />+ </Form.Item>++ <Form.Item label="Email Address" name="address" rules={[{ required: true, message: 'Email address is required' }]}>+ <Input placeholder="[email protected]" />+ </Form.Item>++ <Form.Item+ label={<Space>Password {stored && <span style={{ color: theme.colors.textMuted, fontWeight: theme.fontWeight.normal, fontSize: theme.fontSize.xs }}>(leave blank to keep existing)</span>}</Space>}+ name="password"+ extra={AUTH_NOTES[provider]}+ >+ <Input.Password placeholder={stored ? '••••••••' : 'App password or account password'} style={{ fontFamily: 'monospace' }} />+ </Form.Item>++ <Form.Item shouldUpdate={(p, c) => p.provider !== c.provider} noStyle>+ {({ getFieldValue }) => getFieldValue('provider') === 'custom' && (+ <div style={{+ padding: theme.spacing.md,+ marginBottom: theme.spacing.lg,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ backgroundColor: theme.colors.backgroundAlt,+ }}>+ <div style={{ fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, color: theme.colors.text, marginBottom: theme.spacing.md }}>+ Custom IMAP / SMTP+ </div>+ <Flex gap={theme.spacing.md}>+ <Form.Item label="IMAP Host" name="imapHost" style={{ flex: 2 }}>+ <Input placeholder="imap.example.com" />+ </Form.Item>+ <Form.Item label="IMAP Port" name="imapPort" style={{ flex: 1 }}>+ <InputNumber min={1} max={65535} style={{ width: '100%' }} />+ </Form.Item>+ </Flex>+ <Flex gap={theme.spacing.md}>+ <Form.Item label="SMTP Host" name="smtpHost" style={{ flex: 2 }}>+ <Input placeholder="smtp.example.com" />+ </Form.Item>+ <Form.Item label="SMTP Port" name="smtpPort" style={{ flex: 1 }}>+ <InputNumber min={1} max={65535} style={{ width: '100%' }} />+ </Form.Item>+ </Flex>+ </div>+ )}+ </Form.Item>+ </Form>++ {error && <Alert type="error" message={error} showIcon />}++ <div style={{ flex: 1 }} />++ <Flex gap={theme.spacing.sm} justify="center" style={{ paddingTop: theme.spacing.md, borderTop: `1px solid ${theme.colors.border}` }}>+ <Button onClick={handleSave} loading={loading === 'save'}+ style={{ backgroundColor: `${theme.dracula.green}25`, borderColor: `${theme.dracula.green}60`, color: theme.dracula.green }}>+ Save+ </Button>+ {stored && (+ <Button onClick={handleRemove} loading={loading === 'remove'}+ style={{ backgroundColor: `${theme.dracula.pink}25`, borderColor: `${theme.dracula.pink}60`, color: theme.dracula.pink }}>+ Remove+ </Button>+ )}+ </Flex>+ </Flex>+ );+};++export default EmailPanel;diff --git a/client/src/components/credentials/panels/OAuthPanel.tsx b/client/src/components/credentials/panels/OAuthPanel.tsxnew file mode 100644index 00000000..cddb2674--- /dev/null+++ b/client/src/components/credentials/panels/OAuthPanel.tsx@@ -0,0 +1,45 @@+/**+ * OAuthPanel — generic OAuth panel for Twitter, Google Workspace, Telegram.+ * Delegates entirely to the OAuthConnect primitive.+ */++import React from 'react';+import { Flex } from 'antd';+import { useAppTheme } from '../../../hooks/useAppTheme';+import { useCredentialPanel } from '../useCredentialPanel';+import { useProviderStatus } from '../hooks';+import { OAuthConnect } from '../primitives';+import { ApiUsageSection } from '../sections';+import type { ProviderConfig } from '../types';++const OAuthPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ config, visible }) => {+ const theme = useAppTheme();+ const panel = useCredentialPanel(config, visible);+ const status = useProviderStatus(config.statusHook);+ const connected = !!status?.connected;++ return (+ <Flex vertical style={{ padding: theme.spacing.xl, flex: 1, minHeight: 0 }}>+ <OAuthConnect+ config={config} form={panel.form} connected={connected}+ stored={panel.stored} loading={panel.loading} error={panel.error}+ icon={<config.icon size={parseInt(theme.iconSize.md)} />}+ onSaveCredentials={() => {+ const missing = config.fields?.find(f => f.required && !panel.form.getFieldValue(f.key)?.trim());+ if (missing) { panel.setError(`${missing.label} is required`); return; }+ panel.execute('save', async () => {+ for (const f of config.fields!) { const v = panel.form.getFieldValue(f.key)?.trim(); if (v) await panel.actions.save(f.key, v); }+ panel.setStored(true);+ return { success: true };+ });+ }}+ onLogin={() => panel.actions.oauthLogin()}+ onLogout={() => panel.actions.oauthLogout()}+ onRefresh={() => panel.actions.oauthRefresh()}+ extraSection={config.usageService && <ApiUsageSection service={config.usageService} serviceName={config.name} />}+ />+ </Flex>+ );+};++export default OAuthPanel;diff --git a/client/src/components/credentials/panels/QrPairingPanel.tsx b/client/src/components/credentials/panels/QrPairingPanel.tsxnew file mode 100644index 00000000..37f2a8b4--- /dev/null+++ b/client/src/components/credentials/panels/QrPairingPanel.tsx@@ -0,0 +1,80 @@+/**+ * QrPairingPanel — config-driven QR pairing for WhatsApp and Android.+ * Status rows + QR config come from ProviderConfig — zero isWhatsApp conditionals.+ * Only action handlers need hook access (WhatsApp start vs Android relay connect).+ */++import React, { useMemo } from 'react';+import { Alert, Flex } from 'antd';+import ApiKeyInput from '../../ui/ApiKeyInput';+import QRCodeDisplay from '../../ui/QRCodeDisplay';+import { useAppTheme } from '../../../hooks/useAppTheme';+import { useWebSocket } from '../../../contexts/WebSocketContext';+import { useWhatsApp } from '../../../hooks/useWhatsApp';+import { useCredentialPanel } from '../useCredentialPanel';+import { useProviderStatus } from '../hooks';+import { StatusCard, ActionBar } from '../primitives';+import { RateLimitSection } from '../sections';+import type { ActionDef } from '../primitives/ActionBar';+import type { ProviderConfig } from '../types';++const QrPairingPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ config, visible }) => {+ const theme = useAppTheme();+ const panel = useCredentialPanel(config, visible);+ const status = useProviderStatus(config.statusHook);+ const { startConnection, restartConnection, getStatus: refreshWa } = useWhatsApp();+ const { sendRequest, setAndroidStatus } = useWebSocket();+ const qr = config.qr!;+ const connected = qr.isConnected(status);+ const qrData = status?.[qr.qrField];+ const field = config.fields?.[0];++ // Build actions from config.actions descriptors + hook methods+ const actionHandlers: Record<string, () => void> = useMemo(() => ({+ start: () => panel.execute('start', startConnection),+ restart: () => panel.execute('restart', restartConnection),+ refresh: () => panel.execute('refresh', refreshWa),+ connect: () => panel.execute('connect', async () => {+ const key = panel.form.getFieldValue('android_remote')?.trim();+ if (!key) { panel.setError('No API key configured'); return; }+ const res = await sendRequest('android_relay_connect', { url: (import.meta as any).env?.VITE_ANDROID_RELAY_URL || '', api_key: key });+ if (res.qr_data) setAndroidStatus((prev: any) => ({ ...prev, connected: true, paired: false, qr_data: res.qr_data, session_token: res.session_token || prev.session_token }));+ return res;+ }),+ disconnect: () => panel.execute('disconnect', () => sendRequest('android_relay_disconnect', {})),+ }), [panel, startConnection, restartConnection, refreshWa, sendRequest, setAndroidStatus]);++ const actions: ActionDef[] = (config.actions ?? []).map(a => ({+ key: a.key,+ label: a.label,+ color: (theme.dracula as any)[a.themeColor] ?? a.themeColor,+ onClick: actionHandlers[a.key] ?? (() => {}),+ hidden: a.hidden?.(status, panel.stored),+ disabled: a.disabled?.(status, panel.stored),+ }));++ return (+ <Flex vertical gap={theme.spacing.lg} style={{ padding: theme.spacing.xl, flex: 1, minHeight: 0 }}>+ {field && <ApiKeyInput+ value={panel.form.getFieldValue(field.key) || ''}+ onChange={(v: string) => panel.form.setFieldValue(field.key, v)}+ onSave={() => panel.actions.save(field.key, panel.form.getFieldValue(field.key)?.trim()).then(() => panel.setStored(true))}+ onDelete={() => panel.actions.remove(field.key)}+ placeholder={field.placeholder} loading={panel.loading === 'save'} isStored={panel.stored}+ />}+ {config.statusRows && <StatusCard icon={<config.icon size={parseInt(theme.iconSize.md)} />} title={config.name} rows={config.statusRows} status={status} />}+ <Flex vertical align="center" justify="center"+ style={{ backgroundColor: theme.colors.backgroundAlt, borderRadius: theme.borderRadius.lg, padding: theme.spacing.xl, flex: 1, minHeight: 300 }}>+ <QRCodeDisplay value={qrData} isConnected={connected} size={280}+ connectedTitle={qr.connectedTitle} connectedSubtitle={qr.connectedSubtitle(status)}+ loading={qr.isLoading(status)} emptyText={qr.emptyText(status, panel.stored)} />+ {!connected && qrData && <div style={{ marginTop: theme.spacing.md, color: theme.colors.textSecondary, fontSize: theme.fontSize.sm }}>{qr.scanText}</div>}+ </Flex>+ {config.hasRateLimits && connected && <RateLimitSection />}+ {panel.error && <Alert type="error" message={panel.error} showIcon />}+ <ActionBar actions={actions} loading={panel.loading} />+ </Flex>+ );+};++export default QrPairingPanel;diff --git a/client/src/components/credentials/primitives/ActionBar.tsx b/client/src/components/credentials/primitives/ActionBar.tsxnew file mode 100644index 00000000..e2e605d1--- /dev/null+++ b/client/src/components/credentials/primitives/ActionBar.tsx@@ -0,0 +1,45 @@+/**+ * ActionBar — bottom themed action buttons driven by a config array.+ * Replaces the 5 identical action button sections across panels.+ */++import React from 'react';+import { Button, Flex } from 'antd';+import { useAppTheme } from '../../../hooks/useAppTheme';++export interface ActionDef {+ key: string;+ label: string;+ /** Dracula color string from theme (e.g., theme.dracula.green). */+ color: string;+ onClick: () => void;+ disabled?: boolean;+ icon?: React.ReactNode;+ hidden?: boolean;+}++interface Props {+ actions: ActionDef[];+ loading: string | null;+}++const ActionBar: React.FC<Props> = ({ actions, loading }) => {+ const theme = useAppTheme();+ return (+ <Flex gap={theme.spacing.sm} justify="center"+ style={{ paddingTop: theme.spacing.md, borderTop: `1px solid ${theme.colors.border}` }}>+ {actions.filter(a => !a.hidden).map(a => (+ <Button key={a.key}+ onClick={a.onClick}+ loading={loading === a.key}+ disabled={a.disabled}+ icon={a.icon}+ style={{ backgroundColor: `${a.color}25`, borderColor: `${a.color}60`, color: a.color }}>+ {a.label}+ </Button>+ ))}+ </Flex>+ );+};++export default ActionBar;diff --git a/client/src/components/credentials/primitives/FieldRenderer.tsx b/client/src/components/credentials/primitives/FieldRenderer.tsxnew file mode 100644index 00000000..f2ab72d5--- /dev/null+++ b/client/src/components/credentials/primitives/FieldRenderer.tsx@@ -0,0 +1,51 @@+/**+ * FieldRenderer — generic schema-driven field renderer (n8n CredentialInputs pattern).+ * Takes a FieldDef[] array + antd Form instance, renders the right control per field.+ * Replaces all manual Input/Input.Password/label blocks across panels.+ */++import React from 'react';+import { Form, Input, Space } from 'antd';+import { useAppTheme } from '../../../hooks/useAppTheme';+import type { FieldDef } from '../types';+import type { FormInstance } from 'antd';++interface Props {+ fields: FieldDef[];+ form: FormInstance;+}++const FieldRenderer: React.FC<Props> = ({ fields, form }) => {+ const theme = useAppTheme();+ const inputStyle: React.CSSProperties = {+ fontFamily: theme.fontFamily?.mono || 'monospace',+ fontSize: theme.fontSize.sm,+ };++ return (+ <Space direction="vertical" size="small" style={{ width: '100%' }}>+ {fields.map(f => (+ <Form.Item key={f.key} label={f.label} required={f.required}+ style={{ marginBottom: theme.spacing.xs }}>+ {f.secret ? (+ <Input.Password+ value={form.getFieldValue(f.key) || ''}+ onChange={e => form.setFieldValue(f.key, e.target.value)}+ placeholder={f.placeholder}+ style={inputStyle}+ />+ ) : (+ <Input+ value={form.getFieldValue(f.key) || ''}+ onChange={e => form.setFieldValue(f.key, e.target.value)}+ placeholder={f.placeholder}+ style={inputStyle}+ />+ )}+ </Form.Item>+ ))}+ </Space>+ );+};++export default FieldRenderer;diff --git a/client/src/components/credentials/primitives/OAuthConnect.tsx b/client/src/components/credentials/primitives/OAuthConnect.tsxnew file mode 100644index 00000000..31bcc4e5--- /dev/null+++ b/client/src/components/credentials/primitives/OAuthConnect.tsx@@ -0,0 +1,90 @@+/**+ * OAuthConnect — reusable OAuth connect/disconnect flow.+ * Composes StatusCard (data-driven) + FieldRenderer + ActionBar.+ * Accepts optional `extraSection` slot for panel-specific content (e.g., API usage).+ */++import React from 'react';+import { Button, Alert, Flex, Space } from 'antd';+import { ReloadOutlined } from '@ant-design/icons';+import { useAppTheme } from '../../../hooks/useAppTheme';+import FieldRenderer from './FieldRenderer';+import ActionBar, { type ActionDef } from './ActionBar';+import StatusCard from './StatusCard';+import type { ProviderConfig, StatusRowDef } from '../types';+import type { FormInstance } from 'antd';++interface Props {+ config: ProviderConfig;+ form: FormInstance;+ connected: boolean;+ stored: boolean;+ loading: string | null;+ error: string | null;+ icon: React.ReactNode;+ onSaveCredentials: () => void;+ onLogin: () => void;+ onLogout: () => void;+ onRefresh: () => void;+ /** Optional slot rendered below the info box, above the ActionBar. */+ extraSection?: React.ReactNode;+}++const OAuthConnect: React.FC<Props> = ({+ config, form, connected, stored, loading, error, icon,+ onSaveCredentials, onLogin, onLogout, onRefresh, extraSection,+}) => {+ const theme = useAppTheme();++ const statusRows: StatusRowDef[] = [+ { label: 'Status', ok: () => connected, trueText: 'Connected', falseText: 'Not Connected' },+ { label: 'Credentials', ok: () => stored, trueText: 'Configured', falseText: 'Not configured' },+ ];++ const actions: ActionDef[] = [+ { key: 'login', label: `Login with ${config.name}`, color: theme.dracula.green, onClick: onLogin, disabled: !stored, hidden: connected },+ { key: 'logout', label: 'Disconnect', color: theme.dracula.pink, onClick: onLogout, hidden: !connected },+ { key: 'refresh', label: 'Refresh', color: theme.dracula.cyan, onClick: onRefresh, icon: <ReloadOutlined /> },+ ];++ return (+ <Flex vertical gap={theme.spacing.lg} style={{ flex: 1, minHeight: 0 }}>+ <StatusCard icon={icon} title={config.name} rows={statusRows} status={null} />++ {!connected && config.fields && (+ <Space direction="vertical" size="middle" style={{ width: '100%' }}>+ <FieldRenderer fields={config.fields} form={form} />+ <Button onClick={onSaveCredentials} loading={loading === 'save'}+ style={{ backgroundColor: `${theme.dracula.purple}25`, borderColor: `${theme.dracula.purple}60`, color: theme.dracula.purple }}>+ Save Credentials+ </Button>+ {config.instructions && (+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textMuted, lineHeight: 1.5 }}>+ {config.instructions}+ {config.callbackUrl && <><br/>Callback URL: <code style={{ color: theme.dracula.cyan }}>{config.callbackUrl}</code></>}+ </div>+ )}+ </Space>+ )}++ {error && <Alert type="error" message={error} showIcon />}++ <div style={{ padding: theme.spacing.md, borderRadius: theme.borderRadius.md,+ backgroundColor: `${theme.dracula.cyan}10`, border: `1px solid ${theme.dracula.cyan}30` }}>+ <div style={{ fontSize: theme.fontSize.sm, color: theme.colors.textSecondary, lineHeight: 1.5 }}>+ {connected ? `Your ${config.name} account is connected.`+ : stored ? 'Click Login to authorize.'+ : 'Enter your credentials above to get started.'}+ </div>+ </div>++ {extraSection}++ <div style={{ flex: 1 }} />++ <ActionBar actions={actions} loading={loading} />+ </Flex>+ );+};++export default OAuthConnect;diff --git a/client/src/components/credentials/primitives/StatusCard.tsx b/client/src/components/credentials/primitives/StatusCard.tsxnew file mode 100644index 00000000..b73f9123--- /dev/null+++ b/client/src/components/credentials/primitives/StatusCard.tsx@@ -0,0 +1,46 @@+/**+ * StatusCard — config-driven status Descriptions.+ * Config provides data (ok/trueText/falseText); component resolves theme colors.+ * Matches original CredentialsModal's Descriptions density (bordered, column=1, small).+ */++import React from 'react';+import { Descriptions, Tag, Space } from 'antd';+import { useAppTheme } from '../../../hooks/useAppTheme';+import type { StatusRowDef } from '../types';++interface Props {+ icon: React.ReactNode;+ title: string;+ rows: StatusRowDef[];+ status: any;+}++const StatusCard: React.FC<Props> = ({ icon, title, rows, status }) => {+ const theme = useAppTheme();+ const tagStyle = (ok: boolean, warn?: boolean): React.CSSProperties => {+ const c = ok ? theme.dracula.green : warn ? theme.dracula.orange : theme.dracula.pink;+ return { backgroundColor: `${c}25`, borderColor: `${c}60`, color: c };+ };++ return (+ <Descriptions bordered column={1} size="small"+ title={<Space>{icon} {title}</Space>}+ style={{ borderRadius: theme.borderRadius.md }}+ styles={{+ label: { backgroundColor: theme.colors.backgroundPanel, color: theme.colors.textSecondary, fontWeight: theme.fontWeight.medium },+ content: { backgroundColor: theme.colors.background, color: theme.colors.text },+ }}>+ {rows.map(r => {+ const ok = r.ok(status);+ return (+ <Descriptions.Item key={r.label} label={r.label}>+ <Tag style={tagStyle(ok, r.warn)}>{ok ? r.trueText : r.falseText}</Tag>+ </Descriptions.Item>+ );+ })}+ </Descriptions>+ );+};++export default StatusCard;diff --git a/client/src/components/credentials/primitives/index.ts b/client/src/components/credentials/primitives/index.tsnew file mode 100644index 00000000..141e2ba4--- /dev/null+++ b/client/src/components/credentials/primitives/index.ts@@ -0,0 +1,5 @@+export { default as StatusCard } from './StatusCard';+export { default as ActionBar } from './ActionBar';+export type { ActionDef as ActionBarAction } from './ActionBar';+export { default as FieldRenderer } from './FieldRenderer';+export { default as OAuthConnect } from './OAuthConnect';diff --git a/client/src/components/credentials/providers.tsx b/client/src/components/credentials/providers.tsxnew file mode 100644index 00000000..f14e0010--- /dev/null+++ b/client/src/components/credentials/providers.tsx@@ -0,0 +1,238 @@+/**+ * Provider configs — every credential provider as a plain config object.+ *+ * Icons: reuse existing asset modules and node-definition exports.+ * Google Maps + Android use emoji (matching the convention of locationNodes+ * and androidServiceNodes, which already use '🗺️' and '🔋' etc.).+ * Colors: theme token keys (resolved at render by the consumer).+ * Status rows: pure data (ok/trueText/falseText), theme colors resolved in StatusCard.+ */++import React from 'react';+import { AI_PROVIDER_META } from '../icons/AIProviderIcons';+import { ApifyIcons } from '../../assets/icons/apify';+import { SearchIcons } from '../../assets/icons/search';+import { TelegramIcons } from '../../assets/icons/telegram';+import { GoogleIcons } from '../../assets/icons/google';+import { EmailIcons } from '../../assets/icons/email';+import { WHATSAPP_CONNECT_ICON } from '../../nodeDefinitions/whatsappNodes';+import { TWITTER_ICON } from '../../nodeDefinitions/twitterNodes';+import type { ProviderConfig, CategoryGroup } from './types';++// ============================================================================+// ICON FACTORIES — thin wrappers around existing asset strings.+// All icons accept a `size` prop from the caller (no hardcoded dimensions).+// ============================================================================++interface IconProps { size: number }++/** Wraps a raw SVG string (from assets/icons/) into a sized component. */+const fromRawSvg = (rawSvg: string): React.FC<IconProps> => {+ const Comp: React.FC<IconProps> = ({ size }) => {+ const ref = React.useRef<HTMLDivElement>(null);+ React.useEffect(() => { if (ref.current) ref.current.innerHTML = rawSvg; }, []);+ return <div ref={ref} style={{ width: size, height: size }} />;+ };+ return Comp;+};++/** Wraps a data:image/svg+xml URI (from node definitions) into a sized component. */+const fromDataUri = (dataUri: string): React.FC<IconProps> => {+ const Comp: React.FC<IconProps> = ({ size }) => (+ <img src={dataUri} width={size} height={size} alt="" style={{ display: 'block' }} />+ );+ return Comp;+};++/** Wraps an emoji string into a sized inline element — matches node-definition convention. */+const fromEmoji = (emoji: string): React.FC<IconProps> => {+ const Comp: React.FC<IconProps> = ({ size }) => (+ <span style={{ fontSize: size, lineHeight: 1, display: 'inline-block' }}>{emoji}</span>+ );+ return Comp;+};++// Reuse raw SVG strings from assets/icons/+const BraveIcon = fromRawSvg(SearchIcons.brave);+const SerperIcon = fromRawSvg(SearchIcons.serper);+const PerplexityIcon = fromRawSvg(SearchIcons.perplexity);+const TelegramBotIcon = fromRawSvg(TelegramIcons.telegram);+const GWorkspaceIcon = fromRawSvg(GoogleIcons.gmail);+const EmailCredIcon = fromRawSvg(EmailIcons.read);++// Apify needs explicit scaling attribute on its root <svg>+const ApifyIconC: React.FC<IconProps> = ({ size }) => {+ const scaled = ApifyIcons.apify.replace('<svg', '<svg width="100%" height="100%"');+ return <div dangerouslySetInnerHTML={{ __html: scaled }} style={{ width: size, height: size }} />;+};++// Reuse data URIs exported from node definitions+const WhatsAppIcon = fromDataUri(WHATSAPP_CONNECT_ICON);+const XIcon = fromDataUri(TWITTER_ICON);++// Google Maps + Android: emoji (matches locationNodes '🗺️' and androidServiceNodes '📱')+const GoogleMapsIcon = fromEmoji('🗺️');+const AndroidIcon = fromEmoji('📱');++// ============================================================================+// AI PROVIDERS — derived from centralized AI_PROVIDER_META+// ============================================================================++const AI_PLACEHOLDERS: Record<string, string> = {+ openai: 'sk-...', anthropic: 'sk-ant-...', gemini: 'AIza...',+ groq: 'gsk_...', cerebras: 'csk-...', openrouter: 'sk-or-...',+ deepseek: 'sk-...', kimi: 'sk-...', mistral: 'sk-...',+};++const aiProviders: ProviderConfig[] = Object.entries(AI_PROVIDER_META).map(([id, meta]) => ({+ id, name: meta.label, category: 'ai', categoryLabel: 'AI Providers',+ color: meta.color, kind: 'apiKey' as const, icon: meta.Icon, hasDefaults: true,+ fields: [{ key: 'apiKey', label: 'API Key', secret: true, placeholder: AI_PLACEHOLDERS[id], required: true }],+}));++// ============================================================================+// ALL PROVIDERS — flat array. Categories derived below.+// ============================================================================++export const PROVIDERS: ProviderConfig[] = [+ ...aiProviders,++ // ── Social: WhatsApp (QR pairing) ────────────────────────────────────+ {+ id: 'whatsapp_personal', name: 'WhatsApp Personal',+ category: 'social', categoryLabel: 'Social Media',+ color: 'categoryWhatsapp', kind: 'qrPairing', icon: WhatsAppIcon,+ statusHook: 'whatsapp', hasRateLimits: true,+ statusRows: [+ { label: 'Status', ok: s => !!s?.connected, trueText: 'Connected', falseText: 'Disconnected' },+ { label: 'Session', ok: s => !!s?.has_session, trueText: 'Active', falseText: 'Inactive' },+ { label: 'Service', ok: s => !!s?.running, trueText: 'Running', falseText: 'Stopped' },+ ],+ actions: [+ { key: 'start', label: 'Start', themeColor: 'green' },+ { key: 'restart', label: 'Restart', themeColor: 'orange' },+ { key: 'refresh', label: 'Refresh', themeColor: 'cyan' },+ ],+ qr: {+ qrField: 'qr',+ isConnected: s => !!s?.connected,+ connectedTitle: 'Already Connected!',+ connectedSubtitle: () => 'No QR code needed',+ isLoading: s => !!(s?.running && !s?.qr && !s?.connected),+ emptyText: s => s?.running ? 'Waiting for QR code...' : 'Start service to get QR code',+ scanText: 'Scan with WhatsApp mobile app',+ },+ },++ // ── Social: Twitter/X (OAuth) ────────────────────────────────────────+ {+ id: 'twitter', name: 'Twitter/X',+ category: 'social', categoryLabel: 'Social Media',+ color: 'categoryTrigger', kind: 'oauth', icon: XIcon,+ statusHook: 'twitter', usageService: 'twitter',+ ws: { login: 'twitter_oauth_login', logout: 'twitter_logout', status: 'twitter_oauth_status' },+ fields: [+ { key: 'twitter_client_id', label: 'Client ID', placeholder: 'Client ID (from X Developer Portal)', required: true },+ { key: 'twitter_client_secret', label: 'Client Secret', secret: true, placeholder: 'Client Secret (optional for PKCE)' },+ ],+ callbackUrl: 'http://localhost:3010/api/twitter/callback',+ instructions: 'Get credentials from the X Developer Portal. Create an app with OAuth 2.0 enabled.',+ },++ // ── Social: Telegram Bot (OAuth-like token flow) ─────────────────────+ {+ id: 'telegram', name: 'Telegram Bot',+ category: 'social', categoryLabel: 'Social Media',+ color: 'categoryChat', kind: 'oauth', icon: TelegramBotIcon, statusHook: 'telegram',+ ws: { login: 'telegram_connect', logout: 'telegram_disconnect', status: 'telegram_status' },+ fields: [{ key: 'telegram_bot_token', label: 'Bot Token', secret: true, placeholder: '123456789:ABCdefGHIjklMNOpqrSTUvwxYZ', required: true }],+ instructions: 'Get a bot token from @BotFather on Telegram. After connecting, send any message to your bot to register as the owner.',+ },++ // ── Productivity: Google Workspace (OAuth) ───────────────────────────+ {+ id: 'gmail', name: 'Google Workspace',+ category: 'productivity', categoryLabel: 'Productivity',+ color: 'categoryAI', kind: 'oauth', icon: GWorkspaceIcon,+ statusHook: 'google', usageService: 'google_workspace',+ ws: { login: 'google_oauth_login', logout: 'google_logout', status: 'google_oauth_status' },+ fields: [+ { key: 'google_client_id', label: 'Client ID', placeholder: 'Client ID (from Google Cloud Console)', required: true },+ { key: 'google_client_secret', label: 'Client Secret', secret: true, placeholder: 'Client Secret (required)', required: true },+ ],+ callbackUrl: 'http://localhost:3010/api/google/callback',+ instructions: 'Get credentials from Google Cloud Console. Enable Gmail, Calendar, Drive, Sheets, Tasks, and People APIs.',+ },++ // ── Email (Himalaya IMAP/SMTP) ───────────────────────────────────────+ {+ id: 'email_himalaya', name: 'Email (IMAP/SMTP)',+ category: 'email', categoryLabel: 'Email',+ color: 'categoryChat', kind: 'email', icon: EmailCredIcon,+ },++ // ── Android Device (QR pairing) ──────────────────────────────────────+ {+ id: 'android_remote', name: 'Android Device',+ category: 'android', categoryLabel: 'Android',+ color: 'categoryAndroid', kind: 'qrPairing', icon: AndroidIcon,+ statusHook: 'android',+ fields: [{ key: 'android_remote', label: 'API Key', secret: true, placeholder: 'Enter Android Relay API key...', required: true }],+ statusRows: [+ { label: 'Device', ok: s => !!s?.paired, trueText: 'Paired', falseText: 'Not Paired' },+ { label: 'Relay', ok: s => !!s?.connected, trueText: 'Connected', falseText: 'Disconnected' },+ { label: 'Pairing', ok: s => !!s?.paired, trueText: 'Paired', falseText: 'Waiting', warn: true },+ ],+ actions: [+ { key: 'connect', label: 'Connect', themeColor: 'green',+ disabled: (s, stored) => !!s?.paired || !stored },+ { key: 'disconnect', label: 'Disconnect', themeColor: 'pink',+ disabled: s => !s?.connected },+ ],+ qr: {+ qrField: 'qr_data',+ isConnected: s => !!s?.paired,+ connectedTitle: 'Device Paired!',+ connectedSubtitle: s => s?.device_name || 'Android Device',+ isLoading: s => !!(s?.connected && !s?.qr_data && !s?.paired),+ emptyText: (s, stored) => !stored ? 'Add API key first' : (s?.connected ? 'Waiting for QR code...' : 'Click Connect to start'),+ scanText: 'Scan with Android companion app',+ },+ },++ // ── Search ───────────────────────────────────────────────────────────+ { id: 'brave_search', name: 'Brave Search', category: 'search', categoryLabel: 'Search',+ color: 'categoryLocation', kind: 'apiKey', icon: BraveIcon,+ fields: [{ key: 'apiKey', label: 'API Key', secret: true, placeholder: 'BSA...', required: true }] },+ { id: 'perplexity', name: 'Perplexity', category: 'search', categoryLabel: 'Search',+ color: 'categoryUtil', kind: 'apiKey', icon: PerplexityIcon,+ fields: [{ key: 'apiKey', label: 'API Key', secret: true, placeholder: 'pplx-...', required: true }] },++ // ── Scrapers ─────────────────────────────────────────────────────────+ { id: 'apify', name: 'Apify', category: 'scrapers', categoryLabel: 'Scrapers',+ color: 'categoryAI', kind: 'apiKey', icon: ApifyIconC, validateAs: 'apify',+ fields: [{ key: 'apiKey', label: 'API Key', secret: true, placeholder: 'apify_api_...', required: true }] },+ { id: 'serper', name: 'Serper', category: 'scrapers', categoryLabel: 'Scrapers',+ color: 'categoryAI', kind: 'apiKey', icon: SerperIcon,+ fields: [{ key: 'apiKey', label: 'API Key', secret: true, required: true }] },++ // ── Services ─────────────────────────────────────────────────────────+ { id: 'google_maps', name: 'Google Maps', category: 'services', categoryLabel: 'Services',+ color: 'categoryLocation', kind: 'apiKey', icon: GoogleMapsIcon,+ validateAs: 'google_maps', usageService: 'google_maps',+ fields: [{ key: 'apiKey', label: 'API Key', secret: true, placeholder: 'AIza...', required: true }] },+];++// ============================================================================+// CATEGORIES — derived from PROVIDERS, preserving insertion order+// ============================================================================++export const CATEGORIES: CategoryGroup[] = (() => {+ const map = new Map<string, CategoryGroup>();+ for (const p of PROVIDERS) {+ let cat = map.get(p.category);+ if (!cat) { cat = { key: p.category, label: p.categoryLabel, items: [] }; map.set(p.category, cat); }+ cat.items.push(p);+ }+ return Array.from(map.values());+})();diff --git a/client/src/components/credentials/sections/ApiUsageSection.tsx b/client/src/components/credentials/sections/ApiUsageSection.tsxnew file mode 100644index 00000000..c35d4e0e--- /dev/null+++ b/client/src/components/credentials/sections/ApiUsageSection.tsx@@ -0,0 +1,84 @@+/**+ * ApiUsageSection — generic API call stats for external services.+ * Used by Twitter, Google Workspace, Google Maps panels.+ */++import React, { useState, useEffect, useCallback } from 'react';+import { Collapse, Statistic, Alert, Button, Tag, Space, Spin, Flex, Descriptions } from 'antd';+import { DollarOutlined, ReloadOutlined } from '@ant-design/icons';+import { useAppTheme } from '../../../hooks/useAppTheme';+import { useApiKeys, type APIUsageSummary } from '../../../hooks/useApiKeys';++interface Props {+ service: string;+ serviceName: string;+}++const ApiUsageSection: React.FC<Props> = ({ service, serviceName }) => {+ const theme = useAppTheme();+ const { getAPIUsageSummary, isConnected } = useApiKeys();+ const [data, setData] = useState<APIUsageSummary | null>(null);+ const [loading, setLoading] = useState(false);++ const load = useCallback(async () => {+ if (!isConnected) return;+ setLoading(true);+ try {+ const services = await getAPIUsageSummary(service);+ setData(services.find(s => s.service === service) ?? null);+ } finally {+ setLoading(false);+ }+ }, [isConnected, service, getAPIUsageSummary]);++ useEffect(() => { load(); }, [load]);++ const costTag = data ? (+ <Tag style={{ backgroundColor: `${theme.dracula.green}25`, borderColor: `${theme.dracula.green}60`, color: theme.dracula.green }}>+ ${data.total_cost.toFixed(4)}+ </Tag>+ ) : null;++ return (+ <Collapse items={[{+ key: 'usage',+ label: <Space><DollarOutlined style={{ color: theme.dracula.yellow }} /> API Usage & Costs {costTag}</Space>,+ children: loading ? (+ <Flex justify="center" style={{ padding: theme.spacing.lg }}><Spin size="small" /></Flex>+ ) : !data ? (+ <Alert type="info" showIcon+ message={`No usage data yet. Use ${serviceName} nodes in your workflows to track costs.`} />+ ) : (+ <Space direction="vertical" size="middle" style={{ width: '100%' }}>+ <Flex gap={theme.spacing.md} wrap="wrap">+ <Statistic title="Total Cost" value={data.total_cost} precision={4} prefix="$"+ valueStyle={{ color: theme.dracula.green, fontSize: theme.fontSize.lg }} />+ <Statistic title="API Calls" value={data.execution_count}+ valueStyle={{ color: theme.dracula.cyan, fontSize: theme.fontSize.lg }} />+ <Statistic title="Resources" value={data.total_resources}+ valueStyle={{ color: theme.dracula.purple, fontSize: theme.fontSize.lg }} />+ </Flex>++ {data.operations?.length > 0 && (+ <Descriptions size="small" column={1} bordered title="Operations Breakdown">+ {data.operations.map(op => (+ <Descriptions.Item key={op.operation} label={<code>{op.operation}</code>}>+ <Space>+ <Tag>{op.resource_count} resources</Tag>+ <Tag style={{ backgroundColor: `${theme.dracula.green}15`, color: theme.dracula.green, border: 'none' }}>+ ${op.total_cost.toFixed(4)}+ </Tag>+ </Space>+ </Descriptions.Item>+ ))}+ </Descriptions>+ )}++ <Button size="small" icon={<ReloadOutlined />} onClick={load} loading={loading}>Refresh</Button>+ </Space>+ ),+ }]} />+ );+};++export default ApiUsageSection;diff --git a/client/src/components/credentials/sections/LlmUsageSection.tsx b/client/src/components/credentials/sections/LlmUsageSection.tsxnew file mode 100644index 00000000..0117e166--- /dev/null+++ b/client/src/components/credentials/sections/LlmUsageSection.tsx@@ -0,0 +1,95 @@+/**+ * LlmUsageSection — token usage and costs for an AI provider.+ * Uses antd Collapse + Statistic + Descriptions for fully declarative display.+ */++import React, { useState, useEffect, useCallback } from 'react';+import { Collapse, Statistic, Descriptions, Alert, Space, Button, Spin, Flex } from 'antd';+import { DollarOutlined, ReloadOutlined } from '@ant-design/icons';+import { useAppTheme } from '../../../hooks/useAppTheme';+import { useApiKeys, type ProviderUsageSummary } from '../../../hooks/useApiKeys';++interface Props {+ providerId: string;+ providerName: string;+}++const LlmUsageSection: React.FC<Props> = ({ providerId, providerName }) => {+ const theme = useAppTheme();+ const { getProviderUsageSummary, isConnected } = useApiKeys();+ const [data, setData] = useState<ProviderUsageSummary | null>(null);+ const [loading, setLoading] = useState(false);+ const [expanded, setExpanded] = useState(false);++ const load = useCallback(async () => {+ if (!isConnected) return;+ setLoading(true);+ try {+ const summary = await getProviderUsageSummary();+ setData(summary.find(p => p.provider === providerId) ?? null);+ } finally {+ setLoading(false);+ }+ }, [isConnected, providerId, getProviderUsageSummary]);++ useEffect(() => { if (expanded) load(); }, [expanded, load]);++ return (+ <Collapse ghost+ onChange={keys => setExpanded(Array.isArray(keys) ? keys.includes('usage') : keys === 'usage')}+ items={[{+ key: 'usage',+ label: <Space><DollarOutlined /> Usage & Costs</Space>,+ children: loading ? (+ <Flex justify="center" style={{ padding: theme.spacing.lg }}><Spin size="small" /></Flex>+ ) : !data || data.execution_count === 0 ? (+ <Alert type="info" showIcon message={`No usage data yet for ${providerName}`} />+ ) : (+ <Space direction="vertical" size="middle" style={{ width: '100%' }}>+ <Flex gap={theme.spacing.lg} wrap="wrap">+ <Statistic title="Total Tokens" value={data.total_tokens}+ valueStyle={{ color: theme.dracula.cyan, fontSize: theme.fontSize.lg }} />+ <Statistic title="Total Cost" value={data.total_cost} precision={4} prefix="$"+ valueStyle={{ color: theme.dracula.green, fontSize: theme.fontSize.lg }} />+ <Statistic title="Executions" value={data.execution_count}+ valueStyle={{ color: theme.dracula.purple, fontSize: theme.fontSize.lg }} />+ </Flex>++ <Descriptions size="small" column={2} bordered>+ <Descriptions.Item label="Input Tokens">+ {data.total_input_tokens.toLocaleString()}+ <span style={{ color: theme.dracula.green, marginLeft: theme.spacing.sm }}>+ (${data.total_input_cost.toFixed(4)})+ </span>+ </Descriptions.Item>+ <Descriptions.Item label="Output Tokens">+ {data.total_output_tokens.toLocaleString()}+ <span style={{ color: theme.dracula.green, marginLeft: theme.spacing.sm }}>+ (${data.total_output_cost.toFixed(4)})+ </span>+ </Descriptions.Item>+ {data.total_cache_cost > 0 && (+ <Descriptions.Item label="Cache Cost" span={2}>+ <span style={{ color: theme.dracula.green }}>${data.total_cache_cost.toFixed(4)}</span>+ </Descriptions.Item>+ )}+ </Descriptions>++ {data.models.length > 1 && (+ <Descriptions size="small" column={1} title="By Model" bordered>+ {data.models.map(m => (+ <Descriptions.Item key={m.model} label={<code style={{ fontSize: theme.fontSize.xs }}>{m.model}</code>}>+ <span style={{ color: theme.dracula.green }}>${m.total_cost.toFixed(4)}</span>+ </Descriptions.Item>+ ))}+ </Descriptions>+ )}++ <Button size="small" icon={<ReloadOutlined />} onClick={load} loading={loading}>Refresh</Button>+ </Space>+ ),+ }]} />+ );+};++export default LlmUsageSection;diff --git a/client/src/components/credentials/sections/ProviderDefaultsSection.tsx b/client/src/components/credentials/sections/ProviderDefaultsSection.tsxnew file mode 100644index 00000000..9170a0ed--- /dev/null+++ b/client/src/components/credentials/sections/ProviderDefaultsSection.tsx@@ -0,0 +1,180 @@+/**+ * ProviderDefaultsSection — antd Form bound to a remote ProviderDefaults object.+ *+ * Uses:+ * - Form.useForm() + setFieldsValue() — replaces manual defaults state+ * - Form.Item with label+extra — replaces custom label/desc styling+ * - Form.Item shouldUpdate — reactive conditional fields from Form state+ * - Form.useWatch — react to default_model changes to refetch constraints+ * - Collapse native header — no custom rendering+ */++import React, { useState, useEffect, useCallback } from 'react';+import { Form, Collapse, Select, InputNumber, Switch, Button, Tag, Space, Spin } from 'antd';+import { SettingOutlined } from '@ant-design/icons';+import { useAppTheme } from '../../../hooks/useAppTheme';+import { useApiKeys, type ProviderDefaults, type ModelConstraints } from '../../../hooks/useApiKeys';++interface Props {+ providerId: string;+}++const ProviderDefaultsSection: React.FC<Props> = ({ providerId }) => {+ const theme = useAppTheme();+ const { getProviderDefaults, saveProviderDefaults, getStoredModels, getModelConstraints, isConnected } = useApiKeys();++ const [form] = Form.useForm<ProviderDefaults>();+ const [models, setModels] = useState<string[]>([]);+ const [constraints, setConstraints] = useState<ModelConstraints | null>(null);+ const [loading, setLoading] = useState(false);+ const [dirty, setDirty] = useState(false);++ // Watch default_model from the Form — refetch constraints when it changes+ const selectedModel = Form.useWatch('default_model', form);+ const thinkingEnabled = Form.useWatch('thinking_enabled', form);++ // Load defaults + models on mount+ useEffect(() => {+ if (!isConnected) return;+ let cancelled = false;+ (async () => {+ setLoading(true);+ try {+ const [d, m] = await Promise.all([getProviderDefaults(providerId), getStoredModels(providerId)]);+ if (!cancelled) {+ form.setFieldsValue(d);+ if (m?.length) setModels(m);+ setDirty(false);+ }+ } finally {+ if (!cancelled) setLoading(false);+ }+ })();+ return () => { cancelled = true; };+ }, [providerId, isConnected]);++ // Refetch constraints when selected model changes+ useEffect(() => {+ if (!isConnected || !selectedModel) return;+ let cancelled = false;+ getModelConstraints(selectedModel, providerId).then(c => {+ if (cancelled) return;+ setConstraints(c);+ if (c?.max_output_tokens && form.getFieldValue('max_tokens') !== c.max_output_tokens) {+ form.setFieldValue('max_tokens', c.max_output_tokens);+ }+ });+ return () => { cancelled = true; };+ }, [selectedModel, providerId, isConnected]);++ const handleSave = useCallback(async () => {+ setLoading(true);+ try {+ const values = form.getFieldsValue();+ const ok = await saveProviderDefaults(providerId, values);+ if (ok) setDirty(false);+ } finally {+ setLoading(false);+ }+ }, [form, providerId, saveProviderDefaults]);++ // Derived from constraints+ const [tempMin, tempMax] = constraints?.temperature_range ?? [0, 2];+ const maxOut = constraints?.max_output_tokens;+ const thinkType = constraints?.thinking_type;+ const canThink = constraints?.supports_thinking;+ const fixedTemp = constraints?.is_reasoning_model && tempMin === tempMax;++ const chipStyle = (bg: string): React.CSSProperties => ({+ margin: 0, fontSize: theme.fontSize.xs,+ backgroundColor: `${bg}20`, borderColor: `${bg}50`, color: bg,+ });++ return (+ <Collapse ghost defaultActiveKey={['defaults']} items={[{+ key: 'defaults',+ label: <Space><SettingOutlined /> Default Parameters</Space>,+ children: (+ <Spin spinning={loading}>+ <Form form={form} layout="vertical" size="small" onValuesChange={() => setDirty(true)} preserve>+ <Form.Item+ label="Default Model"+ name="default_model"+ extra="Model used when none specified"+ >+ <Select showSearch placeholder="Select model"+ options={models.map(m => ({ label: m, value: m }))}+ filterOption={(input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}+ notFoundContent={models.length ? 'No models found' : 'Validate API key first'}+ popupMatchSelectWidth={false}+ getPopupContainer={trigger => trigger.parentElement || document.body}+ listHeight={300}+ />+ </Form.Item>++ {constraints && (+ <Space wrap size="small" style={{ marginBottom: theme.spacing.md }}>+ {maxOut != null && <Tag style={chipStyle(theme.dracula.green)}>Max Output: {maxOut.toLocaleString()}</Tag>}+ {constraints.context_length != null && <Tag style={chipStyle(theme.dracula.cyan)}>Context: {constraints.context_length.toLocaleString()}</Tag>}+ <Tag style={chipStyle(theme.dracula.purple)}>Temp: {tempMin}-{tempMax}</Tag>+ {canThink && <Tag style={chipStyle(theme.dracula.orange)}>Thinking: {thinkType}</Tag>}+ {constraints.is_reasoning_model && <Tag style={chipStyle(theme.dracula.pink)}>Reasoning</Tag>}+ </Space>+ )}++ {!fixedTemp && (+ <Form.Item label="Temperature" name="temperature" extra={`Controls randomness (${tempMin}-${tempMax})`}>+ <InputNumber min={tempMin} max={tempMax} step={0.1} style={{ width: 100 }} />+ </Form.Item>+ )}++ <Form.Item label="Max Tokens" name="max_tokens"+ extra={maxOut != null ? `Up to ${maxOut.toLocaleString()}` : 'Maximum response length'}>+ <InputNumber min={1} max={maxOut || undefined} style={{ width: 140 }} />+ </Form.Item>++ {canThink && (+ <Form.Item label="Thinking / Reasoning" name="thinking_enabled" valuePropName="checked"+ extra={`Extended thinking (${thinkType})`}>+ <Switch />+ </Form.Item>+ )}++ {canThink && thinkType === 'budget' && thinkingEnabled && (+ <Form.Item label="Thinking Budget" name="thinking_budget" extra="Token budget (1024-16000)">+ <InputNumber min={1024} max={16000} style={{ width: 120 }} />+ </Form.Item>+ )}++ {canThink && thinkType === 'effort' && thinkingEnabled && (+ <Form.Item label="Reasoning Effort" name="reasoning_effort" extra="Low, medium, or high">+ <Select style={{ width: 130 }}+ options={[{ label: 'Low', value: 'low' }, { label: 'Medium', value: 'medium' }, { label: 'High', value: 'high' }]}+ getPopupContainer={trigger => trigger.parentElement || document.body} />+ </Form.Item>+ )}++ {canThink && thinkType === 'format' && thinkingEnabled && (+ <Form.Item label="Reasoning Format" name="reasoning_format" extra="Parsed or hidden">+ <Select style={{ width: 130 }}+ options={[{ label: 'Parsed', value: 'parsed' }, { label: 'Hidden', value: 'hidden' }]}+ getPopupContainer={trigger => trigger.parentElement || document.body} />+ </Form.Item>+ )}++ <Button onClick={handleSave} disabled={!dirty} loading={loading} block+ style={{+ backgroundColor: dirty ? `${theme.dracula.green}25` : undefined,+ borderColor: dirty ? `${theme.dracula.green}60` : undefined,+ color: dirty ? theme.dracula.green : undefined,+ }}>+ Save Defaults+ </Button>+ </Form>+ </Spin>+ ),+ }]} />+ );+};++export default ProviderDefaultsSection;diff --git a/client/src/components/credentials/sections/RateLimitSection.tsx b/client/src/components/credentials/sections/RateLimitSection.tsxnew file mode 100644index 00000000..0bf1810e--- /dev/null+++ b/client/src/components/credentials/sections/RateLimitSection.tsx@@ -0,0 +1,153 @@+/**+ * RateLimitSection — WhatsApp rate limit configuration.+ * antd Form bound to RateLimitConfig from WebSocket.+ */++import React, { useState, useEffect, useCallback } from 'react';+import { Form, Collapse, InputNumber, Switch, Button, Alert, Space, Statistic, Flex } from 'antd';+import { useAppTheme } from '../../../hooks/useAppTheme';+import { useWebSocket, type RateLimitConfig, type RateLimitStats } from '../../../contexts/WebSocketContext';++const RateLimitSection: React.FC = () => {+ const theme = useAppTheme();+ const { getWhatsAppRateLimitConfig, setWhatsAppRateLimitConfig, unpauseWhatsAppRateLimit } = useWebSocket();+ const [form] = Form.useForm<RateLimitConfig>();+ const [stats, setStats] = useState<RateLimitStats | null>(null);+ const [loading, setLoading] = useState(false);+ const [dirty, setDirty] = useState(false);+ const [loaded, setLoaded] = useState(false);++ const load = useCallback(async () => {+ setLoading(true);+ try {+ const result = await getWhatsAppRateLimitConfig();+ if (result.success && result.config) {+ form.setFieldsValue(result.config);+ setStats(result.stats ?? null);+ setDirty(false);+ setLoaded(true);+ }+ } finally {+ setLoading(false);+ }+ }, [form, getWhatsAppRateLimitConfig]);++ useEffect(() => { load(); }, [load]);++ const handleSave = useCallback(async () => {+ setLoading(true);+ try {+ const result = await setWhatsAppRateLimitConfig(form.getFieldsValue());+ if (result.success && result.config) {+ form.setFieldsValue(result.config);+ setDirty(false);+ }+ } finally {+ setLoading(false);+ }+ }, [form, setWhatsAppRateLimitConfig]);++ const handleUnpause = useCallback(async () => {+ setLoading(true);+ try {+ const result = await unpauseWhatsAppRateLimit();+ if (result.success && result.stats) setStats(result.stats);+ } finally {+ setLoading(false);+ }+ }, [unpauseWhatsAppRateLimit]);++ return (+ <Collapse items={[{+ key: 'ratelimits',+ label: 'Rate Limits',+ extra: (+ <span onClick={e => e.stopPropagation()}>+ <Form form={form} component={false}>+ <Form.Item name="enabled" valuePropName="checked" noStyle>+ <Switch size="small" onChange={() => setDirty(true)} />+ </Form.Item>+ </Form>+ </span>+ ),+ children: !loaded ? (+ <Flex justify="center" style={{ padding: theme.spacing.lg }}>Loading...</Flex>+ ) : (+ <Form form={form} layout="vertical" size="small" onValuesChange={() => setDirty(true)}>+ {stats && (+ <Flex gap={theme.spacing.md} wrap="wrap" style={{ marginBottom: theme.spacing.md }}>+ <Statistic title="Last Minute" value={stats.messages_sent_last_minute} />+ <Statistic title="Last Hour" value={stats.messages_sent_last_hour} />+ <Statistic title="Today" value={stats.messages_sent_today} />+ <Statistic title="New Contacts" value={stats.new_contacts_today} />+ <Statistic title="Responses" value={stats.responses_received} />+ <Statistic title="Response Rate" value={Math.round((stats.response_rate || 0) * 100)} suffix="%" />+ </Flex>+ )}+ {stats?.is_paused && (+ <Alert type="warning" message={stats.pause_reason || 'Paused'}+ action={<Button size="small" onClick={handleUnpause}>Unpause</Button>}+ style={{ marginBottom: theme.spacing.md }} />+ )}++ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs, fontWeight: theme.fontWeight.medium }}>+ Message Delays (milliseconds)+ </div>+ <Flex gap={theme.spacing.sm} wrap="wrap">+ <Form.Item label="Min Delay" name="min_delay_ms"><InputNumber style={{ width: 120 }} /></Form.Item>+ <Form.Item label="Max Delay" name="max_delay_ms"><InputNumber style={{ width: 120 }} /></Form.Item>+ <Form.Item label="Typing Duration" name="typing_delay_ms"><InputNumber style={{ width: 120 }} /></Form.Item>+ <Form.Item label="Link Extra Delay" name="link_extra_delay_ms"><InputNumber style={{ width: 120 }} /></Form.Item>+ </Flex>++ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs, fontWeight: theme.fontWeight.medium }}>+ Message Limits+ </div>+ <Flex gap={theme.spacing.sm} wrap="wrap">+ <Form.Item label="Per Minute" name="max_messages_per_minute"><InputNumber style={{ width: 120 }} /></Form.Item>+ <Form.Item label="Per Hour" name="max_messages_per_hour"><InputNumber style={{ width: 120 }} /></Form.Item>+ <Form.Item label="New Contacts/Day" name="max_new_contacts_per_day"><InputNumber style={{ width: 140 }} /></Form.Item>+ </Flex>++ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs, fontWeight: theme.fontWeight.medium }}>+ Behavior+ </div>+ <Space direction="vertical" size="small" style={{ width: '100%', marginBottom: theme.spacing.md }}>+ <Form.Item label="Simulate Typing" name="simulate_typing" valuePropName="checked"+ extra="Show typing indicator before sending" style={{ marginBottom: 0 }}>+ <Switch />+ </Form.Item>+ <Form.Item label="Randomize Delays" name="randomize_delays" valuePropName="checked"+ extra="Add variance between min/max delay" style={{ marginBottom: 0 }}>+ <Switch />+ </Form.Item>+ <Form.Item label="Pause on Low Response" name="pause_on_low_response" valuePropName="checked"+ extra="Auto-pause if response rate drops below threshold" style={{ marginBottom: 0 }}>+ <Switch />+ </Form.Item>+ <Form.Item shouldUpdate={(p, c) => p.pause_on_low_response !== c.pause_on_low_response} noStyle>+ {({ getFieldValue }) => getFieldValue('pause_on_low_response') && (+ <Form.Item label="Response Rate Threshold (%)" name="response_rate_threshold"+ normalize={(v: number) => v / 100}+ getValueProps={(v: number) => ({ value: Math.round((v ?? 0.3) * 100) })}>+ <InputNumber min={0} max={100} style={{ width: '100%' }} />+ </Form.Item>+ )}+ </Form.Item>+ </Space>++ <Button onClick={handleSave} loading={loading} disabled={!dirty} block+ style={{+ backgroundColor: dirty ? `${theme.dracula.green}25` : undefined,+ borderColor: dirty ? `${theme.dracula.green}60` : undefined,+ color: dirty ? theme.dracula.green : undefined,+ }}>+ Save Changes+ </Button>+ </Form>+ ),+ }]} />+ );+};++export default RateLimitSection;diff --git a/client/src/components/credentials/sections/index.ts b/client/src/components/credentials/sections/index.tsnew file mode 100644index 00000000..51ce2bb5--- /dev/null+++ b/client/src/components/credentials/sections/index.ts@@ -0,0 +1,4 @@+export { default as ProviderDefaultsSection } from './ProviderDefaultsSection';+export { default as LlmUsageSection } from './LlmUsageSection';+export { default as ApiUsageSection } from './ApiUsageSection';+export { default as RateLimitSection } from './RateLimitSection';diff --git a/client/src/components/credentials/types.ts b/client/src/components/credentials/types.tsnew file mode 100644index 00000000..e7e6a404--- /dev/null+++ b/client/src/components/credentials/types.ts@@ -0,0 +1,123 @@+/**+ * Credential system types.+ * Every provider is described by a single ProviderConfig object.+ * ALL conditional logic lives in config — panel components are pure renderers.+ */++import type { FC } from 'react';++// ============================================================================+// Panel kinds — one renderer branch per kind+// ============================================================================++export type PanelKind = 'apiKey' | 'oauth' | 'qrPairing' | 'email';++// ============================================================================+// Field schema — drives antd Form.Item rendering via FieldRenderer+// ============================================================================++export interface FieldDef {+ key: string;+ label: string;+ secret?: boolean;+ placeholder?: string;+ required?: boolean;+}++// ============================================================================+// Status row — drives StatusCard rendering from data+// ============================================================================++export interface StatusRowDef {+ label: string;+ /** Extract boolean from status object. StatusCard handles themed Tag rendering. */+ ok: (status: any) => boolean;+ trueText: string;+ falseText: string;+ /** Use warning color instead of error when not ok. */+ warn?: boolean;+}++// ============================================================================+// Action — drives ActionBar rendering from data+// ============================================================================++export interface ActionDef {+ key: string;+ label: string;+ /** Theme color key (e.g., 'green', 'pink', 'cyan', 'orange'). Resolved at render. */+ themeColor: string;+ /** Return true to hide this action. */+ hidden?: (status: any, stored: boolean) => boolean;+ /** Return true to disable this action. */+ disabled?: (status: any, stored: boolean) => boolean;+}++// ============================================================================+// QR pairing config — everything WhatsApp/Android-specific lives here+// ============================================================================++export interface QrPairingDef {+ /** Path to QR data in status object. */+ qrField: string;+ /** Check if device is connected/paired. */+ isConnected: (status: any) => boolean;+ connectedTitle: string;+ connectedSubtitle: (status: any) => string;+ /** Loading state for QR display. */+ isLoading: (status: any) => boolean;+ /** Empty text when no QR available. */+ emptyText: (status: any, stored: boolean) => string;+ scanText: string;+}++// ============================================================================+// Provider config — the ONLY thing you add to register a new provider+// ============================================================================++export interface ProviderConfig {+ id: string;+ name: string;+ category: string;+ categoryLabel: string;+ /** Theme color key (resolved via theme.colors[color] at render). */+ color: string;+ kind: PanelKind;+ icon: FC<{ size: number }>;++ /** Credential input fields. */+ fields?: FieldDef[];+ /** WebSocket commands for OAuth flows. */+ ws?: { login: string; logout: string; status: string };+ /** Which status hook to read. */+ statusHook?: 'whatsapp' | 'android' | 'twitter' | 'google' | 'telegram';+ /** Config-driven status rows (replaces per-provider conditionals). */+ statusRows?: StatusRowDef[];+ /** Config-driven actions (replaces per-provider handler code). */+ actions?: ActionDef[];+ /** QR pairing config (replaces isWhatsApp/isAndroid conditionals). */+ qr?: QrPairingDef;++ /** Non-standard validation type ('google_maps' | 'apify'). */+ validateAs?: string;+ /** OAuth callback URL shown as help text. */+ callbackUrl?: string;+ /** Help text shown under OAuth credential fields. */+ instructions?: string;+ /** Show AI provider defaults section (model, temperature, thinking). */+ hasDefaults?: boolean;+ /** Show WhatsApp rate limit configuration section. */+ hasRateLimits?: boolean;+ /** Service key for API cost tracking section (twitter, google_workspace, google_maps). */+ usageService?: string;+}++// ============================================================================+// Category — derived from providers, not declared separately+// ============================================================================++export interface CategoryGroup {+ key: string;+ label: string;+ items: ProviderConfig[];+}diff --git a/client/src/components/credentials/useCredentialPanel.ts b/client/src/components/credentials/useCredentialPanel.tsnew file mode 100644index 00000000..4d87e4c3--- /dev/null+++ b/client/src/components/credentials/useCredentialPanel.ts@@ -0,0 +1,95 @@+/**+ * useCredentialPanel — single hook replacing 20 useState calls + 19 handlers.+ *+ * Uses antd Form.useForm() for field state management.+ * Provides a generic `execute(key, fn)` that handles try/catch/loading/error+ * identically to every handleTwitterSave, handleGmailLogin, etc.+ */++import { useState, useEffect, useCallback } from 'react';+import { Form } from 'antd';+import { useApiKeys } from '../../hooks/useApiKeys';+import { useWebSocket } from '../../contexts/WebSocketContext';+import type { ProviderConfig } from './types';++export function useCredentialPanel(config: ProviderConfig, visible: boolean) {+ const [form] = Form.useForm();+ const [loading, setLoading] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [stored, setStored] = useState(false);++ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,+ validateGoogleMapsKey, validateApifyKey, getProviderDefaults, saveProviderDefaults,+ getProviderUsageSummary, getAPIUsageSummary, getStoredModels, getModelConstraints,+ isConnected } = useApiKeys();+ const { sendRequest } = useWebSocket();++ // Load stored values into form when panel becomes visible+ useEffect(() => {+ if (!visible || !isConnected || !config.fields) return;+ let cancelled = false;+ (async () => {+ const values: Record<string, string> = {};+ let anyStored = false;+ for (const field of config.fields!) {+ const has = await hasStoredKey(field.key === 'apiKey' ? config.id : field.key);+ if (has) {+ const val = await getStoredApiKey(field.key === 'apiKey' ? config.id : field.key);+ if (val && !cancelled) { values[field.key] = val; anyStored = true; }+ }+ }+ if (!cancelled) {+ form.setFieldsValue(values);+ setStored(anyStored);+ setError(null);+ }+ })();+ return () => { cancelled = true; };+ }, [config.id, visible, isConnected]);++ // Generic action executor — replaces all 19 duplicate handler functions+ const execute = useCallback(async (key: string, fn: () => Promise<any>) => {+ setLoading(key);+ setError(null);+ try {+ const result = await fn();+ if (result && !result.success && result.error) {+ setError(result.error);+ }+ return result;+ } catch (err: any) {+ setError(err.message || `Failed: ${key}`);+ return undefined;+ } finally {+ setLoading(null);+ }+ }, []);++ // Pre-built actions that panels call directly+ const actions = {+ validate: (id: string, key: string) => execute('validate', async () => {+ if (config.validateAs === 'google_maps') return validateGoogleMapsKey(key);+ if (config.validateAs === 'apify') return validateApifyKey(key);+ return validateApiKey(id, key);+ }),+ save: (key: string, value: string) => execute('save', () => saveApiKey(key, value)),+ remove: (key: string) => execute('remove', async () => { await removeApiKey(key); setStored(false); form.resetFields(); }),+ oauthLogin: () => execute('login', async () => {+ const res = await sendRequest(config.ws!.login, {});+ if (res.success && res.url) window.open(res.url, '_blank');+ return res;+ }),+ oauthLogout: () => execute('logout', () => sendRequest(config.ws!.logout, {})),+ oauthRefresh: () => execute('refresh', () => sendRequest(config.ws!.status, {})),+ sendWs: (type: string, data?: Record<string, any>) => execute(type, () => sendRequest(type, data ?? {})),+ };++ return {+ form, loading, error, stored, setStored, setError,+ execute, actions, isConnected,+ // Pass through API methods panels need+ getProviderDefaults, saveProviderDefaults,+ getProviderUsageSummary, getAPIUsageSummary,+ getStoredModels, getModelConstraints,+ };+}