Spaces:
Sleeping

olokaflow / apps /web /src /components /AIProfileHubView.tsx
phucsd's picture
feat(ui): apply Antigravity ui-ux-pro-max, taste-design, design-md & shadcn-ui with Lucide SVG icons
e602d40 verified
Raw History Blame Contribute Delete
30.2 kB
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<Props> = ({
profiles,
routings,
onRefresh,
}) => {
const [selectedProfileId, setSelectedProfileId] = useState<string>(
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<AIProviderProtocol>('openai-compatible');
const [formBaseUrl, setFormBaseUrl] = useState('');
const [formApiKey, setFormApiKey] = useState('');
const [formNotes, setFormNotes] = useState('');
const [newModelIdInput, setNewModelIdInput] = useState('');
const [testingState, setTestingState] = useState<string | null>(null);
const [testResult, setTestResult] = useState<AIConnectionTestResult | null>(
null
);
const [localRoutings, setLocalRoutings] =
useState<AIRoleRoutingEntry[]>(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 (
<div className="space-y-6">
{/* Header Banner */}
<div className="fliki-card p-6 bg-white flex flex-wrap items-center justify-between gap-4">
<div>
<Badge variant="crimson" className="mb-1.5">
<ShieldCheck className="w-3 h-3" />
Multi-Profile AI Hub • Mã hóa AES-256-GCM
</Badge>
<h2 className="text-xl font-bold tracking-tight text-zinc-900">
Quản Lý Đa Profile LLM, Giọng Đọc OlokaTTS & Kiểm Định Kết Nối API
</h2>
<p className="text-xs text-zinc-500 mt-0.5">
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.
</p>
</div>
<Button onClick={startNewProfile} variant="primary">
<Plus className="w-3.5 h-3.5" />
<span>Thêm Profile AI Mới</span>
</Button>
</div>
{/* Main Grid: Left Profile List / Right Active Profile Inspector */}
<div className="grid grid-cols-1 lg:grid-cols-12 gap-5">
{/* Left 4 Cols: Profiles List */}
<div className="lg:col-span-4 space-y-2.5">
<div className="text-xs font-bold uppercase tracking-wider text-zinc-500 px-1 flex items-center justify-between">
<span>Danh sách Profile</span>
<span className="font-mono tabular-nums">{profiles.length}</span>
</div>
{profiles.map((p) => {
const isSel = !isEditing && activeProfile?.id === p.id;
return (
<div
key={p.id}
onClick={() => {
setIsEditing(false);
setSelectedProfileId(p.id);
setTestResult(null);
}}
className={`${
isSel ? 'fliki-card-active' : 'fliki-card'
} p-4 bg-white cursor-pointer`}
>
<div className="flex items-start justify-between gap-2">
<div>
<div className="font-bold text-sm text-zinc-900">{p.name}</div>
<div className="text-xs text-zinc-500 font-mono truncate max-w-[230px] mt-0.5">
{p.baseUrl}
</div>
</div>
<Badge
variant={
p.healthStatus === 'healthy'
? 'emerald'
: p.healthStatus === 'failed'
? 'crimson'
: 'default'
}
mono
>
{p.healthStatus === 'healthy'
? `ONLINE ${p.lastLatencyMs ? `${p.lastLatencyMs}ms` : ''}`
: p.healthStatus.toUpperCase()}
</Badge>
</div>
<div className="mt-3 flex items-center justify-between text-[11px] text-zinc-500">
<span className="px-2 py-0.5 rounded-md bg-zinc-100 font-mono font-semibold text-zinc-700">
{p.protocol}
</span>
<span className="flex items-center gap-1 font-mono tabular-nums">
<KeyRound className="w-3 h-3 text-zinc-400" />
{p.models.length} model •{' '}
{p.hasApiKey ? 'Đã lưu Key' : 'Chưa nhập Key'}
</span>
</div>
</div>
);
})}
</div>
{/* Right 8 Cols: Profile Form or Live 4-Tier Tester */}
<div className="lg:col-span-8">
{isEditing ? (
<form
onSubmit={handleSaveProfile}
className="fliki-card p-6 bg-white space-y-4"
>
<div className="flex items-center justify-between border-b border-zinc-100 pb-3">
<h3 className="text-base font-bold text-zinc-900">
{selectedProfileId ? 'Chỉnh sửa Profile AI' : 'Thêm Profile AI Mới'}
</h3>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setIsEditing(false)}
>
<X className="w-3.5 h-3.5" />
<span>Hủy</span>
</Button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-semibold text-zinc-700 mb-1">
Tên hiển thị Profile *
</label>
<input
type="text"
value={formName}
onChange={(e) => 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]"
/>
</div>
<div>
<label className="block text-xs font-semibold text-zinc-700 mb-1">
Chuẩn giao thức (Protocol)
</label>
<select
value={formProtocol}
onChange={(e) => {
const val = e.target.value as AIProviderProtocol;
setFormProtocol(val);
const preset = PROTOCOL_OPTIONS.find((o) => o.value === val);
if (preset) setFormBaseUrl(preset.defaultUrl);
}}
className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-sm text-zinc-900"
>
{PROTOCOL_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
<div className="md:col-span-2">
<label className="block text-xs font-semibold text-zinc-700 mb-1">
API Base URL *
</label>
<input
type="text"
value={formBaseUrl}
onChange={(e) => 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]"
/>
</div>
<div className="md:col-span-2">
<label className="block text-xs font-semibold text-zinc-700 mb-1">
API Key / Secret Token (Mã hóa AES-256-GCM trên Server)
</label>
<input
type="password"
value={formApiKey}
onChange={(e) => 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]"
/>
</div>
<div className="md:col-span-2">
<label className="block text-xs font-semibold text-zinc-700 mb-1">
Ghi chú
</label>
<input
type="text"
value={formNotes}
onChange={(e) => 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"
/>
</div>
</div>
<div className="flex justify-end gap-2 pt-2">
<Button
type="button"
variant="secondary"
onClick={() => setIsEditing(false)}
>
Hủy
</Button>
<Button type="submit" variant="primary">
<Save className="w-3.5 h-3.5" />
<span>Lưu Profile AI</span>
</Button>
</div>
</form>
) : (
activeProfile && (
<div className="fliki-card p-6 bg-white space-y-5">
{/* Active Profile Header & Action Buttons */}
<div className="flex flex-wrap items-start justify-between gap-3 border-b border-zinc-100 pb-4">
<div>
<div className="flex items-center gap-2">
<h3 className="text-lg font-bold text-zinc-900">
{activeProfile.name}
</h3>
<Badge variant="default" mono>
{activeProfile.protocol}
</Badge>
</div>
<p className="text-xs font-mono text-zinc-500 mt-1">
Endpoint: {activeProfile.baseUrl} • Key:{' '}
{activeProfile.maskedApiKey || '(Chưa cấu hình)'}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button
variant="primary"
onClick={() => handleTestConnection(activeProfile)}
disabled={testingState !== null}
>
<Zap className="w-3.5 h-3.5" />
<span>
{testingState === 'ping' ? 'Đang Ping...' : 'Test Kết Nối (Ping)'}
</span>
</Button>
<Button
variant="dark"
onClick={() => handleFetchModels(activeProfile)}
disabled={testingState !== null}
>
<RefreshCw
className={`w-3.5 h-3.5 ${
testingState === 'fetch-models' ? 'animate-spin' : ''
}`}
/>
<span>
{testingState === 'fetch-models'
? 'Đang quét...'
: 'Quét Danh Sách Model (/models)'}
</span>
</Button>
{activeProfile.protocol === 'openai-voice' && (
<Button
variant="outlineCrimson"
onClick={() => handleTestSpecialized(activeProfile, 'voice')}
disabled={testingState !== null}
>
<Mic className="w-3.5 h-3.5" />
<span>Test Đọc Giọng TTS</span>
</Button>
)}
{activeProfile.protocol === 'huggingface' && (
<Button
variant="outlineCrimson"
onClick={() => handleTestSpecialized(activeProfile, 'image_gen')}
disabled={testingState !== null}
>
<ImageIcon className="w-3.5 h-3.5" />
<span>Test Sinh Ảnh FLUX.1</span>
</Button>
)}
<Button
variant="secondary"
onClick={() => startEditProfile(activeProfile)}
>
<Edit3 className="w-3.5 h-3.5" />
<span>Sửa Key / URL</span>
</Button>
</div>
</div>
{/* Live Test Result Output Box */}
{testResult && (
<div
className={`p-4 rounded-2xl border text-xs space-y-2 ${
testResult.success
? 'bg-emerald-50/90 border-emerald-200 text-emerald-950'
: 'bg-rose-50/90 border-rose-200 text-rose-950'
}`}
>
<div className="flex items-center justify-between font-bold">
<span className="flex items-center gap-1.5">
{testResult.success ? (
<CheckCircle2 className="w-4 h-4 text-emerald-600" />
) : (
<AlertCircle className="w-4 h-4 text-[#E11D48]" />
)}
{testResult.success
? 'KẾT QUẢ TEST THÀNH CÔNG'
: 'KẾT QUẢ TEST LỖI'}
</span>
<span className="font-mono tabular-nums">
Tổng: {testResult.durationMs}ms
{testResult.ttftMs ? ` • TTFT: ${testResult.ttftMs}ms` : ''}
</span>
</div>
<p>{testResult.message}</p>
{testResult.sampleOutput && (
<pre className="p-2.5 rounded-xl bg-white/90 border border-zinc-200 font-mono text-[11px] text-zinc-800 overflow-x-auto">
{testResult.sampleOutput}
</pre>
)}
{testResult.audioPreviewUrl && (
<audio
src={testResult.audioPreviewUrl}
controls
autoPlay
className="h-9 w-full mt-2"
/>
)}
{testResult.imagePreviewUrl && (
<img
src={testResult.imagePreviewUrl}
alt="Test Generated"
className="w-36 h-36 rounded-xl object-cover border border-zinc-200 mt-2"
/>
)}
</div>
)}
{/* Models List inside Active Profile */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<h4 className="text-xs font-bold uppercase tracking-wider text-zinc-600">
Danh sách Model trong Profile ({activeProfile.models.length})
</h4>
<div className="flex gap-2">
<input
type="text"
value={newModelIdInput}
onChange={(e) => 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"
/>
<Button
type="button"
variant="dark"
size="sm"
onClick={() => handleAddManualModel(activeProfile)}
>
<Plus className="w-3.5 h-3.5" />
<span>Thêm Model</span>
</Button>
</div>
</div>
<div className="divide-y divide-zinc-100 border border-zinc-200 rounded-2xl overflow-hidden">
{activeProfile.models.map((m) => (
<div
key={m.id}
className="p-3.5 bg-white hover:bg-zinc-50/70 flex flex-wrap items-center justify-between gap-3"
>
<div>
<div className="flex items-center gap-2">
<span className="font-mono font-bold text-xs text-zinc-900">
{m.modelId}
</span>
{m.ttftMs && (
<Badge variant="emerald" mono>
TTFT {m.ttftMs}ms
</Badge>
)}
</div>
<div className="flex flex-wrap gap-1 mt-1">
{m.capabilities.map((c) => (
<span
key={c}
className="px-2 py-0.5 rounded-md bg-zinc-100 text-zinc-600 text-[10px] font-mono font-semibold"
>
{c}
</span>
))}
</div>
</div>
<div className="flex items-center gap-1.5">
<Button
type="button"
variant="outlineCrimson"
size="sm"
onClick={() => handleTestModel(activeProfile, m.modelId)}
disabled={testingState !== null}
>
<Activity className="w-3.5 h-3.5" />
<span>
{testingState === `model-${m.modelId}`
? 'Đang test...'
: 'Test Chat & JSON'}
</span>
</Button>
{m.capabilities.includes('vision') && (
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => handleTestVision(activeProfile, m.modelId)}
disabled={testingState !== null}
>
<Eye className="w-3.5 h-3.5" />
<span>Test Vision</span>
</Button>
)}
</div>
</div>
))}
</div>
</div>
</div>
)
)}
</div>
</div>
{/* =====================================================================
TASK-TO-MODEL ROLE ROUTING MATRIX WITH AUTOMATIC FAILOVER
===================================================================== */}
<div className="fliki-card p-6 bg-white space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-zinc-100 pb-4">
<div>
<h3 className="text-base font-bold text-zinc-900 flex items-center gap-2">
<GitBranch className="w-4 h-4 text-[#E11D48]" />
<span>
Ma Trận Phân Phối Nhiệm Vụ Đa Tác Tử (Role Routing Matrix & Auto-Failover)
</span>
</h3>
<p className="text-xs text-zinc-500 mt-0.5">
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.
</p>
</div>
<Button
type="button"
variant="primary"
onClick={handleSaveRoutings}
disabled={savingRouting}
>
<Save className="w-3.5 h-3.5" />
<span>{savingRouting ? 'Đang lưu...' : 'Lưu Cấu Hình Phân Phối'}</span>
</Button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3.5">
{localRoutings.map((rt, idx) => {
const primProf = profiles.find((p) => p.id === rt.primaryProfileId);
return (
<div
key={rt.role}
className="p-4 rounded-2xl bg-zinc-50/70 border border-zinc-200/90 space-y-2.5"
>
<div>
<div className="text-xs font-bold text-zinc-900">{rt.label}</div>
<div className="text-[11px] text-zinc-500">{rt.description}</div>
</div>
<div className="grid grid-cols-2 gap-2">
<div>
<label className="block text-[10px] font-bold uppercase text-zinc-500 mb-1">
Profile Chính
</label>
<select
value={rt.primaryProfileId}
onChange={(e) => {
const next = [...localRoutings];
const p = profiles.find((x) => x.id === e.target.value);
next[idx] = {
...rt,
primaryProfileId: e.target.value,
primaryModelId: p?.models[0]?.modelId || '',
};
setLocalRoutings(next);
}}
className="w-full bg-white border border-zinc-200 rounded-xl px-2.5 py-1.5 text-xs font-semibold text-zinc-800"
>
{profiles.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
</div>
<div>
<label className="block text-[10px] font-bold uppercase text-zinc-500 mb-1">
Model Chính
</label>
<input
type="text"
list={`models-${rt.role}`}
value={rt.primaryModelId}
onChange={(e) => {
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"
/>
<datalist id={`models-${rt.role}`}>
{(primProf?.models || []).map((m) => (
<option key={m.id} value={m.modelId}>
{m.name}
</option>
))}
</datalist>
</div>
</div>
</div>
);
})}
</div>
</div>
</div>
);
};