import React, { useState } from 'react'; import { Cpu, ShieldCheck, Plus, Zap, RefreshCw, Mic, Image as ImageIcon, Edit3, CheckCircle2, AlertCircle, KeyRound, Save, X, Eye, Activity, GitBranch, } from 'lucide-react'; import { api } from '../api'; import type { AIProviderProfile, AIRoleRoutingEntry, AIConnectionTestResult, AIProviderProtocol, AIModelCapability, } from '@olokaflow/shared'; import { Button, Badge } from './ui/primitives'; interface Props { profiles: AIProviderProfile[]; routings: AIRoleRoutingEntry[]; onRefresh: () => void; } const PROTOCOL_OPTIONS: Array<{ value: AIProviderProtocol; label: string; defaultUrl: string; }> = [ { value: 'openai-compatible', label: 'OpenAI-Compatible Gateway (vLLM / LiteLLM / OpenRouter / DeepSeek / MiMo)', defaultUrl: 'https://openrouter.ai/api/v1', }, { value: 'gemini', label: 'Google Gemini (OpenAI / Native Endpoint)', defaultUrl: 'https://generativelanguage.googleapis.com/v1beta/openai', }, { value: 'anthropic', label: 'Anthropic Claude (/v1/messages)', defaultUrl: 'https://api.anthropic.com/v1', }, { value: 'openai-voice', label: 'OlokaTTS (https://tts.oloka.net) & OpenAI Voice (/v1/audio/speech)', defaultUrl: 'https://tts.oloka.net', }, { value: 'huggingface', label: 'Hugging Face Pro Inference (FLUX.1 Image Gen)', defaultUrl: 'https://router.huggingface.co/hf-inference/models', }, { value: 'modal-render', label: 'Modal Serverless HyperFrames Render Endpoint', defaultUrl: 'https://phucsd--autocode-hyperframes-renderer-web.modal.run', }, ]; export const AIProfileHubView: React.FC = ({ profiles, routings, onRefresh, }) => { const [selectedProfileId, setSelectedProfileId] = useState( profiles[0]?.id || '' ); const activeProfile = profiles.find((p) => p.id === selectedProfileId) || profiles[0]; const [isEditing, setIsEditing] = useState(false); const [formName, setFormName] = useState(''); const [formProtocol, setFormProtocol] = useState('openai-compatible'); const [formBaseUrl, setFormBaseUrl] = useState(''); const [formApiKey, setFormApiKey] = useState(''); const [formNotes, setFormNotes] = useState(''); const [newModelIdInput, setNewModelIdInput] = useState(''); const [testingState, setTestingState] = useState(null); const [testResult, setTestResult] = useState( null ); const [localRoutings, setLocalRoutings] = useState(routings); const [savingRouting, setSavingRouting] = useState(false); React.useEffect(() => { setLocalRoutings(routings); }, [routings]); function startNewProfile() { setIsEditing(true); setSelectedProfileId(''); setFormName('Cổng LLM OpenAI-Compatible Mới'); setFormProtocol('openai-compatible'); setFormBaseUrl('https://openrouter.ai/api/v1'); setFormApiKey(''); setFormNotes('Cổng AI tùy chỉnh'); setTestResult(null); } function startEditProfile(p: AIProviderProfile) { setIsEditing(true); setSelectedProfileId(p.id); setFormName(p.name); setFormProtocol(p.protocol); setFormBaseUrl(p.baseUrl); setFormApiKey(p.maskedApiKey || ''); setFormNotes(p.notes || ''); setTestResult(null); } async function handleSaveProfile(e: React.FormEvent) { e.preventDefault(); try { const existing = profiles.find((p) => p.id === selectedProfileId); const res = await api.saveAIProfile({ id: selectedProfileId || undefined, name: formName, protocol: formProtocol, baseUrl: formBaseUrl, apiKey: formApiKey, notes: formNotes, models: existing?.models || [], }); setIsEditing(false); setSelectedProfileId(res.profile.id); onRefresh(); } catch (err: any) { alert(`Lỗi lưu Profile: ${err.message}`); } } async function handleFetchModels(p: AIProviderProfile) { setTestingState('fetch-models'); setTestResult(null); try { const res = await api.fetchModelsFromEndpoint({ profileId: p.id }); setTestResult({ success: true, testType: 'connection', durationMs: 120, message: res.message, testedAt: new Date().toISOString(), }); onRefresh(); } catch (err: any) { setTestResult({ success: false, testType: 'connection', durationMs: 0, message: err.message, testedAt: new Date().toISOString(), }); } finally { setTestingState(null); } } async function handleTestConnection(p: AIProviderProfile) { setTestingState('ping'); setTestResult(null); try { const res = await api.testProfileConnection({ profileId: p.id }); setTestResult(res.result); onRefresh(); } finally { setTestingState(null); } } async function handleTestModel(p: AIProviderProfile, modelId: string) { setTestingState(`model-${modelId}`); setTestResult(null); try { const res = await api.testModelPreflight({ profileId: p.id, modelId }); setTestResult(res.result); onRefresh(); } finally { setTestingState(null); } } async function handleTestVision(p: AIProviderProfile, modelId: string) { setTestingState(`vision-${modelId}`); setTestResult(null); try { const res = await api.testModelVision({ profileId: p.id, modelId }); setTestResult(res.result); onRefresh(); } finally { setTestingState(null); } } async function handleTestSpecialized( p: AIProviderProfile, kind: 'voice' | 'image_gen' | 'modal_render', modelId?: string ) { setTestingState(`spec-${kind}`); setTestResult(null); try { const res = await api.testMediaEndpoint({ profileId: p.id, testKind: kind, modelId, }); setTestResult(res.result); onRefresh(); } finally { setTestingState(null); } } async function handleAddManualModel(p: AIProviderProfile) { const cleanId = newModelIdInput.trim(); if (!cleanId) return; const defaultCaps: AIModelCapability[] = p.protocol === 'openai-voice' ? ['tts'] : p.protocol === 'huggingface' ? ['image_gen'] : ['chat', 'coding', 'json_mode', 'vision']; await api.saveAIProfile({ ...p, models: [ ...p.models, { id: `mdl-${cleanId.replace(/[^a-zA-Z0-9_-]/g, '-')}`, modelId: cleanId, name: cleanId, ownedBy: p.protocol, capabilities: defaultCaps, supportsThinking: cleanId.includes('r1') || cleanId.includes('reason'), reasoningEffort: 'none', maxTokens: 8192, healthStatus: 'untested', lastTestedAt: null, ttftMs: null, durationMs: null, lastTestMessage: '', }, ], }); setNewModelIdInput(''); onRefresh(); } async function handleSaveRoutings() { setSavingRouting(true); try { await api.saveRoleRoutings(localRoutings); onRefresh(); } finally { setSavingRouting(false); } } return (
{/* Header Banner */}
Multi-Profile AI Hub • Mã hóa AES-256-GCM

Quản Lý Đa Profile LLM, Giọng Đọc OlokaTTS & Kiểm Định Kết Nối API

Kết nối không giới hạn các cổng OpenAI-compatible tự host, Gemini, Claude, OlokaTTS (https://tts.oloka.net), Hugging Face Pro FLUX.1 và Modal Cloud Render.

{/* Main Grid: Left Profile List / Right Active Profile Inspector */}
{/* Left 4 Cols: Profiles List */}
Danh sách Profile {profiles.length}
{profiles.map((p) => { const isSel = !isEditing && activeProfile?.id === p.id; return (
{ setIsEditing(false); setSelectedProfileId(p.id); setTestResult(null); }} className={`${ isSel ? 'fliki-card-active' : 'fliki-card' } p-4 bg-white cursor-pointer`} >
{p.name}
{p.baseUrl}
{p.healthStatus === 'healthy' ? `ONLINE ${p.lastLatencyMs ? `${p.lastLatencyMs}ms` : ''}` : p.healthStatus.toUpperCase()}
{p.protocol} {p.models.length} model •{' '} {p.hasApiKey ? 'Đã lưu Key' : 'Chưa nhập Key'}
); })}
{/* Right 8 Cols: Profile Form or Live 4-Tier Tester */}
{isEditing ? (

{selectedProfileId ? 'Chỉnh sửa Profile AI' : 'Thêm Profile AI Mới'}

setFormName(e.target.value)} required className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-sm text-zinc-900 focus:outline-none focus:border-[#E11D48]" />
setFormBaseUrl(e.target.value)} required placeholder="https://..." className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-sm font-mono text-zinc-900 focus:outline-none focus:border-[#E11D48]" />
setFormApiKey(e.target.value)} placeholder="Nhập sk-... hoặc Bearer token (Để trống nếu giữ nguyên key cũ)" className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-sm font-mono text-zinc-900 focus:outline-none focus:border-[#E11D48]" />
setFormNotes(e.target.value)} className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-sm text-zinc-900" />
) : ( activeProfile && (
{/* Active Profile Header & Action Buttons */}

{activeProfile.name}

{activeProfile.protocol}

Endpoint: {activeProfile.baseUrl} • Key:{' '} {activeProfile.maskedApiKey || '(Chưa cấu hình)'}

{activeProfile.protocol === 'openai-voice' && ( )} {activeProfile.protocol === 'huggingface' && ( )}
{/* Live Test Result Output Box */} {testResult && (
{testResult.success ? ( ) : ( )} {testResult.success ? 'KẾT QUẢ TEST THÀNH CÔNG' : 'KẾT QUẢ TEST LỖI'} Tổng: {testResult.durationMs}ms {testResult.ttftMs ? ` • TTFT: ${testResult.ttftMs}ms` : ''}

{testResult.message}

{testResult.sampleOutput && (
                        {testResult.sampleOutput}
                      
)} {testResult.audioPreviewUrl && (
)} {/* Models List inside Active Profile */}

Danh sách Model trong Profile ({activeProfile.models.length})

setNewModelIdInput(e.target.value)} placeholder="Thêm mã Model ID thủ công..." className="bg-zinc-50 border border-zinc-200 rounded-xl px-3 py-1.5 text-xs font-mono text-zinc-900" />
{activeProfile.models.map((m) => (
{m.modelId} {m.ttftMs && ( TTFT {m.ttftMs}ms )}
{m.capabilities.map((c) => ( {c} ))}
{m.capabilities.includes('vision') && ( )}
))}
) )}
{/* ===================================================================== TASK-TO-MODEL ROLE ROUTING MATRIX WITH AUTOMATIC FAILOVER ===================================================================== */}

Ma Trận Phân Phối Nhiệm Vụ Đa Tác Tử (Role Routing Matrix & Auto-Failover)

Gán từng vai trò trong pipeline tạo video cho Profile & Model chính + dự phòng tự động chuyển đổi khi quá tải.

{localRoutings.map((rt, idx) => { const primProf = profiles.find((p) => p.id === rt.primaryProfileId); return (
{rt.label}
{rt.description}
{ const next = [...localRoutings]; next[idx] = { ...rt, primaryModelId: e.target.value }; setLocalRoutings(next); }} className="w-full bg-white border border-zinc-200 rounded-xl px-2.5 py-1.5 text-xs font-mono font-bold text-zinc-800" /> {(primProf?.models || []).map((m) => ( ))}
); })}
); };