Compare commits

...

2 Commits

Author SHA1 Message Date
Xin Wang
47207dab19 边栏缩略图,小助手添加工具配置,添加自动测试大类 2026-02-04 16:35:44 +08:00
Xin Wang
75914cf2e6 Update workflow 2026-02-02 10:10:24 +08:00
9 changed files with 1910 additions and 333 deletions

69
App.tsx
View File

@@ -1,6 +1,7 @@
import React, { useState } from 'react';
import { HashRouter as Router, Routes, Route, Link, useLocation, Navigate } from 'react-router-dom';
import { Bot, Phone, Book, User, LayoutDashboard, Cpu, Mic2, Video } from 'lucide-react';
import { HashRouter as Router, Routes, Route, Link, useLocation } from 'react-router-dom';
import { Bot, Phone, Book, User, LayoutDashboard, Mic2, Video, GitBranch, Zap, PanelLeftClose, PanelLeftOpen } from 'lucide-react';
import { AssistantsPage } from './pages/Assistants';
import { KnowledgeBasePage } from './pages/KnowledgeBase';
@@ -8,19 +9,24 @@ import { CallLogsPage } from './pages/CallLogs';
import { ProfilePage } from './pages/Profile';
import { DashboardPage } from './pages/Dashboard';
import { VoiceLibraryPage } from './pages/VoiceLibrary';
import { WorkflowsPage } from './pages/Workflows';
import { WorkflowEditorPage } from './pages/WorkflowEditor';
import { AutoTestPage } from './pages/AutoTest';
const SidebarItem: React.FC<{ to: string; icon: React.ReactNode; label: string; active: boolean }> = ({ to, icon, label, active }) => (
const SidebarItem: React.FC<{ to: string; icon: React.ReactNode; label: string; active: boolean; isCollapsed: boolean }> = ({ to, icon, label, active, isCollapsed }) => (
<Link
to={to}
className={`flex items-center space-x-3 px-4 py-3 rounded-md transition-all duration-200 ${active ? 'bg-primary/20 text-primary border-r-2 border-primary' : 'text-muted-foreground hover:bg-muted/50 hover:text-foreground'}`}
title={isCollapsed ? label : undefined}
className={`flex items-center space-x-3 px-4 py-3 rounded-md transition-all duration-300 ${active ? 'bg-primary/20 text-primary border-r-2 border-primary' : 'text-muted-foreground hover:bg-muted/50 hover:text-foreground'} ${isCollapsed ? 'justify-center space-x-0 px-2' : ''}`}
>
{icon}
<span className="font-medium text-sm">{label}</span>
<div className="shrink-0">{icon}</div>
{!isCollapsed && <span className="font-medium text-sm animate-in fade-in duration-300 whitespace-nowrap overflow-hidden">{label}</span>}
</Link>
);
const AppLayout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const location = useLocation();
const [isCollapsed, setIsCollapsed] = useState(false);
const navItems = [
{ path: '/', label: '首页', icon: <LayoutDashboard className="h-5 w-5" /> },
@@ -28,48 +34,67 @@ const AppLayout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
{ path: '/voices', label: '声音库', icon: <Mic2 className="h-5 w-5" /> },
{ path: '/call-logs', label: '视频通话记录', icon: <Phone className="h-5 w-5" /> },
{ path: '/knowledge', label: '知识库', icon: <Book className="h-5 w-5" /> },
{ path: '/workflows', label: '工作流', icon: <GitBranch className="h-5 w-5" /> },
{ path: '/auto-test', label: '自动测试', icon: <Zap className="h-5 w-5" /> },
{ path: '/profile', label: '个人中心', icon: <User className="h-5 w-5" /> },
];
return (
<div className="flex h-screen overflow-hidden">
{/* Sidebar with Glass effect */}
<aside className="w-64 border-r border-border/40 bg-card/30 backdrop-blur-md hidden md:flex flex-col">
<div className="p-6 flex items-center space-x-3 border-b border-border/40 overflow-hidden">
{/* Cool Logo */}
{/* Sidebar with Glass effect and collapse logic */}
<aside
className={`border-r border-border/40 bg-card/30 backdrop-blur-md hidden md:flex flex-col transition-all duration-300 ease-in-out relative group ${isCollapsed ? 'w-20' : 'w-64'}`}
>
<div className={`p-6 flex items-center border-b border-border/40 overflow-hidden transition-all duration-300 ${isCollapsed ? 'justify-center px-4' : 'space-x-3'}`}>
<div className="h-10 w-10 shrink-0 bg-gradient-to-br from-cyan-400 to-blue-600 rounded-xl flex items-center justify-center shadow-[0_0_20px_rgba(6,182,212,0.5)] border border-white/10">
<Video className="h-6 w-6 text-white drop-shadow-md" />
</div>
{/* No Wrap Title */}
<span className="text-lg font-bold tracking-wide whitespace-nowrap bg-clip-text text-transparent bg-gradient-to-r from-white to-white/80">
AI VideoAssistant
</span>
{!isCollapsed && (
<span className="text-lg font-bold tracking-wide whitespace-nowrap bg-clip-text text-transparent bg-gradient-to-r from-white to-white/80 animate-in slide-in-from-left-2">
AI VideoAssistant
</span>
)}
</div>
<nav className="flex-1 p-4 space-y-2">
<nav className="flex-1 p-4 space-y-2 overflow-y-auto overflow-x-hidden custom-scrollbar">
{navItems.map(item => (
<SidebarItem
key={item.path}
to={item.path}
icon={item.icon}
label={item.label}
isCollapsed={isCollapsed}
active={item.path === '/' ? location.pathname === '/' : location.pathname.startsWith(item.path)}
/>
))}
</nav>
<div className="p-4 border-t border-border/40 text-xs text-muted-foreground text-center font-mono">
SYSTEM v2.0
{/* Footer with Version and Collapse Button */}
<div className={`p-4 border-t border-border/40 flex items-center transition-all duration-300 ${isCollapsed ? 'justify-center' : 'justify-between'}`}>
{!isCollapsed && (
<span className="text-[10px] text-muted-foreground font-mono opacity-60 animate-in fade-in">
SYSTEM v2.0
</span>
)}
<button
onClick={() => setIsCollapsed(!isCollapsed)}
title={isCollapsed ? "展开边栏" : "收起边栏"}
className={`p-1.5 rounded-md hover:bg-white/5 text-muted-foreground hover:text-primary transition-all ${isCollapsed ? '' : 'ml-2'}`}
>
{isCollapsed ? <PanelLeftOpen className="h-4 w-4" /> : <PanelLeftClose className="h-4 w-4" />}
</button>
</div>
</aside>
{/* Main Content */}
<main className="flex-1 flex flex-col overflow-hidden relative">
<main className="flex-1 flex flex-col overflow-hidden relative bg-background">
<header className="h-16 border-b border-border/40 flex items-center px-6 bg-card/30 backdrop-blur-md md:hidden space-x-3">
<div className="h-8 w-8 bg-gradient-to-br from-cyan-400 to-blue-600 rounded-lg flex items-center justify-center shadow-lg">
<Video className="h-5 w-5 text-white" />
</div>
<span className="font-bold text-lg whitespace-nowrap">AI VideoAssistant</span>
<span className="font-bold text-lg whitespace-nowrap text-white">AI VideoAssistant</span>
</header>
<div className="flex-1 overflow-auto p-6 md:p-8">
<div className="flex-1 overflow-auto p-4 md:p-6 transition-all duration-300">
{children}
</div>
</main>
@@ -87,6 +112,10 @@ const App: React.FC = () => {
<Route path="/voices" element={<VoiceLibraryPage />} />
<Route path="/knowledge" element={<KnowledgeBasePage />} />
<Route path="/call-logs" element={<CallLogsPage />} />
<Route path="/workflows" element={<WorkflowsPage />} />
<Route path="/workflows/new" element={<WorkflowEditorPage />} />
<Route path="/workflows/edit/:id" element={<WorkflowEditorPage />} />
<Route path="/auto-test" element={<AutoTestPage />} />
<Route path="/profile" element={<ProfilePage />} />
</Routes>
</AppLayout>

View File

@@ -1,11 +1,20 @@
import React, { useState, useEffect, useRef } from 'react';
import { Plus, Search, Play, Copy, Trash2, Edit2, Mic, MessageSquare, Save, Video, PhoneOff, Camera, ArrowLeftRight, Send, Phone, MoreHorizontal, Rocket, AlertTriangle } from 'lucide-react';
import { Plus, Search, Play, Copy, Trash2, Edit2, Mic, MessageSquare, Save, Video, PhoneOff, Camera, ArrowLeftRight, Send, Phone, MoreHorizontal, Rocket, AlertTriangle, PhoneCall, CameraOff, Image, Images, CloudSun, Calendar, TrendingUp, Coins, Wrench, Globe, Terminal, X } from 'lucide-react';
import { Button, Input, Card, Badge, Drawer, Dialog } from '../components/UI';
import { mockAssistants, mockKnowledgeBases } from '../services/mockData';
import { Assistant, TabValue } from '../types';
import { GoogleGenAI } from "@google/genai";
interface ToolItem {
id: string;
name: string;
icon: React.ReactNode;
desc: string;
category: 'system' | 'query';
isCustom?: boolean;
}
export const AssistantsPage: React.FC = () => {
const [assistants, setAssistants] = useState<Assistant[]>(mockAssistants);
const [searchTerm, setSearchTerm] = useState('');
@@ -14,6 +23,16 @@ export const AssistantsPage: React.FC = () => {
const [debugOpen, setDebugOpen] = useState(false);
const [hotwordInput, setHotwordInput] = useState('');
// Custom Tools State
const [customTools, setCustomTools] = useState<ToolItem[]>([]);
const [hiddenToolIds, setHiddenToolIds] = useState<string[]>([]); // Track deleted/hidden base tools
const [isAddToolModalOpen, setIsAddToolModalOpen] = useState(false);
const [addingToCategory, setAddingToCategory] = useState<'system' | 'query'>('system');
// New Tool Form State
const [newToolName, setNewToolName] = useState('');
const [newToolDesc, setNewToolDesc] = useState('');
// State for delete confirmation dialog
const [deleteId, setDeleteId] = useState<string | null>(null);
@@ -35,7 +54,8 @@ export const AssistantsPage: React.FC = () => {
language: 'zh',
voice: 'default',
speed: 1,
hotwords: []
hotwords: [],
tools: []
};
setAssistants([...assistants, newAssistant]);
setSelectedId(newId);
@@ -65,6 +85,31 @@ export const AssistantsPage: React.FC = () => {
setAssistants(prev => prev.map(a => a.id === selectedId ? { ...a, [field]: value } : a));
};
const toggleTool = (toolId: string) => {
if (!selectedAssistant) return;
const currentTools = selectedAssistant.tools || [];
const newTools = currentTools.includes(toolId)
? currentTools.filter(id => id !== toolId)
: [...currentTools, toolId];
updateAssistant('tools', newTools);
};
const deleteTool = (e: React.MouseEvent, toolId: string) => {
e.stopPropagation();
// 1. Remove from assistant configurations if enabled
setAssistants(prev => prev.map(a => ({
...a,
tools: a.tools?.filter(id => id !== toolId) || []
})));
// 2. Remove from tool list
if (customTools.some(t => t.id === toolId)) {
setCustomTools(prev => prev.filter(t => t.id !== toolId));
} else {
setHiddenToolIds(prev => [...prev, toolId]);
}
};
const addHotword = () => {
if (hotwordInput.trim() && selectedAssistant) {
updateAssistant('hotwords', [...selectedAssistant.hotwords, hotwordInput.trim()]);
@@ -78,12 +123,52 @@ export const AssistantsPage: React.FC = () => {
}
};
const handleAddCustomTool = () => {
if (!newToolName.trim()) return;
const newTool: ToolItem = {
id: `custom_${Date.now()}`,
name: newToolName,
desc: newToolDesc,
category: addingToCategory,
icon: addingToCategory === 'system' ? <Terminal className="w-4 h-4" /> : <Globe className="w-4 h-4" />,
isCustom: true
};
setCustomTools([...customTools, newTool]);
setIsAddToolModalOpen(false);
setNewToolName('');
setNewToolDesc('');
};
const openAddToolModal = (e: React.MouseEvent, cat: 'system' | 'query') => {
e.stopPropagation();
setAddingToCategory(cat);
setIsAddToolModalOpen(true);
};
// Define tools available
const baseSystemTools: ToolItem[] = [
{ id: 'cam_open', name: '打开相机', icon: <Camera className="w-4 h-4" />, desc: '允许 AI 开启摄像头流', category: 'system' },
{ id: 'cam_close', name: '关闭相机', icon: <CameraOff className="w-4 h-4" />, desc: '允许 AI 停止摄像头流', category: 'system' },
{ id: 'take_photo', name: '拍照', icon: <Image className="w-4 h-4" />, desc: 'AI 触发单张拍摄', category: 'system' },
{ id: 'burst_3', name: '连拍三张', icon: <Images className="w-4 h-4" />, desc: 'AI 触发快速连拍', category: 'system' },
];
const baseQueryTools: ToolItem[] = [
{ id: 'q_weather', name: '天气查询', icon: <CloudSun className="w-4 h-4" />, desc: '查询实时及未来天气', category: 'query' },
{ id: 'q_calendar', name: '日历查询', icon: <Calendar className="w-4 h-4" />, desc: '查询日程及节假日信息', category: 'query' },
{ id: 'q_stock', name: '股价查询', icon: <TrendingUp className="w-4 h-4" />, desc: '查询股票实时行情', category: 'query' },
{ id: 'q_exchange', name: '汇率查询', icon: <Coins className="w-4 h-4" />, desc: '查询多国货币汇率', category: 'query' },
];
const systemTools = [...baseSystemTools, ...customTools.filter(t => t.category === 'system')].filter(t => !hiddenToolIds.includes(t.id));
const queryTools = [...baseQueryTools, ...customTools.filter(t => t.category === 'query')].filter(t => !hiddenToolIds.includes(t.id));
return (
<div className="flex h-[calc(100vh-6rem)] gap-6 animate-in fade-in">
{/* LEFT COLUMN: List */}
<div className="w-80 flex flex-col gap-4 shrink-0">
<div className="flex items-center justify-between px-1">
<h2 className="text-xl font-bold tracking-tight"></h2>
<h2 className="text-xl font-bold tracking-tight text-white"></h2>
</div>
<div className="flex gap-2">
@@ -148,10 +233,10 @@ export const AssistantsPage: React.FC = () => {
<>
{/* Header Area */}
<div className="p-6 border-b border-white/5 bg-white/[0.02] space-y-4">
{/* Row 1: Name and Actions - Aligned with items-end */}
{/* Row 1: Name and Actions */}
<div className="flex items-end justify-between gap-4">
<div className="flex-1">
<label className="text-xs text-muted-foreground font-mono mb-2 block ml-1">ASSISTANT NAME</label>
<label className="text-[10px] text-muted-foreground font-black tracking-widest uppercase mb-2 block ml-1">ASSISTANT NAME</label>
<Input
value={selectedAssistant.name}
onChange={(e) => updateAssistant('name', e.target.value)}
@@ -189,16 +274,22 @@ export const AssistantsPage: React.FC = () => {
>
</button>
<button
onClick={() => setActiveTab(TabValue.TOOLS)}
className={`px-6 py-1.5 text-sm font-medium rounded-md transition-all ${activeTab === TabValue.TOOLS ? 'bg-primary text-primary-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground hover:bg-white/5'}`}
>
</button>
</div>
</div>
{/* Content Scroll Area */}
<div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
<div className="max-w-4xl mx-auto space-y-8 animate-in slide-in-from-bottom-2 duration-300">
{activeTab === TabValue.GLOBAL ? (
{activeTab === TabValue.GLOBAL && (
<div className="space-y-6">
<div className="space-y-2">
<label className="text-sm font-medium text-foreground flex items-center">
<label className="text-sm font-medium text-white flex items-center">
<MessageSquare className="w-4 h-4 mr-2 text-primary"/> (Opener)
</label>
<Input
@@ -211,11 +302,11 @@ export const AssistantsPage: React.FC = () => {
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-foreground flex items-center">
<label className="text-sm font-medium text-white flex items-center">
<BotIcon className="w-4 h-4 mr-2 text-primary"/> (Prompt)
</label>
<textarea
className="flex min-h-[200px] w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 resize-y"
className="flex min-h-[200px] w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 resize-y text-white"
value={selectedAssistant.prompt}
onChange={(e) => updateAssistant('prompt', e.target.value)}
placeholder="设定小助手的人设、语气、行为规范以及业务逻辑..."
@@ -223,7 +314,7 @@ export const AssistantsPage: React.FC = () => {
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-foreground"></label>
<label className="text-sm font-medium text-white"></label>
<select
className="flex h-10 w-full rounded-md border border-white/10 bg-white/5 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 [&>option]:bg-card text-foreground"
value={selectedAssistant.knowledgeBaseId}
@@ -236,11 +327,13 @@ export const AssistantsPage: React.FC = () => {
</select>
</div>
</div>
) : (
)}
{activeTab === TabValue.VOICE && (
<div className="space-y-8">
<div className="grid grid-cols-2 gap-6">
<div className="space-y-2">
<label className="text-sm font-medium text-foreground"> (Language)</label>
<label className="text-sm font-medium text-white"> (Language)</label>
<select
className="flex h-10 w-full rounded-md border border-white/10 bg-white/5 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 [&>option]:bg-card text-foreground"
value={selectedAssistant.language}
@@ -251,7 +344,7 @@ export const AssistantsPage: React.FC = () => {
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-foreground"> (Voice)</label>
<label className="text-sm font-medium text-white"> (Voice)</label>
<select
className="flex h-10 w-full rounded-md border border-white/10 bg-white/5 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 [&>option]:bg-card text-foreground"
value={selectedAssistant.voice}
@@ -270,7 +363,7 @@ export const AssistantsPage: React.FC = () => {
<div className="space-y-4 p-4 rounded-xl border border-white/5 bg-white/[0.02]">
<div className="flex justify-between items-center">
<label className="text-sm font-medium text-foreground"> (Speed)</label>
<label className="text-sm font-medium text-white"> (Speed)</label>
<span className="text-sm font-mono text-primary bg-primary/10 px-2 py-0.5 rounded">{selectedAssistant.speed}x</span>
</div>
<input
@@ -290,7 +383,7 @@ export const AssistantsPage: React.FC = () => {
</div>
<div className="space-y-3">
<label className="text-sm font-medium text-foreground flex items-center">
<label className="text-sm font-medium text-white flex items-center">
<Mic className="w-4 h-4 mr-2 text-primary"/> ASR (Hotwords)
</label>
<div className="flex space-x-2">
@@ -318,6 +411,102 @@ export const AssistantsPage: React.FC = () => {
</div>
</div>
)}
{activeTab === TabValue.TOOLS && (
<div className="space-y-8 animate-in fade-in">
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-[10px] font-black flex items-center text-primary uppercase tracking-[0.2em]">
<Wrench className="w-3.5 h-3.5 mr-2" />
</h3>
<button
onClick={(e) => openAddToolModal(e, 'system')}
className="p-1 rounded-full bg-primary/10 text-primary hover:bg-primary/20 transition-colors shadow-sm"
>
<Plus className="w-3.5 h-3.5" />
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{systemTools.map(tool => (
<div
key={tool.id}
onClick={() => toggleTool(tool.id)}
className={`p-4 rounded-xl border transition-all cursor-pointer group relative flex items-start space-x-3 ${selectedAssistant.tools?.includes(tool.id) ? 'bg-primary/10 border-primary/40 shadow-[0_0_15px_rgba(6,182,212,0.1)]' : 'bg-card/30 border-white/5 hover:bg-white/5 hover:border-white/10'}`}
>
<div className={`p-2 rounded-lg shrink-0 transition-colors ${selectedAssistant.tools?.includes(tool.id) ? 'bg-primary text-primary-foreground' : 'bg-white/5 text-muted-foreground'}`}>
{tool.icon}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between mb-0.5">
<span className="text-sm font-bold text-white">{tool.name}</span>
<div className={`w-4 h-4 rounded-full border-2 flex items-center justify-center transition-all ${selectedAssistant.tools?.includes(tool.id) ? 'border-primary bg-primary' : 'border-white/10'}`}>
{selectedAssistant.tools?.includes(tool.id) && <div className="w-1.5 h-1.5 bg-white rounded-full"></div>}
</div>
</div>
<p className="text-[10px] text-muted-foreground line-clamp-1 opacity-70">{tool.desc}</p>
</div>
{/* Delete Button */}
<button
onClick={(e) => deleteTool(e, tool.id)}
className="absolute -top-1 -right-1 p-0.5 rounded-full bg-destructive text-white opacity-0 group-hover:opacity-100 transition-opacity hover:scale-110 shadow-lg z-10"
title="删除工具"
>
<X className="w-3 h-3" />
</button>
</div>
))}
</div>
</div>
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-[10px] font-black flex items-center text-blue-400 uppercase tracking-[0.2em]">
<TrendingUp className="w-3.5 h-3.5 mr-2" />
</h3>
<button
onClick={(e) => openAddToolModal(e, 'query')}
className="p-1 rounded-full bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 transition-colors shadow-sm"
>
<Plus className="w-3.5 h-3.5" />
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{queryTools.map(tool => (
<div
key={tool.id}
onClick={() => toggleTool(tool.id)}
className={`p-4 rounded-xl border transition-all cursor-pointer group relative flex items-start space-x-3 ${selectedAssistant.tools?.includes(tool.id) ? 'bg-blue-500/10 border-blue-500/40 shadow-[0_0_15px_rgba(59,130,246,0.1)]' : 'bg-card/30 border-white/5 hover:bg-white/5 hover:border-white/10'}`}
>
<div className={`p-2 rounded-lg shrink-0 transition-colors ${selectedAssistant.tools?.includes(tool.id) ? 'bg-blue-500 text-white' : 'bg-white/5 text-muted-foreground'}`}>
{tool.icon}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between mb-0.5">
<span className="text-sm font-bold text-white">{tool.name}</span>
<div className={`w-4 h-4 rounded-full border-2 flex items-center justify-center transition-all ${selectedAssistant.tools?.includes(tool.id) ? 'border-blue-500 bg-blue-500' : 'border-white/10'}`}>
{selectedAssistant.tools?.includes(tool.id) && <div className="w-1.5 h-1.5 bg-white rounded-full"></div>}
</div>
</div>
<p className="text-[10px] text-muted-foreground line-clamp-1 opacity-70">{tool.desc}</p>
</div>
{/* Delete Button */}
<button
onClick={(e) => deleteTool(e, tool.id)}
className="absolute -top-1 -right-1 p-0.5 rounded-full bg-destructive text-white opacity-0 group-hover:opacity-100 transition-opacity hover:scale-110 shadow-lg z-10"
title="删除工具"
>
<X className="w-3 h-3" />
</button>
</div>
))}
</div>
</div>
<div className="p-4 bg-white/5 border border-white/5 rounded-xl text-[10px] text-muted-foreground flex items-center gap-3">
<Rocket className="w-4 h-4 text-primary shrink-0" />
<span>AI </span>
</div>
</div>
)}
</div>
</div>
</>
@@ -340,6 +529,44 @@ export const AssistantsPage: React.FC = () => {
/>
)}
{/* Add Custom Tool Modal */}
<Dialog
isOpen={isAddToolModalOpen}
onClose={() => setIsAddToolModalOpen(false)}
title={addingToCategory === 'system' ? '添加自定义系统指令' : '添加自定义信息查询'}
footer={
<>
<Button variant="ghost" onClick={() => setIsAddToolModalOpen(false)}></Button>
<Button onClick={handleAddCustomTool}></Button>
</>
}
>
<div className="space-y-4">
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"></label>
<Input
value={newToolName}
onChange={e => setNewToolName(e.target.value)}
placeholder="例如: 智能家居控制"
autoFocus
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"> ( AI )</label>
<textarea
className="flex min-h-[100px] w-full rounded-md border border-white/10 bg-white/5 px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 text-white"
value={newToolDesc}
onChange={e => setNewToolDesc(e.target.value)}
placeholder="描述该工具的功能,以及 AI 应该在什么情况下调用它..."
/>
</div>
<div className="p-3 bg-primary/5 border border-primary/20 rounded-lg text-[10px] text-muted-foreground flex items-start gap-2">
<Wrench className="w-3.5 h-3.5 text-primary shrink-0 mt-0.5" />
<p> AI these </p>
</div>
</div>
</Dialog>
{/* Delete Confirmation Dialog */}
<Dialog
isOpen={!!deleteId}
@@ -357,7 +584,7 @@ export const AssistantsPage: React.FC = () => {
<AlertTriangle className="h-6 w-6 text-destructive" />
</div>
<div>
<p className="text-sm text-foreground">
<p className="text-sm text-foreground text-white">
</p>
{deleteId && (
@@ -385,12 +612,12 @@ const BotIcon = ({className}: {className?: string}) => (
);
// --- Debug Drawer Component ---
const DebugDrawer: React.FC<{ isOpen: boolean; onClose: () => void; assistant: Assistant }> = ({ isOpen, onClose, assistant }) => {
export const DebugDrawer: React.FC<{ isOpen: boolean; onClose: () => void; assistant: Assistant }> = ({ isOpen, onClose, assistant }) => {
const [mode, setMode] = useState<'text' | 'voice' | 'video'>('text');
const [messages, setMessages] = useState<{role: 'user' | 'model', text: string}[]>([]);
const [inputText, setInputText] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [callStatus, setCallStatus] = useState<'idle' | 'calling' | 'active'>('idle');
// Media State
const videoRef = useRef<HTMLVideoElement>(null);
@@ -400,19 +627,24 @@ const DebugDrawer: React.FC<{ isOpen: boolean; onClose: () => void; assistant: A
const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
const [selectedCamera, setSelectedCamera] = useState<string>('');
const [selectedMic, setSelectedMic] = useState<string>('');
const [isSwapped, setIsSwapped] = useState(false); // False: AI is Big, Local is Small. True: Local is Big, AI is Small.
const [isSwapped, setIsSwapped] = useState(false);
// Initialize with opener
// Initialize
useEffect(() => {
if (isOpen) {
setMessages([{ role: 'model', text: assistant.opener || "Hello!" }]);
if (mode === 'text') {
setMessages([{ role: 'model', text: assistant.opener || "Hello!" }]);
} else {
setMessages([]);
setCallStatus('idle');
}
} else {
// Reset and stop media when closed
setMode('text');
stopMedia();
setIsSwapped(false);
setCallStatus('idle');
}
}, [isOpen, assistant]);
}, [isOpen, assistant, mode]);
// Auto-scroll logic
useEffect(() => {
@@ -429,13 +661,10 @@ const DebugDrawer: React.FC<{ isOpen: boolean; onClose: () => void; assistant: A
await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
const dev = await navigator.mediaDevices.enumerateDevices();
setDevices(dev);
const cams = dev.filter(d => d.kind === 'videoinput');
const mics = dev.filter(d => d.kind === 'audioinput');
if (cams.length > 0 && !selectedCamera) setSelectedCamera(cams[0].deviceId);
if (mics.length > 0 && !selectedMic) setSelectedMic(mics[0].deviceId);
} catch (e) {
console.error("Error enumerating devices", e);
}
@@ -444,7 +673,6 @@ const DebugDrawer: React.FC<{ isOpen: boolean; onClose: () => void; assistant: A
}
}, [isOpen, mode]);
// Handle Video/Media stream
const stopMedia = () => {
if (streamRef.current) {
streamRef.current.getTracks().forEach(track => track.stop());
@@ -454,7 +682,7 @@ const DebugDrawer: React.FC<{ isOpen: boolean; onClose: () => void; assistant: A
useEffect(() => {
const handleStream = async () => {
if (isOpen && mode === 'video') {
if (isOpen && mode === 'video' && callStatus === 'active') {
try {
stopMedia();
const constraints = {
@@ -469,14 +697,28 @@ const DebugDrawer: React.FC<{ isOpen: boolean; onClose: () => void; assistant: A
} catch (err) {
console.error("Failed to access camera/mic:", err);
}
} else {
} else if (callStatus !== 'active') {
stopMedia();
}
};
handleStream();
return () => stopMedia();
}, [mode, isOpen, selectedCamera, selectedMic]);
}, [mode, isOpen, selectedCamera, selectedMic, callStatus]);
const handleCall = () => {
setCallStatus('calling');
setTimeout(() => {
setCallStatus('active');
setMessages([{ role: 'model', text: assistant.opener || "Hello!" }]);
}, 1500);
};
const handleHangup = () => {
stopMedia();
setCallStatus('idle');
setMessages([]);
};
const handleSend = async () => {
if (!inputText.trim()) return;
@@ -509,12 +751,6 @@ const DebugDrawer: React.FC<{ isOpen: boolean; onClose: () => void; assistant: A
}
};
const handleClose = () => {
stopMedia();
onClose();
};
// Reusable Messages List Component
const TranscriptionLog = () => (
<div ref={scrollRef} className="flex-1 overflow-y-auto space-y-4 p-2 border border-white/5 rounded-md bg-black/20 min-h-0">
{messages.length === 0 && <div className="text-center text-muted-foreground text-xs py-4"></div>}
@@ -530,171 +766,113 @@ const DebugDrawer: React.FC<{ isOpen: boolean; onClose: () => void; assistant: A
</div>
);
// Helper to render the Local Video Element
const renderLocalVideo = (isSmall: boolean) => (
<div className={`relative w-full h-full bg-black overflow-hidden ${isSmall ? 'rounded-lg border border-white/20 shadow-lg' : ''}`}>
<video
ref={videoRef}
autoPlay
muted
playsInline
className="w-full h-full object-cover transform scale-x-[-1]"
/>
<div className="absolute top-2 left-2 bg-black/50 px-2 py-0.5 rounded text-[10px] text-white/80">
Me
</div>
<video ref={videoRef} autoPlay muted playsInline className="w-full h-full object-cover transform scale-x-[-1]" />
<div className="absolute top-2 left-2 bg-black/50 px-2 py-0.5 rounded text-[10px] text-white/80">Me</div>
</div>
);
// Helper to render the "Remote" AI Video Element (Simulated)
const renderRemoteVideo = (isSmall: boolean) => (
<div className={`relative w-full h-full bg-slate-900 overflow-hidden flex flex-col items-center justify-center ${isSmall ? 'rounded-lg border border-white/20 shadow-lg' : ''}`}>
<div className="relative flex items-center justify-center">
<div className={`rounded-full bg-primary/20 animate-pulse ${isSmall ? 'w-16 h-16' : 'w-32 h-32'}`}></div>
<div className={`absolute rounded-full bg-primary/40 animate-ping ${isSmall ? 'w-12 h-12' : 'w-24 h-24'}`}></div>
<div className={`absolute rounded-full bg-primary flex items-center justify-center shadow-[0_0_30px_hsl(var(--primary))] ${isSmall ? 'w-12 h-12' : 'w-24 h-24'}`}>
<Video className={`${isSmall ? 'w-6 h-6' : 'w-10 h-10'} text-primary-foreground`} />
</div>
</div>
{!isSmall && (
<div className="mt-4 font-mono text-primary animate-pulse text-sm">
{assistant.name}
</div>
)}
{!isSmall && <div className="mt-4 font-mono text-primary animate-pulse text-sm">{assistant.name}</div>}
</div>
);
return (
<Drawer isOpen={isOpen} onClose={handleClose} title={`调试: ${assistant.name}`}>
<Drawer isOpen={isOpen} onClose={() => { handleHangup(); onClose(); }} title={`调试: ${assistant.name}`}>
<div className="flex flex-col h-full">
{/* Mode Toggle */}
<div className="flex justify-center mb-4 bg-white/5 p-1 rounded-lg shrink-0">
<button
className={`flex-1 py-1 text-sm rounded-md transition-all ${mode === 'text' ? 'bg-primary text-primary-foreground shadow' : 'text-muted-foreground hover:bg-white/5'}`}
onClick={() => setMode('text')}
>
<MessageSquare className="inline w-4 h-4 mr-1"/>
</button>
<button
className={`flex-1 py-1 text-sm rounded-md transition-all ${mode === 'voice' ? 'bg-primary text-primary-foreground shadow' : 'text-muted-foreground hover:bg-white/5'}`}
onClick={() => setMode('voice')}
>
<Mic className="inline w-4 h-4 mr-1"/>
</button>
<button
className={`flex-1 py-1 text-sm rounded-md transition-all ${mode === 'video' ? 'bg-primary text-primary-foreground shadow' : 'text-muted-foreground hover:bg-white/5'}`}
onClick={() => setMode('video')}
>
<Video className="inline w-4 h-4 mr-1"/>
</button>
{(['text', 'voice', 'video'] as const).map(m => (
<button key={m} className={`flex-1 py-1 text-sm rounded-md transition-all ${mode === m ? 'bg-primary text-primary-foreground shadow' : 'text-muted-foreground hover:bg-white/5'}`} onClick={() => setMode(m)}>
{m === 'text' && <MessageSquare className="inline w-4 h-4 mr-1"/>}
{m === 'voice' && <Mic className="inline w-4 h-4 mr-1"/>}
{m === 'video' && <Video className="inline w-4 h-4 mr-1"/>}
{m === 'text' ? '文本' : m === 'voice' ? '语音' : '视频'}
</button>
))}
</div>
{/* Content Area */}
<div className="flex-1 overflow-hidden flex flex-col min-h-0 mb-4 gap-2">
{mode === 'text' && <TranscriptionLog />}
{mode === 'voice' && (
<div className="flex flex-col h-full">
{/* Visualizer Area */}
<div className="h-1/3 min-h-[150px] shrink-0 border border-white/5 rounded-md bg-black/20 flex flex-col items-center justify-center text-muted-foreground space-y-4 mb-2 relative overflow-hidden">
<div className="absolute inset-0 bg-gradient-to-b from-transparent to-black/20 pointer-events-none"></div>
<div className="h-24 w-24 rounded-full bg-primary/10 flex items-center justify-center animate-pulse relative z-10">
<Mic className="h-10 w-10 text-primary" />
</div>
<p className="text-sm relative z-10">...</p>
</div>
{/* Transcript */}
<h4 className="text-xs font-medium text-muted-foreground px-1"> / Live Transcription</h4>
<TranscriptionLog />
</div>
)}
{mode === 'video' && (
<div className="flex flex-col h-full space-y-2">
{/* Video Area (Top) */}
<div className="h-3/5 shrink-0 flex flex-col gap-2">
{/* Device Settings Bar */}
<div className="flex gap-2 shrink-0">
<div className="flex-1">
<select
className="w-full text-xs bg-white/5 border border-white/10 rounded px-2 py-1.5 focus:outline-none focus:border-primary/50 text-foreground"
value={selectedCamera}
onChange={(e) => setSelectedCamera(e.target.value)}
>
{devices.filter(d => d.kind === 'videoinput').map(d => (
<option key={d.deviceId} value={d.deviceId}>{d.label || `Camera...`}</option>
))}
</select>
</div>
<div className="flex-1">
<select
className="w-full text-xs bg-white/5 border border-white/10 rounded px-2 py-1.5 focus:outline-none focus:border-primary/50 text-foreground"
value={selectedMic}
onChange={(e) => setSelectedMic(e.target.value)}
>
{devices.filter(d => d.kind === 'audioinput').map(d => (
<option key={d.deviceId} value={d.deviceId}>{d.label || `Mic...`}</option>
))}
</select>
</div>
</div>
{/* Video Container (PiP) */}
<div className="flex-1 relative rounded-lg overflow-hidden border border-white/10 bg-black min-h-0">
{/* Main Window */}
<div className="absolute inset-0">
{isSwapped ? renderLocalVideo(false) : renderRemoteVideo(false)}
</div>
{/* Small Window */}
<div className="absolute bottom-2 right-2 w-24 h-36 z-10 transition-all duration-300">
{isSwapped ? renderRemoteVideo(true) : renderLocalVideo(true)}
</div>
{/* Swap Button */}
<div className="absolute top-2 right-2 z-20">
<Button
variant="secondary"
size="icon"
className="rounded-full h-7 w-7 bg-black/50 hover:bg-primary/80 backdrop-blur text-white border border-white/20"
onClick={() => setIsSwapped(!isSwapped)}
title="切换窗口"
>
<ArrowLeftRight className="h-3 w-3" />
</Button>
</div>
<div className="flex-1 overflow-hidden flex flex-col min-h-0 mb-4">
{mode === 'text' ? (
<TranscriptionLog />
) : callStatus === 'idle' ? (
<div className="flex-1 flex flex-col items-center justify-center space-y-6 border border-white/5 rounded-xl bg-black/20 animate-in fade-in zoom-in-95">
<div className="relative">
<div className="absolute inset-0 bg-primary/20 rounded-full blur-2xl animate-pulse"></div>
<div className="relative h-24 w-24 rounded-full bg-white/5 border border-white/10 flex items-center justify-center">
{mode === 'voice' ? <Mic className="h-10 w-10 text-muted-foreground" /> : <Video className="h-10 w-10 text-muted-foreground" />}
</div>
</div>
{/* Transcript Area (Bottom) */}
<div className="flex-1 flex flex-col min-h-0">
<h4 className="text-xs font-medium text-muted-foreground px-1 mb-1"> / Live Transcription</h4>
<TranscriptionLog />
<div className="text-center">
<h3 className="text-lg font-bold text-white mb-1"></h3>
<p className="text-xs text-muted-foreground"></p>
</div>
</div>
)}
</div>
{/* Footer Actions - Unified Input */}
<div className="shrink-0 space-y-2">
{(mode === 'voice' || mode === 'video') && (
<div className="flex justify-end">
<Button variant="destructive" size="sm" className="w-full shadow-red-500/20 shadow-lg" onClick={handleClose}>
<PhoneOff className="mr-2 h-3 w-3" />
</Button>
</div>
)}
<div className="flex space-x-2">
<Input
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder={mode === 'text' ? "输入消息..." : "输入文字模拟语音/Input to simulate speech..."}
onKeyDown={(e) => e.key === 'Enter' && handleSend()}
disabled={isLoading}
className="flex-1"
/>
<Button size="icon" onClick={handleSend} disabled={isLoading}>
<Send className="h-4 w-4" />
<Button onClick={handleCall} className="w-48 h-12 rounded-full bg-green-500 hover:bg-green-600 shadow-[0_0_20px_rgba(34,197,94,0.4)] text-base font-bold">
<PhoneCall className="mr-2 h-5 w-5" />
</Button>
</div>
) : callStatus === 'calling' ? (
<div className="flex-1 flex flex-col items-center justify-center space-y-6">
<div className="h-24 w-24 rounded-full bg-primary/20 flex items-center justify-center animate-bounce">
<PhoneCall className="h-10 w-10 text-primary" />
</div>
<div className="text-center">
<p className="text-primary font-mono text-sm tracking-widest animate-pulse">CALLING...</p>
<p className="text-xs text-muted-foreground mt-2"> AI </p>
</div>
<Button onClick={handleHangup} variant="destructive" className="rounded-full h-10 px-8"></Button>
</div>
) : (
<div className="flex-1 flex flex-col min-h-0 space-y-2">
{mode === 'voice' ? (
<div className="flex flex-col h-full animate-in fade-in">
<div className="h-1/3 min-h-[150px] shrink-0 border border-white/5 rounded-md bg-black/20 flex flex-col items-center justify-center text-muted-foreground space-y-4 mb-2 relative overflow-hidden">
<div className="h-24 w-24 rounded-full bg-primary/10 flex items-center justify-center animate-pulse relative z-10">
<Mic className="h-10 w-10 text-primary" />
</div>
<p className="text-sm relative z-10">...</p>
</div>
<h4 className="text-xs font-medium text-muted-foreground px-1 mb-1 uppercase tracking-tight"></h4>
<TranscriptionLog />
</div>
) : (
<div className="flex flex-col h-full space-y-2 animate-in fade-in">
<div className="h-3/5 shrink-0 flex flex-col gap-2">
<div className="flex gap-2 shrink-0">
<select className="flex-1 text-xs bg-white/5 border border-white/10 rounded px-2 py-1 text-foreground" value={selectedCamera} onChange={e => setSelectedCamera(e.target.value)}>
{devices.filter(d => d.kind === 'videoinput').map(d => <option key={d.deviceId} value={d.deviceId}>{d.label || 'Camera'}</option>)}
</select>
<select className="flex-1 text-xs bg-white/5 border border-white/10 rounded px-2 py-1 text-foreground" value={selectedMic} onChange={e => setSelectedMic(e.target.value)}>
{devices.filter(d => d.kind === 'audioinput').map(d => <option key={d.deviceId} value={d.deviceId}>{d.label || 'Mic'}</option>)}
</select>
</div>
<div className="flex-1 relative rounded-lg overflow-hidden border border-white/10 bg-black min-h-0">
<div className="absolute inset-0">{isSwapped ? renderLocalVideo(false) : renderRemoteVideo(false)}</div>
<div className="absolute bottom-2 right-2 w-24 h-36 z-10">{isSwapped ? renderRemoteVideo(true) : renderLocalVideo(true)}</div>
<button className="absolute top-2 right-2 z-20 h-8 w-8 rounded-full bg-black/50 backdrop-blur flex items-center justify-center text-white border border-white/10 hover:bg-primary/80" onClick={() => setIsSwapped(!isSwapped)}><ArrowLeftRight className="h-3.5 w-3.5" /></button>
</div>
</div>
<TranscriptionLog />
</div>
)}
<Button variant="destructive" size="sm" className="w-full h-10 font-bold" onClick={handleHangup}>
<PhoneOff className="mr-2 h-4 w-4" />
</Button>
</div>
)}
</div>
<div className="shrink-0 space-y-2">
<div className="flex space-x-2">
<Input value={inputText} onChange={e => setInputText(e.target.value)} placeholder={mode === 'text' ? "输入消息..." : "输入文本模拟交互..."} onKeyDown={e => e.key === 'Enter' && handleSend()} disabled={isLoading || (mode !== 'text' && callStatus !== 'active')} className="flex-1" />
<Button size="icon" onClick={handleSend} disabled={isLoading || (mode !== 'text' && callStatus !== 'active')}><Send className="h-4 w-4" /></Button>
</div>
</div>
</div>

326
pages/AutoTest.tsx Normal file
View File

@@ -0,0 +1,326 @@
import React, { useState } from 'react';
import { Plus, Search, Play, Copy, Trash2, Zap, MessageSquare, Mic, AlertTriangle, ListFilter, Braces, Rocket } from 'lucide-react';
import { Button, Input, Card, Badge, Dialog } from '../components/UI';
import { mockAutoTestAssistants, mockAssistants } from '../services/mockData';
import { AutoTestAssistant, TestType, TestMethod } from '../types';
export const AutoTestPage: React.FC = () => {
const [testAssistants, setTestAssistants] = useState<AutoTestAssistant[]>(mockAutoTestAssistants);
const [searchTerm, setSearchTerm] = useState('');
const [selectedId, setSelectedId] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const selectedTestAssistant = testAssistants.find(a => a.id === selectedId) || null;
const filteredTests = testAssistants.filter(a =>
a.name.toLowerCase().includes(searchTerm.toLowerCase())
);
const handleCreate = () => {
const newId = `at_${Date.now()}`;
const newAssistant: AutoTestAssistant = {
id: newId,
name: '新测试助手',
type: TestType.INTELLIGENT,
method: TestMethod.TEXT,
targetAssistantId: mockAssistants[0]?.id || '',
fixedWorkflowSteps: [],
intelligentPrompt: '你是一个普通的测试用户,试图了解产品信息。',
createdAt: new Date().toISOString().replace('T', ' ').substring(0, 16)
};
setTestAssistants([...testAssistants, newAssistant]);
setSelectedId(newId);
};
const handleCopy = (e: React.MouseEvent, assistant: AutoTestAssistant) => {
e.stopPropagation();
const newAssistant = { ...assistant, id: `at_${Date.now()}`, name: `${assistant.name} (Copy)` };
setTestAssistants([...testAssistants, newAssistant]);
};
const handleDeleteClick = (e: React.MouseEvent, id: string) => {
e.stopPropagation();
setDeleteId(id);
};
const confirmDelete = () => {
if (deleteId) {
setTestAssistants(prev => prev.filter(a => a.id !== deleteId));
if (selectedId === deleteId) setSelectedId(null);
setDeleteId(null);
}
};
const updateAssistant = (field: keyof AutoTestAssistant, value: any) => {
if (!selectedId) return;
setTestAssistants(prev => prev.map(a => a.id === selectedId ? { ...a, [field]: value } : a));
};
const handleAddStep = () => {
if (selectedTestAssistant) {
updateAssistant('fixedWorkflowSteps', [...selectedTestAssistant.fixedWorkflowSteps, '']);
}
};
const updateStep = (idx: number, val: string) => {
if (selectedTestAssistant) {
const newSteps = [...selectedTestAssistant.fixedWorkflowSteps];
newSteps[idx] = val;
updateAssistant('fixedWorkflowSteps', newSteps);
}
};
const removeStep = (idx: number) => {
if (selectedTestAssistant) {
updateAssistant('fixedWorkflowSteps', selectedTestAssistant.fixedWorkflowSteps.filter((_, i) => i !== idx));
}
};
return (
<div className="flex h-[calc(100vh-6rem)] gap-6 animate-in fade-in">
{/* LEFT COLUMN: Test Assistants List */}
<div className="w-80 flex flex-col gap-4 shrink-0">
<div className="flex items-center justify-between px-1">
<h2 className="text-xl font-bold tracking-tight"></h2>
</div>
<div className="flex gap-2">
<div className="relative flex-1">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="搜索测试助手..."
className="pl-9 bg-card/50 border-white/5"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<Button size="icon" onClick={handleCreate} title="新建测试助手">
<Plus className="h-5 w-5" />
</Button>
</div>
<div className="flex-1 overflow-y-auto space-y-2 pr-1 custom-scrollbar">
{filteredTests.map(test => (
<div
key={test.id}
onClick={() => setSelectedId(test.id)}
className={`group relative flex flex-col p-4 rounded-xl border transition-all cursor-pointer ${
selectedId === test.id
? 'bg-primary/10 border-primary/40 shadow-[0_0_15px_rgba(6,182,212,0.15)]'
: 'bg-card/30 border-white/5 hover:bg-white/5 hover:border-white/10'
}`}
>
<div className="flex justify-between items-start mb-2">
<span className={`font-semibold truncate pr-6 ${selectedId === test.id ? 'text-primary' : 'text-foreground'}`}>
{test.name}
</span>
</div>
<div className="flex items-center space-x-3 text-[10px] text-muted-foreground font-mono uppercase">
<Badge variant="outline" className="text-[9px] py-0 px-1.5 opacity-70">
{test.type === TestType.FIXED ? '固定流程' : '智能测试'}
</Badge>
<div className="flex items-center">
{test.method === TestMethod.TEXT ? <MessageSquare className="h-2.5 w-2.5 mr-1" /> : <Mic className="h-2.5 w-2.5 mr-1" />}
{test.method === TestMethod.TEXT ? '文本' : '音频'}
</div>
</div>
{/* Hover Actions */}
<div className="absolute right-2 top-2 flex space-x-1 opacity-0 group-hover:opacity-100 transition-opacity bg-background/50 backdrop-blur-sm rounded-lg p-0.5">
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={(e) => handleCopy(e, test)} title="复制">
<Copy className="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive hover:text-destructive" onClick={(e) => handleDeleteClick(e, test.id)} title="删除">
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</div>
))}
{filteredTests.length === 0 && (
<div className="text-center py-10 text-muted-foreground text-sm font-mono opacity-50">
[ NO TESTERS FOUND ]
</div>
)}
</div>
</div>
{/* RIGHT COLUMN: Config Panel */}
<div className="flex-1 bg-card/20 backdrop-blur-sm border border-white/5 rounded-2xl overflow-hidden flex flex-col relative shadow-xl">
{selectedTestAssistant ? (
<>
{/* Header Area */}
<div className="p-6 border-b border-white/5 bg-white/[0.02] space-y-4">
<div className="flex items-end justify-between gap-4">
<div className="flex-1">
<label className="text-[10px] text-muted-foreground font-black uppercase tracking-widest mb-2 block ml-1">TESTER NAME</label>
<Input
value={selectedTestAssistant.name}
onChange={(e) => updateAssistant('name', e.target.value)}
className="font-bold bg-white/5 border-white/10 focus:border-primary/50 text-base"
/>
</div>
<Button
onClick={() => alert("开始自动化测试...")}
className="shadow-[0_0_20px_rgba(34,197,94,0.3)] bg-green-500 hover:bg-green-600 text-white font-bold"
>
<Rocket className="mr-2 h-4 w-4" />
</Button>
</div>
</div>
{/* Scroll Area */}
<div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
<div className="max-w-4xl mx-auto space-y-8 animate-in slide-in-from-bottom-2 duration-300">
{/* Basic Config Grid */}
<div className="grid grid-cols-2 gap-8">
<div className="space-y-3">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-[0.2em] flex items-center">
<Zap className="h-3 w-3 mr-2 text-primary" />
</label>
<div className="flex p-1 bg-white/5 rounded-lg">
<button
onClick={() => updateAssistant('type', TestType.FIXED)}
className={`flex-1 py-1.5 text-xs font-bold rounded-md transition-all ${selectedTestAssistant.type === TestType.FIXED ? 'bg-primary text-primary-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground hover:bg-white/5'}`}
>
</button>
<button
onClick={() => updateAssistant('type', TestType.INTELLIGENT)}
className={`flex-1 py-1.5 text-xs font-bold rounded-md transition-all ${selectedTestAssistant.type === TestType.INTELLIGENT ? 'bg-primary text-primary-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground hover:bg-white/5'}`}
>
</button>
</div>
</div>
<div className="space-y-3">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-[0.2em] flex items-center">
<ListFilter className="h-3 w-3 mr-2 text-primary" />
</label>
<div className="flex p-1 bg-white/5 rounded-lg">
<button
onClick={() => updateAssistant('method', TestMethod.TEXT)}
className={`flex-1 py-1.5 text-xs font-bold rounded-md transition-all ${selectedTestAssistant.method === TestMethod.TEXT ? 'bg-primary text-primary-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground hover:bg-white/5'}`}
>
</button>
<button
onClick={() => updateAssistant('method', TestMethod.AUDIO)}
className={`flex-1 py-1.5 text-xs font-bold rounded-md transition-all ${selectedTestAssistant.method === TestMethod.AUDIO ? 'bg-primary text-primary-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground hover:bg-white/5'}`}
>
</button>
</div>
</div>
</div>
<div className="space-y-3">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-[0.2em]"> (TARGET ASSISTANT)</label>
<select
className="flex h-10 w-full rounded-lg border border-white/10 bg-white/5 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 [&>option]:bg-card text-foreground"
value={selectedTestAssistant.targetAssistantId}
onChange={(e) => updateAssistant('targetAssistantId', e.target.value)}
>
{mockAssistants.map(a => (
<option key={a.id} value={a.id}>{a.name}</option>
))}
</select>
</div>
{/* Conditional Settings */}
<div className="pt-6 border-t border-white/5">
{selectedTestAssistant.type === TestType.FIXED ? (
<div className="space-y-4 animate-in fade-in duration-300">
<div className="flex items-center justify-between">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-[0.2em] flex items-center">
<Braces className="h-3 w-3 mr-2 text-primary" /> (Steps)
</label>
<Button variant="outline" size="sm" onClick={handleAddStep} className="h-7 text-[10px]">
<Plus className="w-3 h-3 mr-1" />
</Button>
</div>
<div className="space-y-3">
{selectedTestAssistant.fixedWorkflowSteps.map((step, idx) => (
<div key={idx} className="flex items-center gap-3 group">
<div className="flex items-center justify-center w-6 h-6 rounded bg-primary/20 text-[10px] font-mono text-primary font-bold shrink-0">
{idx + 1}
</div>
<Input
value={step}
onChange={(e) => updateStep(idx, e.target.value)}
placeholder={`步骤 ${idx + 1} 的测试输入...`}
className="bg-white/5"
/>
<Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100" onClick={() => removeStep(idx)}>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
))}
{selectedTestAssistant.fixedWorkflowSteps.length === 0 && (
<div className="text-center py-8 border border-dashed border-white/5 rounded-xl text-xs text-muted-foreground">
</div>
)}
</div>
</div>
) : (
<div className="space-y-4 animate-in fade-in duration-300">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-[0.2em] flex items-center">
<Zap className="h-3 w-3 mr-2 text-primary" /> (System Prompt)
</label>
<textarea
className="flex min-h-[250px] w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 resize-y"
value={selectedTestAssistant.intelligentPrompt}
onChange={(e) => updateAssistant('intelligentPrompt', e.target.value)}
placeholder="在此设定测试助手的身份、测试目标和预期行为..."
/>
<p className="text-[10px] text-muted-foreground leading-relaxed opacity-60">
Prompt
</p>
</div>
)}
</div>
</div>
</div>
</>
) : (
<div className="flex-1 flex flex-col items-center justify-center text-muted-foreground">
<div className="w-16 h-16 rounded-2xl bg-white/5 flex items-center justify-center mb-4">
<Zap className="h-8 w-8 opacity-50" />
</div>
<p className="text-lg font-medium"></p>
<p className="text-sm opacity-60"></p>
</div>
)}
</div>
{/* Delete Confirmation Dialog */}
<Dialog
isOpen={!!deleteId}
onClose={() => setDeleteId(null)}
title="确认删除"
footer={
<>
<Button variant="ghost" onClick={() => setDeleteId(null)}></Button>
<Button variant="destructive" onClick={confirmDelete}></Button>
</>
}
>
<div className="flex items-center space-x-4">
<div className="p-3 bg-destructive/10 rounded-full">
<AlertTriangle className="h-6 w-6 text-destructive" />
</div>
<div>
<p className="text-sm text-foreground">
</p>
</div>
</div>
</Dialog>
</div>
);
};

View File

@@ -1,5 +1,6 @@
import React, { useState, useMemo } from 'react';
import { Phone, CheckCircle, Clock, UserCheck, Activity, Filter } from 'lucide-react';
import { Phone, CheckCircle, Clock, UserCheck, Activity, Filter, ChevronDown, BarChart3, HelpCircle, Mail } from 'lucide-react';
import { Card, Button } from '../components/UI';
import { mockAssistants, getDashboardStats } from '../services/mockData';
@@ -12,84 +13,133 @@ export const DashboardPage: React.FC = () => {
}, [timeRange, selectedAssistantId]);
return (
<div className="space-y-6 animate-in fade-in">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<h1 className="text-2xl font-bold tracking-tight text-foreground"></h1>
<div className="min-h-full flex flex-col justify-center animate-in fade-in py-1">
<div className="w-full max-w-5xl mx-auto space-y-4 px-2">
{/* Filters */}
<div className="flex flex-col sm:flex-row items-center gap-3 bg-card/40 backdrop-blur-md p-2 rounded-lg border border-border/50">
<div className="flex items-center px-2">
<Filter className="h-4 w-4 text-primary mr-2" />
<select
className="bg-transparent text-sm font-medium focus:outline-none text-foreground [&>option]:bg-background"
value={selectedAssistantId}
onChange={(e) => setSelectedAssistantId(e.target.value)}
>
<option value="all"></option>
{mockAssistants.map(a => (
<option key={a.id} value={a.id}>{a.name}</option>
))}
</select>
{/* 1. Utility Row (Top Navigation Actions) */}
<div className="flex justify-end items-center gap-2 border-b border-white/[0.03] pb-2">
<Button variant="ghost" size="sm" className="h-7 px-2.5 text-[10px] font-bold border border-white/5 hover:bg-primary/10 hover:text-primary transition-all">
<HelpCircle className="w-3 h-3 mr-1.5 opacity-70" />
</Button>
<Button variant="ghost" size="sm" className="h-7 px-2.5 text-[10px] font-bold border border-white/5 hover:bg-primary/10 hover:text-primary transition-all">
<Mail className="w-3 h-3 mr-1.5 opacity-70" />
</Button>
</div>
{/* 2. Welcome Row */}
<div className="flex flex-col space-y-0.5 text-center md:text-left pt-1">
<h1 className="text-2xl font-bold tracking-tight text-white">
, <span className="text-primary">Admin User</span>
</h1>
<p className="text-muted-foreground flex items-center justify-center md:justify-start text-[11px]">
<span className="flex items-center ml-2 text-green-400 text-[10px] font-mono bg-green-400/10 px-1.5 py-0.5 rounded-full border border-green-400/20">
<span className="w-1 h-1 rounded-full bg-green-400 animate-pulse mr-1"></span>
HEALTHY
</span>
</p>
</div>
{/* 3. Section Header: Title + Filters aligned perfectly */}
<div className="flex flex-col md:flex-row items-center justify-between border-b border-white/5 pb-3 pt-1 gap-3">
<div className="flex items-center space-x-2.5">
<div className="p-1 bg-primary/10 rounded-lg">
<BarChart3 className="h-3.5 w-3.5 text-primary" />
</div>
<div className="flex flex-col">
<h2 className="text-sm font-bold text-white tracking-wide leading-none"></h2>
<span className="text-[8px] font-mono text-muted-foreground uppercase tracking-[0.2em] opacity-40 mt-1">Metrics Overview</span>
</div>
</div>
<div className="h-4 w-px bg-border/50 hidden sm:block"></div>
<div className="flex bg-muted/50 rounded-md p-1">
{(['week', 'month', 'year'] as const).map((r) => (
<button
key={r}
onClick={() => setTimeRange(r)}
className={`px-3 py-1 text-xs font-medium rounded-sm transition-all ${timeRange === r ? 'bg-primary text-primary-foreground shadow-[0_0_10px_rgba(6,182,212,0.3)]' : 'text-muted-foreground hover:text-foreground hover:bg-white/5'}`}
>
{r === 'week' ? '近一周' : r === 'month' ? '近一个月' : '近一年'}
</button>
))}
{/* Filters Group (Aligned Right) */}
<div className="flex items-center gap-1.5 bg-black/20 p-0.5 rounded-lg border border-white/5 shadow-inner scale-95 origin-right">
{/* Assistant Selector */}
<div className="relative group min-w-[130px]">
<div className="absolute left-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-muted-foreground group-focus-within:text-primary transition-colors">
<Filter className="h-2.5 w-2.5" />
</div>
<select
className="w-full bg-transparent border-0 rounded-lg pl-7 pr-6 py-1 text-[10px] font-bold focus:outline-none appearance-none cursor-pointer transition-all text-white/80"
value={selectedAssistantId}
onChange={(e) => setSelectedAssistantId(e.target.value)}
>
<option value="all" className="bg-background"></option>
{mockAssistants.map(a => (
<option key={a.id} value={a.id} className="bg-background">{a.name}</option>
))}
</select>
<ChevronDown className="absolute right-1.5 top-1/2 -translate-y-1/2 h-2.5 w-2.5 text-muted-foreground pointer-events-none" />
</div>
<div className="h-3 w-px bg-white/10 mx-0.5"></div>
{/* Time Range Selector */}
<div className="flex gap-0.5">
{(['week', 'month', 'year'] as const).map((r) => (
<button
key={r}
onClick={() => setTimeRange(r)}
className={`px-2.5 py-0.5 text-[9px] font-black uppercase tracking-tight rounded transition-all ${timeRange === r ? 'bg-primary text-primary-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground hover:bg-white/5'}`}
>
{r === 'week' ? '周' : r === 'month' ? '月' : '年'}
</button>
))}
</div>
</div>
</div>
</div>
{/* Metrics Grid */}
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<StatCard
title="通话数量"
value={stats.totalCalls.toString()}
icon={<Phone className="h-4 w-4 text-primary" />}
trend="+12.5% 较上期"
/>
<StatCard
title="接通率"
value={`${stats.answerRate}%`}
icon={<CheckCircle className="h-4 w-4 text-green-400" />}
trend="+2.1% 较上期"
/>
<StatCard
title="平均通话时长"
value={stats.avgDuration}
icon={<Clock className="h-4 w-4 text-blue-400" />}
trend="-0.5% 较上期"
/>
<StatCard
title="转人工数"
value={stats.humanTransferCount.toString()}
icon={<UserCheck className="h-4 w-4 text-purple-400" />}
trend="+5% 较上期"
/>
</div>
{/* 4. Metrics Grid (Cards) */}
<div className="grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">
<StatCard
title="通话数量"
value={stats.totalCalls.toString()}
icon={<Phone className="h-3.5 w-3.5 text-primary" />}
trend="+12.5% UP"
/>
<StatCard
title="接通率"
value={`${stats.answerRate}%`}
icon={<CheckCircle className="h-3.5 w-3.5 text-green-400" />}
trend="+2.1% UP"
/>
<StatCard
title="平均时长"
value={stats.avgDuration}
icon={<Clock className="h-3.5 w-3.5 text-blue-400" />}
trend="-0.5% LOW"
/>
<StatCard
title="转人工数"
value={stats.humanTransferCount.toString()}
icon={<UserCheck className="h-3.5 w-3.5 text-purple-400" />}
trend="+5% STABLE"
/>
</div>
{/* Charts Section */}
<div className="grid gap-4 md:grid-cols-1">
<Card className="p-6 border-primary/20 bg-card/30">
<div className="flex items-center justify-between mb-6">
<div className="space-y-1">
<h3 className="text-lg font-medium leading-none flex items-center">
<Activity className="h-5 w-5 text-primary mr-2" />
</h3>
<p className="text-sm text-muted-foreground"></p>
</div>
</div>
<div className="h-[300px] w-full">
<SimpleAreaChart data={stats.trend} />
</div>
</Card>
{/* 5. Charts Section */}
<div className="pt-1">
<Card className="p-5 border-white/5 bg-card/20 backdrop-blur-sm overflow-hidden shadow-xl">
<div className="flex flex-col md:flex-row items-center justify-between mb-6 gap-3">
<div className="space-y-0.5 text-center md:text-left">
<h3 className="text-base font-bold leading-none flex items-center justify-center md:justify-start text-white">
<Activity className="h-4 w-4 text-primary mr-2" />
(Performance Insight)
</h3>
<p className="text-[10px] text-muted-foreground font-mono opacity-40">REAL-TIME DATA PROCESSING PIPELINE ENABLED</p>
</div>
<div className="flex items-center space-x-2">
<div className="h-6 w-6 rounded-full border border-primary/20 flex items-center justify-center animate-spin-slow">
<div className="h-1 w-1 rounded-full bg-primary shadow-[0_0_8px_rgba(6,182,212,0.8)]"></div>
</div>
<span className="text-[9px] font-mono text-primary animate-pulse tracking-widest uppercase">Streaming</span>
</div>
</div>
<div className="h-[250px] w-full">
<SimpleAreaChart data={stats.trend} />
</div>
</Card>
</div>
</div>
</div>
);
@@ -98,14 +148,20 @@ export const DashboardPage: React.FC = () => {
// --- Sub Components ---
const StatCard: React.FC<{ title: string; value: string; icon: React.ReactNode; trend?: string }> = ({ title, value, icon, trend }) => (
<Card className="p-6 border-border/40 hover:border-primary/50 transition-colors">
<div className="flex flex-row items-center justify-between space-y-0 pb-2">
<h3 className="text-sm font-medium text-muted-foreground">{title}</h3>
{icon}
<Card className="p-4 border-white/5 bg-card/30 hover:border-primary/40 hover:bg-card/50 transition-all duration-300 group flex flex-col justify-between min-h-[110px] shadow-lg">
<div className="flex flex-row items-center justify-between space-y-0">
<h3 className="text-[9px] font-mono font-bold text-muted-foreground uppercase tracking-[0.15em]">{title}</h3>
<div className="p-1.5 bg-white/5 rounded-lg group-hover:bg-primary/20 transition-all group-hover:scale-110">
{icon}
</div>
</div>
<div className="content-end">
<div className="text-2xl font-bold tracking-tight text-foreground">{value}</div>
{trend && <p className="text-xs text-muted-foreground mt-1">{trend}</p>}
<div className="mt-2">
<div className="text-2xl font-black tracking-tight text-white group-hover:text-primary transition-colors">{value}</div>
{trend && (
<p className={`text-[8px] font-bold font-mono mt-1 flex items-center ${trend.includes('+') ? 'text-green-400' : 'text-red-400'}`}>
<span className="bg-white/5 px-1 rounded-sm mr-1 opacity-70">{trend}</span>
</p>
)}
</div>
</Card>
);
@@ -131,9 +187,16 @@ const SimpleAreaChart: React.FC<{ data: { label: string, value: number }[] }> =
return (
<div className="w-full h-full relative">
<svg viewBox={`0 0 ${width} ${height}`} className="w-full h-full overflow-visible" preserveAspectRatio="none">
{/* Tech Grid Lines */}
<line x1={padding} y1={height - padding} x2={width - padding} y2={height - padding} stroke="hsl(var(--border))" strokeWidth="1" />
<line x1={padding} y1={padding} x2={width - padding} y2={padding} stroke="hsl(var(--border))" strokeWidth="1" strokeDasharray="4 4" opacity="0.3" />
{/* Grid Lines */}
<line x1={padding} y1={height - padding} x2={width - padding} y2={height - padding} stroke="rgba(255,255,255,0.03)" strokeWidth="1" />
{[0.25, 0.5, 0.75].map(v => (
<line
key={v}
x1={padding} y1={height - padding - ((height - padding * 2) * v)}
x2={width - padding} y2={height - padding - ((height - padding * 2) * v)}
stroke="rgba(255,255,255,0.02)" strokeWidth="1" strokeDasharray="8 6"
/>
))}
{/* Area Fill Gradient */}
<defs>
@@ -141,9 +204,8 @@ const SimpleAreaChart: React.FC<{ data: { label: string, value: number }[] }> =
<stop offset="0%" stopColor="hsl(var(--primary))" stopOpacity="0.3" />
<stop offset="100%" stopColor="hsl(var(--primary))" stopOpacity="0" />
</linearGradient>
{/* Glow Filter */}
<filter id="glow" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="3" result="coloredBlur" />
<feGaussianBlur stdDeviation="5" result="coloredBlur" />
<feMerge>
<feMergeNode in="coloredBlur" />
<feMergeNode in="SourceGraphic" />
@@ -151,10 +213,8 @@ const SimpleAreaChart: React.FC<{ data: { label: string, value: number }[] }> =
</filter>
</defs>
{/* Fill Area */}
<polygon points={fillPath} fill="url(#chartGradient)" />
{/* Main Line with Glow */}
<polyline
points={points}
fill="none"
@@ -163,22 +223,23 @@ const SimpleAreaChart: React.FC<{ data: { label: string, value: number }[] }> =
strokeLinecap="round"
strokeLinejoin="round"
filter="url(#glow)"
className="drop-shadow-sm"
/>
{/* Data Points */}
{data.length < 20 && data.map((d, i) => {
{data.length < 32 && data.map((d, i) => {
const x = (i / (data.length - 1)) * (width - padding * 2) + padding;
const y = height - (d.value / maxValue) * (height - padding * 2) - padding;
return (
<circle key={i} cx={x} cy={y} r="4" fill="hsl(var(--background))" stroke="hsl(var(--primary))" strokeWidth="2" />
<g key={i} className="group/dot">
<circle cx={x} cy={y} r="3.5" fill="hsl(var(--background))" stroke="hsl(var(--primary))" strokeWidth="2" className="transition-all duration-300 group-hover/dot:r-5 group-hover/dot:stroke-white" />
<circle cx={x} cy={y} r="10" fill="hsl(var(--primary))" fillOpacity="0" className="cursor-pointer" />
</g>
);
})}
</svg>
{/* X-Axis Labels */}
<div className="absolute bottom-0 left-0 right-0 flex justify-between px-[2%] text-xs text-muted-foreground pointer-events-none font-mono">
{data.filter((_, i) => i % Math.ceil(data.length / 6) === 0).map((d, i) => (
<div className="absolute bottom-0 left-0 right-0 flex justify-between px-[3%] text-[8px] text-muted-foreground pointer-events-none font-mono opacity-30 mt-2">
{data.filter((_, i) => i % Math.ceil(data.length / 7) === 0).map((d, i) => (
<span key={i}>{d.label}</span>
))}
</div>

View File

@@ -1,6 +1,6 @@
import React, { useState, useRef } from 'react';
import { Search, Mic2, Play, Pause, Upload, X, Filter } from 'lucide-react';
import { Search, Mic2, Play, Pause, Upload, X, Filter, Plus, Volume2, Sparkles, Wand2, ChevronDown } from 'lucide-react';
import { Button, Input, TableHeader, TableRow, TableHead, TableCell, Dialog, Badge } from '../components/UI';
import { mockVoices } from '../services/mockData';
import { Voice } from '../types';
@@ -8,12 +8,13 @@ import { Voice } from '../types';
export const VoiceLibraryPage: React.FC = () => {
const [voices, setVoices] = useState<Voice[]>(mockVoices);
const [searchTerm, setSearchTerm] = useState('');
const [vendorFilter, setVendorFilter] = useState<'all' | 'Ali' | 'Volcano' | 'Minimax'>('all');
const [vendorFilter, setVendorFilter] = useState<'all' | 'Ali' | 'Volcano' | 'Minimax' | '硅基流动'>('all');
const [genderFilter, setGenderFilter] = useState<'all' | 'Male' | 'Female'>('all');
const [langFilter, setLangFilter] = useState<'all' | 'zh' | 'en'>('all');
const [playingVoiceId, setPlayingVoiceId] = useState<string | null>(null);
const [isCloneModalOpen, setIsCloneModalOpen] = useState(false);
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
const filteredVoices = voices.filter(voice => {
const matchesSearch = voice.name.toLowerCase().includes(searchTerm.toLowerCase());
@@ -28,15 +29,15 @@ export const VoiceLibraryPage: React.FC = () => {
setPlayingVoiceId(null);
} else {
setPlayingVoiceId(id);
// Mock auto-stop after 3 seconds
setTimeout(() => {
setPlayingVoiceId((current) => current === id ? null : current);
}, 3000);
}
};
const handleCloneSuccess = (newVoice: Voice) => {
const handleAddSuccess = (newVoice: Voice) => {
setVoices([newVoice, ...voices]);
setIsAddModalOpen(false);
setIsCloneModalOpen(false);
};
@@ -44,9 +45,14 @@ export const VoiceLibraryPage: React.FC = () => {
<div className="space-y-6 animate-in fade-in">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold tracking-tight"></h1>
<Button onClick={() => setIsCloneModalOpen(true)}>
<Mic2 className="mr-2 h-4 w-4" />
</Button>
<div className="flex space-x-3">
<Button variant="primary" onClick={() => setIsAddModalOpen(true)} className="shadow-[0_0_15px_rgba(6,182,212,0.4)]">
<Plus className="mr-2 h-4 w-4" />
</Button>
<Button variant="primary" onClick={() => setIsCloneModalOpen(true)} className="shadow-[0_0_15px_rgba(6,182,212,0.4)]">
<Mic2 className="mr-2 h-4 w-4" />
</Button>
</div>
</div>
{/* Filter Bar */}
@@ -68,6 +74,7 @@ export const VoiceLibraryPage: React.FC = () => {
onChange={(e) => setVendorFilter(e.target.value as any)}
>
<option value="all"></option>
<option value="硅基流动"> (SiliconFlow)</option>
<option value="Ali"> (Ali)</option>
<option value="Volcano"> (Volcano)</option>
<option value="Minimax">Minimax</option>
@@ -97,7 +104,7 @@ export const VoiceLibraryPage: React.FC = () => {
</div>
</div>
<div className="rounded-md border border-white/5 bg-card/40 backdrop-blur-md">
<div className="rounded-md border border-white/5 bg-card/40 backdrop-blur-md overflow-hidden">
<table className="w-full text-sm">
<TableHeader>
<TableRow>
@@ -113,12 +120,15 @@ export const VoiceLibraryPage: React.FC = () => {
<TableRow key={voice.id}>
<TableCell className="font-medium">
<div className="flex flex-col">
<span>{voice.name}</span>
<span className="flex items-center">
{voice.vendor === '硅基流动' && <Sparkles className="w-3 h-3 text-primary mr-1.5" />}
{voice.name}
</span>
{voice.description && <span className="text-xs text-muted-foreground">{voice.description}</span>}
</div>
</TableCell>
<TableCell>
<Badge variant="outline">{voice.vendor}</Badge>
<Badge variant={voice.vendor === '硅基流动' ? 'default' : 'outline'}>{voice.vendor}</Badge>
</TableCell>
<TableCell>{voice.gender === 'Male' ? '男' : '女'}</TableCell>
<TableCell>{voice.language === 'zh' ? '中文' : 'English'}</TableCell>
@@ -136,26 +146,238 @@ export const VoiceLibraryPage: React.FC = () => {
))}
{filteredVoices.length === 0 && (
<TableRow>
<TableCell className="text-center py-6 text-muted-foreground"></TableCell>
<TableCell> </TableCell>
<TableCell> </TableCell>
<TableCell> </TableCell>
<TableCell> </TableCell>
<TableCell colSpan={5} className="text-center py-6 text-muted-foreground"></TableCell>
</TableRow>
)}
</tbody>
</table>
</div>
<AddVoiceModal
isOpen={isAddModalOpen}
onClose={() => setIsAddModalOpen(false)}
onSuccess={handleAddSuccess}
/>
<CloneVoiceModal
isOpen={isCloneModalOpen}
onClose={() => setIsCloneModalOpen(false)}
onSuccess={handleCloneSuccess}
onSuccess={handleAddSuccess}
/>
</div>
);
};
// --- Unified Add Voice Modal ---
const AddVoiceModal: React.FC<{
isOpen: boolean;
onClose: () => void;
onSuccess: (voice: Voice) => void;
}> = ({ isOpen, onClose, onSuccess }) => {
const [vendor, setVendor] = useState<'硅基流动' | 'Ali' | 'Volcano' | 'Minimax'>('硅基流动');
const [name, setName] = useState('');
// SiliconFlow specific state
const [sfModel, setSfModel] = useState('fishaudio/fish-speech-1.5');
const [sfVoiceId, setSfVoiceId] = useState('fishaudio:amy');
const [sfSpeed, setSfSpeed] = useState(1);
const [sfGain, setSfGain] = useState(0);
// Common/Other state
const [model, setModel] = useState('');
const [voiceKey, setVoiceKey] = useState('');
const [gender, setGender] = useState('Female');
const [language, setLanguage] = useState('zh');
const [description, setDescription] = useState('');
const [testInput, setTestInput] = useState('你好,正在测试语音合成效果。');
const [isAuditioning, setIsAuditioning] = useState(false);
const handleAudition = () => {
if (!testInput.trim()) return;
setIsAuditioning(true);
// Mocking API Call
setTimeout(() => setIsAuditioning(false), 2000);
};
const handleSubmit = () => {
if (!name) { alert("请填写声音显示名称"); return; }
let newVoice: Voice = {
id: `${vendor === '硅基流动' ? 'sf' : 'gen'}-${Date.now()}`,
name: name,
vendor: vendor,
gender: gender,
language: language,
description: description || (vendor === '硅基流动' ? `Model: ${sfModel}` : `Model: ${model}`)
};
onSuccess(newVoice);
// Reset
setName('');
setVendor('硅基流动');
setDescription('');
};
return (
<Dialog
isOpen={isOpen}
onClose={onClose}
title="添加声音"
footer={
<>
<Button variant="ghost" onClick={onClose}></Button>
<Button onClick={handleSubmit} className="bg-primary hover:bg-primary/90"></Button>
</>
}
>
<div className="space-y-4 max-h-[75vh] overflow-y-auto px-1 custom-scrollbar">
{/* 1. Vendor Selection (Dropdown) */}
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"> (Vendor)</label>
<div className="relative">
<select
className="flex h-10 w-full rounded-md border border-white/10 bg-white/5 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 text-foreground appearance-none cursor-pointer [&>option]:bg-card"
value={vendor}
onChange={(e) => setVendor(e.target.value as any)}
>
<option value="硅基流动"> (SiliconFlow)</option>
<option value="Ali"> (Ali)</option>
<option value="Volcano"> (Volcano)</option>
<option value="Minimax">Minimax</option>
</select>
<ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
</div>
</div>
<div className="h-px bg-white/5"></div>
{/* 2. Basic Info */}
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"></label>
<Input value={name} onChange={e => setName(e.target.value)} placeholder="例如: 客服小美" />
</div>
{/* 3. Dynamic Parameters based on Vendor */}
{vendor === '硅基流动' ? (
<div className="space-y-4 animate-in fade-in slide-in-from-top-1 duration-200">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"> (Model)</label>
<select
className="flex h-9 w-full rounded-md border-0 bg-white/5 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 text-foreground [&>option]:bg-card"
value={sfModel}
onChange={e => setSfModel(e.target.value)}
>
<option value="fishaudio/fish-speech-1.5">fishaudio/fish-speech-1.5</option>
<option value="fishaudio/fish-speech-1.4">fishaudio/fish-speech-1.4</option>
<option value="ByteDance/SA-Speech">ByteDance/SA-Speech</option>
</select>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"> ID (Voice)</label>
<Input value={sfVoiceId} onChange={e => setSfVoiceId(e.target.value)} placeholder="fishaudio:amy" />
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"> (Speed)</label>
<div className="flex items-center space-x-2">
<input type="range" min="0.5" max="2" step="0.1" value={sfSpeed} onChange={e => setSfSpeed(parseFloat(e.target.value))} className="flex-1 accent-primary" />
<span className="text-[10px] font-mono text-primary bg-primary/10 px-1.5 py-0.5 rounded">{sfSpeed}x</span>
</div>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"> (Gain)</label>
<div className="flex items-center space-x-2">
<input type="range" min="-10" max="10" step="1" value={sfGain} onChange={e => setSfGain(parseInt(e.target.value))} className="flex-1 accent-primary" />
<span className="text-[10px] font-mono text-primary bg-primary/10 px-1.5 py-0.5 rounded">{sfGain}dB</span>
</div>
</div>
</div>
</div>
) : (
<div className="space-y-4 animate-in fade-in slide-in-from-top-1 duration-200">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"></label>
<Input value={model} onChange={e => setModel(e.target.value)} placeholder="API Model Key" />
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"></label>
<Input value={voiceKey} onChange={e => setVoiceKey(e.target.value)} placeholder="Voice Key" />
</div>
</div>
</div>
)}
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"></label>
<select
className="flex h-9 w-full rounded-md border-0 bg-white/5 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 text-foreground [&>option]:bg-card"
value={gender}
onChange={e => setGender(e.target.value)}
>
<option value="Female"> (Female)</option>
<option value="Male"> (Male)</option>
</select>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"></label>
<select
className="flex h-9 w-full rounded-md border-0 bg-white/5 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 text-foreground [&>option]:bg-card"
value={language}
onChange={e => setLanguage(e.target.value)}
>
<option value="zh"> (Chinese)</option>
<option value="en"> (English)</option>
</select>
</div>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block"></label>
<textarea
className="flex min-h-[60px] w-full rounded-md border-0 bg-white/5 px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 text-white"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="记录该声音的特点..."
/>
</div>
{/* Audition Section */}
<div className="p-4 rounded-xl border border-primary/20 bg-primary/5 space-y-3">
<div className="flex items-center justify-between">
<h4 className="text-[10px] font-black text-primary flex items-center tracking-widest uppercase">
<Volume2 className="w-3.5 h-3.5 mr-1.5" /> (Preview)
</h4>
{vendor === '硅基流动' && <Badge variant="outline" className="text-[8px] border-primary/20 text-primary/70">SiliconFlow Audio API</Badge>}
</div>
<div className="flex gap-2">
<Input
value={testInput}
onChange={e => setTestInput(e.target.value)}
placeholder="输入测试文本..."
className="text-xs bg-black/20"
/>
<Button
variant="primary"
size="sm"
onClick={handleAudition}
disabled={isAuditioning}
className="shrink-0 h-9"
>
{isAuditioning ? <Pause className="h-3.5 w-3.5 animate-pulse" /> : <Play className="h-3.5 w-3.5" />}
</Button>
</div>
</div>
</div>
</Dialog>
);
};
const CloneVoiceModal: React.FC<{
isOpen: boolean;
onClose: () => void;
@@ -178,19 +400,16 @@ const CloneVoiceModal: React.FC<{
return;
}
// Mock creation
const newVoice: Voice = {
id: `v-${Date.now()}`,
name: name,
vendor: 'Volcano', // Default for cloned voices
gender: 'Female', // Mock default
vendor: 'Volcano',
gender: 'Female',
language: 'zh',
description: description || 'User cloned voice'
};
onSuccess(newVoice);
// Reset
setName('');
setDescription('');
setFile(null);
@@ -248,7 +467,7 @@ const CloneVoiceModal: React.FC<{
<div className="space-y-2">
<label className="text-sm font-medium"></label>
<textarea
className="flex min-h-[80px] w-full rounded-md border-0 bg-white/5 px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50"
className="flex min-h-[80px] w-full rounded-md border-0 bg-white/5 px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 text-white"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="描述声音特点(如:年轻、沉稳..."

402
pages/WorkflowEditor.tsx Normal file
View File

@@ -0,0 +1,402 @@
import React, { useState, useRef, useEffect } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { ArrowLeft, Play, Save, Rocket, Plus, Bot, UserCheck, Wrench, Ban, Zap, X, Copy, MousePointer2 } from 'lucide-react';
import { Button, Input, Badge } from '../components/UI';
import { mockAssistants, mockKnowledgeBases, mockWorkflows } from '../services/mockData';
import { WorkflowNode, WorkflowEdge, Workflow } from '../types';
import { DebugDrawer } from './Assistants';
export const WorkflowEditorPage: React.FC = () => {
const navigate = useNavigate();
const { id } = useParams();
const [searchParams] = useSearchParams();
// Template data for new workflows
const templateName = searchParams.get('name');
const templateType = searchParams.get('template');
// Find initial workflow or create a new one
const existingWf = mockWorkflows.find(w => w.id === id);
const [name, setName] = useState(templateName || existingWf?.name || '新工作流');
const [nodes, setNodes] = useState<WorkflowNode[]>(() => {
if (existingWf) return existingWf.nodes;
if (templateType === 'lead') {
return [
{
name: 'introduction',
type: 'conversation',
isStart: true,
metadata: { position: { x: 100, y: 100 } },
prompt: "You are Morgan from GrowthPartners. Start with: 'Hello, this is Morgan from GrowthPartners. We help businesses improve their operational efficiency through custom software solutions. Do you have a few minutes to chat about how we might be able to help your business?'",
messagePlan: { firstMessage: "Hello, this is Morgan from GrowthPartners. Do you have a few minutes to chat?" }
},
{
name: 'need_discovery',
type: 'conversation',
metadata: { position: { x: 450, y: 250 } },
prompt: "Conduct need discovery by asking about business challenges...",
variableExtractionPlan: {
output: [
{ title: 'industry', type: 'string', description: 'user industry' },
{ title: 'pain_points', type: 'string', description: 'main challenges' }
]
}
},
{
name: 'hangup_node',
type: 'end',
metadata: { position: { x: 450, y: 550 } },
tool: {
type: 'endCall',
function: { name: 'hangup', parameters: {} },
messages: [{ type: 'request-start', content: 'Thank you for your time!', blocking: true }]
}
}
];
}
return [
{
name: 'start_node',
type: 'conversation',
isStart: true,
metadata: { position: { x: 200, y: 200 } },
prompt: '欢迎对话系统...',
messagePlan: { firstMessage: '你好!' }
}
];
});
const [edges, setEdges] = useState<WorkflowEdge[]>(existingWf?.edges || []);
const [selectedNodeName, setSelectedNodeName] = useState<string | null>(null);
const [isAddMenuOpen, setIsAddMenuOpen] = useState(false);
const [isDebugOpen, setIsDebugOpen] = useState(false);
const [zoom, setZoom] = useState(1);
const [panOffset, setPanOffset] = useState({ x: 0, y: 0 });
const [draggingNodeName, setDraggingNodeName] = useState<string | null>(null);
const [isPanning, setIsPanning] = useState(false);
const dragOffset = useRef({ x: 0, y: 0 });
const panStart = useRef({ x: 0, y: 0 });
const selectedNode = nodes.find(n => n.name === selectedNodeName);
// Scroll Zoom handler
const handleWheel = (e: React.WheelEvent) => {
e.preventDefault();
const zoomSpeed = 0.001;
const newZoom = Math.min(Math.max(zoom - e.deltaY * zoomSpeed, 0.2), 3);
setZoom(newZoom);
};
// Middle mouse click handler for panning
const handleMouseDown = (e: React.MouseEvent) => {
// Button 1 is middle mouse
if (e.button === 1) {
e.preventDefault();
setIsPanning(true);
panStart.current = { x: e.clientX - panOffset.x, y: e.clientY - panOffset.y };
}
};
const handleNodeMouseDown = (e: React.MouseEvent, nodeName: string) => {
if (e.button !== 0) return; // Only left click for nodes
e.stopPropagation();
setSelectedNodeName(nodeName);
setDraggingNodeName(nodeName);
const node = nodes.find(n => n.name === nodeName);
if (node) {
dragOffset.current = {
x: e.clientX - node.metadata.position.x * zoom,
y: e.clientY - node.metadata.position.y * zoom
};
}
};
useEffect(() => {
const handleMouseMove = (e: MouseEvent) => {
if (draggingNodeName) {
setNodes(prev => prev.map(n =>
n.name === draggingNodeName
? { ...n, metadata: { ...n.metadata, position: { x: (e.clientX - dragOffset.current.x) / zoom, y: (e.clientY - dragOffset.current.y) / zoom } } }
: n
));
} else if (isPanning) {
setPanOffset({
x: e.clientX - panStart.current.x,
y: e.clientY - panStart.current.y
});
}
};
const handleMouseUp = (e: MouseEvent) => {
setDraggingNodeName(null);
setIsPanning(false);
};
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('mouseup', handleMouseUp);
return () => {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
};
}, [draggingNodeName, isPanning, zoom]);
const addNode = (type: WorkflowNode['type']) => {
const newNode: WorkflowNode = {
name: `${type}_${Date.now()}`,
type,
metadata: { position: { x: (300 - panOffset.x) / zoom, y: (300 - panOffset.y) / zoom } },
prompt: type === 'conversation' ? '输入该节点的 Prompt...' : '',
tool: type === 'end' ? { type: 'endCall', function: { name: 'hangup', parameters: {} } } : undefined
};
setNodes([...nodes, newNode]);
setIsAddMenuOpen(false);
};
const updateNodeData = (field: string, value: any) => {
if (!selectedNodeName) return;
setNodes(prev => prev.map(n => n.name === selectedNodeName ? { ...n, [field]: value } : n));
};
const handleSave = () => {
const now = new Date().toISOString().replace('T', ' ').substring(0, 16);
const updatedWorkflow: Workflow = {
id: id || `wf_${Date.now()}`,
name,
nodeCount: nodes.length,
createdAt: existingWf?.createdAt || now,
updatedAt: now,
nodes,
edges,
};
if (id) {
const idx = mockWorkflows.findIndex(w => w.id === id);
if (idx !== -1) mockWorkflows[idx] = updatedWorkflow;
} else {
mockWorkflows.push(updatedWorkflow);
}
alert('保存成功!工作流已同步至列表。');
navigate('/workflows');
};
return (
<div className="flex flex-col h-[calc(100vh-6rem)] relative bg-card/10 border border-white/5 rounded-2xl overflow-hidden animate-in fade-in duration-300">
{/* Editor Header */}
<header className="h-14 border-b border-white/5 bg-white/[0.02] flex items-center justify-between px-4 shrink-0">
<div className="flex items-center space-x-3">
<Button variant="ghost" size="icon" onClick={() => navigate('/workflows')} className="h-8 w-8">
<ArrowLeft className="h-4 w-4" />
</Button>
<div className="h-4 w-px bg-white/10"></div>
<Input
value={name}
onChange={e => setName(e.target.value)}
className="bg-transparent border-transparent focus:bg-white/5 font-bold text-sm h-8 w-48 shadow-none text-white"
/>
</div>
<div className="flex items-center space-x-2">
<Button variant="outline" size="sm" onClick={() => setIsDebugOpen(true)}>
<Play className="mr-1.5 h-3.5 w-3.5" />
</Button>
<Button variant="secondary" size="sm" onClick={handleSave}>
<Save className="mr-1.5 h-3.5 w-3.5" />
</Button>
<Button size="sm" onClick={() => alert('发布成功!')}>
<Rocket className="mr-1.5 h-3.5 w-3.5" />
</Button>
</div>
</header>
{/* Canvas Area */}
<div
className="flex-1 relative bg-[radial-gradient(rgba(255,255,255,0.03)_1px,transparent_1px)] bg-[size:24px_24px] overflow-hidden select-none cursor-crosshair"
onWheel={handleWheel}
onMouseDown={handleMouseDown}
>
{/* Floating Controls */}
<div className="absolute top-4 left-4 z-10 flex flex-col items-start gap-2">
<Button
className="rounded-xl shadow-lg h-10 px-5 bg-primary text-primary-foreground font-semibold hover:bg-primary/90"
onClick={() => setIsAddMenuOpen(!isAddMenuOpen)}
>
<Plus className="mr-2 h-4 w-4" /> {isAddMenuOpen ? '取消' : '添加节点'}
</Button>
{isAddMenuOpen && (
<div className="bg-background/90 backdrop-blur-xl border border-white/10 rounded-xl p-1.5 w-48 shadow-2xl animate-in slide-in-from-top-2">
<button onClick={() => addNode('conversation')} className="flex items-center w-full p-2.5 hover:bg-primary/10 rounded-lg transition-colors text-sm text-left text-white">
<Bot className="w-4 h-4 mr-3 text-primary" /> <span></span>
</button>
<button onClick={() => addNode('tool')} className="flex items-center w-full p-2.5 hover:bg-purple-400/10 rounded-lg transition-colors text-sm text-left text-white">
<Wrench className="w-4 h-4 mr-3 text-purple-400" /> <span></span>
</button>
<button onClick={() => addNode('human')} className="flex items-center w-full p-2.5 hover:bg-orange-400/10 rounded-lg transition-colors text-sm text-left text-white">
<UserCheck className="w-4 h-4 mr-3 text-orange-400" /> <span></span>
</button>
<button onClick={() => addNode('end')} className="flex items-center w-full p-2.5 hover:bg-destructive/10 rounded-lg transition-colors text-sm text-left text-destructive">
<Ban className="w-4 h-4 mr-3" /> <span></span>
</button>
</div>
)}
<div className="flex items-center gap-2 bg-white/5 border border-white/10 rounded-lg px-2 py-1 text-[10px] text-muted-foreground font-mono">
<span>{Math.round(zoom * 100)}%</span>
<span className="opacity-30">|</span>
<span>POS: {Math.round(panOffset.x)}, {Math.round(panOffset.y)}</span>
</div>
</div>
{/* Scalable Container */}
<div
className="absolute inset-0"
style={{
transform: `translate(${panOffset.x}px, ${panOffset.y}px) scale(${zoom})`,
transformOrigin: '0 0'
}}
>
{nodes.map(node => (
<div
key={node.name}
onMouseDown={(e) => handleNodeMouseDown(e, node.name)}
style={{ left: node.metadata.position.x, top: node.metadata.position.y }}
className={`absolute w-56 p-4 rounded-xl border bg-card/70 backdrop-blur-sm cursor-grab active:cursor-grabbing group transition-shadow ${selectedNodeName === node.name ? 'border-primary shadow-[0_0_30px_rgba(6,182,212,0.3)]' : 'border-white/10 hover:border-white/30'}`}
>
<div className="flex items-center justify-between mb-3">
<div className="flex items-center space-x-2 overflow-hidden">
<NodeIcon type={node.type} />
<span className="font-semibold text-[10px] truncate uppercase tracking-tight text-white">{node.name}</span>
</div>
{node.isStart && <Badge variant="default" className="scale-75 origin-right">START</Badge>}
</div>
<div className="text-[10px] text-muted-foreground line-clamp-3 italic opacity-60 leading-relaxed">
{node.prompt || (node.tool ? `Action: ${node.tool.type}` : '待配置逻辑...')}
</div>
{/* Port simulation */}
<div className="absolute -bottom-1.5 left-1/2 -translate-x-1/2 w-3 h-3 bg-primary rounded-full border-2 border-background opacity-0 group-hover:opacity-100 cursor-crosshair transition-opacity shadow-[0_0_5px_rgba(6,182,212,0.5)]"></div>
<div className="absolute -top-1.5 left-1/2 -translate-x-1/2 w-3 h-3 bg-muted rounded-full border-2 border-background opacity-0 group-hover:opacity-100 cursor-crosshair transition-opacity"></div>
</div>
))}
</div>
{/* Bottom Right: Minimap */}
<div className="absolute bottom-6 right-6 w-48 h-32 bg-black/60 border border-white/10 rounded-2xl shadow-2xl pointer-events-none overflow-hidden flex flex-col backdrop-blur-md">
<div className="p-2 border-b border-white/5 bg-white/5 text-[9px] text-muted-foreground font-bold tracking-[0.2em] text-center uppercase">Minimap</div>
<div className="flex-1 relative p-3 opacity-60">
<div className="absolute inset-0 flex items-center justify-center">
<div className="relative w-full h-full">
{nodes.map((n, i) => {
// Simple scaling for minimap
const mx = (n.metadata.position.x / 10) % 100;
const my = (n.metadata.position.y / 10) % 100;
return (
<div
key={i}
className={`absolute w-3 h-2 rounded-sm ${n.type === 'conversation' ? 'bg-primary' : n.type === 'end' ? 'bg-destructive' : 'bg-white/40'}`}
style={{ left: `${20 + mx}%`, top: `${20 + my}%` }}
></div>
);
})}
</div>
</div>
{/* Viewport visualization */}
<div
className="absolute border border-primary/40 bg-primary/5 rounded shadow-sm"
style={{ width: '40%', height: '40%', left: '30%', top: '30%' }}
/>
</div>
</div>
{/* Navigator Guide */}
<div className="absolute bottom-4 left-4 text-[10px] text-muted-foreground/30 font-mono flex items-center gap-2">
<MousePointer2 className="w-3 h-3" /> |
</div>
</div>
{/* Right Settings Panel */}
{selectedNode && (
<div className="absolute right-0 top-14 bottom-0 w-80 border-l border-white/10 bg-background/95 backdrop-blur-2xl flex flex-col animate-in slide-in-from-right duration-300 z-20 shadow-[-10px_0_30px_rgba(0,0,0,0.5)]">
<div className="p-4 border-b border-white/5 flex items-center justify-between bg-white/5">
<h3 className="text-sm font-bold uppercase tracking-widest text-primary"></h3>
<Button variant="ghost" size="icon" onClick={() => setSelectedNodeName(null)} className="h-8 w-8">
<X className="h-4 w-4" />
</Button>
</div>
<div className="flex-1 overflow-y-auto p-5 space-y-6 custom-scrollbar">
<div className="space-y-2">
<label className="text-[10px] text-muted-foreground uppercase font-mono tracking-widest"> (Node Name)</label>
<Input
value={selectedNode.name}
onChange={e => updateNodeData('name', e.target.value)}
className="h-8 text-xs font-mono text-white bg-white/10"
/>
</div>
<div className="space-y-2">
<label className="text-[10px] text-muted-foreground uppercase font-mono tracking-widest"></label>
<Badge variant="outline" className="w-fit">{selectedNode.type.toUpperCase()}</Badge>
</div>
{selectedNode.type === 'conversation' && (
<>
<div className="space-y-2">
<label className="text-[10px] text-muted-foreground uppercase font-mono tracking-widest">Prompt ()</label>
<textarea
className="w-full h-48 bg-white/5 border border-white/10 rounded-lg p-3 text-xs focus:outline-none focus:ring-1 focus:ring-primary/50 text-white placeholder:text-muted-foreground/30 leading-relaxed"
value={selectedNode.prompt || ''}
onChange={e => updateNodeData('prompt', e.target.value)}
placeholder="输入该节点的业务规则、语气要求和回复逻辑..."
/>
</div>
<div className="space-y-2">
<label className="text-[10px] text-muted-foreground uppercase font-mono tracking-widest">First Message ()</label>
<Input
value={selectedNode.messagePlan?.firstMessage || ''}
onChange={e => updateNodeData('messagePlan', { ...selectedNode.messagePlan, firstMessage: e.target.value })}
className="h-8 text-xs text-white"
placeholder="进入该节点时 AI 主动发起的消息..."
/>
</div>
</>
)}
{selectedNode.type === 'end' && (
<div className="p-4 rounded-xl border border-destructive/20 bg-destructive/5 text-xs text-destructive/80 space-y-2">
<p className="font-bold"></p>
<p></p>
</div>
)}
<div className="pt-4 border-t border-white/5">
<label className="flex items-center gap-3 cursor-pointer group">
<input
type="checkbox"
checked={selectedNode.isStart}
onChange={e => updateNodeData('isStart', e.target.checked)}
className="w-4 h-4 rounded accent-primary border-white/10 bg-white/5"
/>
<span className="text-[10px] text-muted-foreground group-hover:text-primary transition-colors uppercase font-mono tracking-widest"> (Start Node)</span>
</label>
</div>
</div>
</div>
)}
{/* Debug Side Drawer */}
<DebugDrawer
isOpen={isDebugOpen}
onClose={() => setIsDebugOpen(false)}
assistant={mockAssistants[0]}
/>
</div>
);
};
const NodeIcon = ({ type }: { type: WorkflowNode['type'] }) => {
switch (type) {
case 'conversation': return <Bot className="h-4 w-4 text-primary" />;
case 'human': return <UserCheck className="h-4 w-4 text-orange-400" />;
case 'tool': return <Wrench className="h-4 w-4 text-purple-400" />;
case 'end': return <Ban className="h-4 w-4 text-destructive" />;
default: return <MousePointer2 className="h-4 w-4" />;
}
};

235
pages/Workflows.tsx Normal file
View File

@@ -0,0 +1,235 @@
import React, { useState, useRef } from 'react';
import { Search, Plus, Upload, MoreHorizontal, Code, Edit2, Copy, Trash2, Calendar, CloudUpload, File as FileIcon, X, Layout, FilePlus } from 'lucide-react';
import { Button, Input, TableHeader, TableRow, TableHead, TableCell, Dialog, Card } from '../components/UI';
import { mockWorkflows } from '../services/mockData';
import { useNavigate } from 'react-router-dom';
export const WorkflowsPage: React.FC = () => {
const navigate = useNavigate();
const [workflows, setWorkflows] = useState(mockWorkflows);
const [searchTerm, setSearchTerm] = useState('');
const [isUploadOpen, setIsUploadOpen] = useState(false);
const [isCreateOpen, setIsCreateOpen] = useState(false);
const [activeMenu, setActiveMenu] = useState<string | null>(null);
// New Workflow State
const [newWfName, setNewWfName] = useState('');
const [selectedTemplate, setSelectedTemplate] = useState<'blank' | 'lead'>('blank');
const filteredWorkflows = workflows.filter(wf =>
wf.name.toLowerCase().includes(searchTerm.toLowerCase())
);
const handleCreateWorkflow = () => {
if (!newWfName.trim()) {
alert('请输入工作流名称');
return;
}
setIsCreateOpen(false);
// Navigate to the editor with the template name and type as query params
navigate(`/workflows/new?name=${encodeURIComponent(newWfName)}&template=${selectedTemplate}`);
};
const handleDeleteWorkflow = (id: string) => {
if (confirm('确定要删除这个工作流吗?')) {
setWorkflows(prev => prev.filter(w => w.id !== id));
setActiveMenu(null);
}
};
return (
<div className="space-y-6 animate-in fade-in">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold tracking-tight text-white"></h1>
<div className="flex space-x-3">
<Button variant="outline" onClick={() => setIsUploadOpen(true)}>
<Upload className="mr-2 h-4 w-4" /> JSON
</Button>
<Button onClick={() => setIsCreateOpen(true)}>
<Plus className="mr-2 h-4 w-4" />
</Button>
</div>
</div>
<div className="flex flex-col md:flex-row gap-4 bg-card/50 p-4 rounded-lg border border-white/5 shadow-sm">
<div className="relative flex-1">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="搜索工作流..."
className="pl-9 border-0 bg-white/5"
value={searchTerm}
onChange={e => setSearchTerm(e.target.value)}
/>
</div>
<div className="flex items-center space-x-2 bg-white/5 rounded-md px-3 border border-white/10 group focus-within:border-primary/50 transition-colors">
<Calendar className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
<select className="bg-transparent text-sm h-9 focus:outline-none border-none text-foreground cursor-pointer [&>option]:bg-background">
<option value="all"></option>
<option value="today"></option>
<option value="week"></option>
<option value="month"></option>
</select>
</div>
</div>
<div className="rounded-xl border border-white/5 bg-card/40 backdrop-blur-md overflow-hidden">
<table className="w-full text-sm">
<TableHeader>
<TableRow>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="text-right"></TableHead>
</TableRow>
</TableHeader>
<tbody>
{filteredWorkflows.map(wf => (
<TableRow key={wf.id} className="group">
<TableCell className="font-medium">
<button
onClick={() => navigate(`/workflows/edit/${wf.id}`)}
className="hover:text-primary transition-colors cursor-pointer text-left font-semibold text-white"
>
{wf.name}
</button>
</TableCell>
<TableCell>{wf.nodeCount} </TableCell>
<TableCell className="text-muted-foreground">{wf.createdAt}</TableCell>
<TableCell className="text-muted-foreground">{wf.updatedAt}</TableCell>
<TableCell className="text-right relative">
<Button
variant="ghost"
size="icon"
onClick={() => setActiveMenu(activeMenu === wf.id ? null : wf.id)}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
{activeMenu === wf.id && (
<div className="absolute right-0 top-12 z-50 w-48 bg-background border border-white/10 rounded-lg shadow-xl py-1 animate-in zoom-in-95">
<button className="flex items-center w-full px-4 py-2 text-xs hover:bg-white/5 text-left" onClick={() => { alert('JSON copied!'); setActiveMenu(null); }}>
<Code className="w-3.5 h-3.5 mr-2 opacity-70" /> JSON
</button>
<button className="flex items-center w-full px-4 py-2 text-xs hover:bg-white/5 text-left" onClick={() => navigate(`/workflows/edit/${wf.id}`)}>
<Edit2 className="w-3.5 h-3.5 mr-2 opacity-70" />
</button>
<button className="flex items-center w-full px-4 py-2 text-xs hover:bg-white/5 text-left" onClick={() => setActiveMenu(null)}>
<Copy className="w-3.5 h-3.5 mr-2 opacity-70" />
</button>
<div className="h-px bg-white/10 my-1" />
<button className="flex items-center w-full px-4 py-2 text-xs hover:bg-white/5 text-left text-destructive" onClick={() => handleDeleteWorkflow(wf.id)}>
<Trash2 className="w-3.5 h-3.5 mr-2 opacity-70" />
</button>
</div>
)}
</TableCell>
</TableRow>
))}
{filteredWorkflows.length === 0 && (
<TableRow>
<TableCell colSpan={5} className="text-center py-12 text-muted-foreground"></TableCell>
</TableRow>
)}
</tbody>
</table>
</div>
<UploadJsonModal isOpen={isUploadOpen} onClose={() => setIsUploadOpen(false)} />
{/* Create Workflow Modal */}
<Dialog
isOpen={isCreateOpen}
onClose={() => setIsCreateOpen(false)}
title="创建新工作流"
footer={
<>
<Button variant="ghost" onClick={() => setIsCreateOpen(false)}></Button>
<Button onClick={handleCreateWorkflow}></Button>
</>
}
>
<div className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium text-white"></label>
<Input
value={newWfName}
onChange={e => setNewWfName(e.target.value)}
placeholder="例如: Lead Qualification Agent"
autoFocus
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-white"></label>
<div className="grid grid-cols-2 gap-3">
<div
onClick={() => setSelectedTemplate('blank')}
className={`p-4 rounded-xl border-2 cursor-pointer transition-all flex flex-col items-center text-center space-y-2 ${selectedTemplate === 'blank' ? 'border-primary bg-primary/10' : 'border-white/5 bg-white/5 hover:bg-white/10'}`}
>
<FilePlus className={`w-8 h-8 ${selectedTemplate === 'blank' ? 'text-primary' : 'text-muted-foreground'}`} />
<div>
<div className="text-sm font-bold text-white"></div>
<div className="text-[10px] text-muted-foreground"></div>
</div>
</div>
<div
onClick={() => setSelectedTemplate('lead')}
className={`p-4 rounded-xl border-2 cursor-pointer transition-all flex flex-col items-center text-center space-y-2 ${selectedTemplate === 'lead' ? 'border-primary bg-primary/10' : 'border-white/5 bg-white/5 hover:bg-white/10'}`}
>
<Layout className={`w-8 h-8 ${selectedTemplate === 'lead' ? 'text-primary' : 'text-muted-foreground'}`} />
<div>
<div className="text-sm font-bold text-white"></div>
<div className="text-[10px] text-muted-foreground"> Lead </div>
</div>
</div>
</div>
</div>
</div>
</Dialog>
</div>
);
};
const UploadJsonModal: React.FC<{ isOpen: boolean; onClose: () => void }> = ({ isOpen, onClose }) => {
const [dragActive, setDragActive] = useState(false);
const [file, setFile] = useState<File | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
const handleDrag = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setDragActive(e.type === "dragenter" || e.type === "dragover");
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault(); e.stopPropagation();
setDragActive(false);
if (e.dataTransfer.files?.[0]) setFile(e.dataTransfer.files[0]);
};
return (
<Dialog
isOpen={isOpen} onClose={onClose} title="上传工作流 JSON"
footer={
<>
<Button variant="ghost" onClick={onClose}></Button>
<Button onClick={() => { alert('Import Success!'); onClose(); }}></Button>
</>
}
>
<div
className={`relative flex flex-col items-center justify-center w-full h-48 rounded-lg border-2 border-dashed transition-all cursor-pointer ${dragActive ? "border-primary bg-primary/10" : "border-white/10 bg-white/5 hover:bg-white/10"}`}
onDragEnter={handleDrag} onDragLeave={handleDrag} onDragOver={handleDrag} onDrop={handleDrop}
onClick={() => inputRef.current?.click()}
>
<input ref={inputRef} type="file" className="hidden" accept=".json" onChange={e => e.target.files?.[0] && setFile(e.target.files[0])} />
<CloudUpload className={`h-10 w-10 mb-3 ${dragActive ? 'text-primary' : 'text-muted-foreground'}`} />
<p className="text-sm text-muted-foreground text-center">
{file ? <span className="text-primary font-medium">{file.name}</span> : <span><span className="font-semibold text-primary"></span> JSON </span>}
</p>
<p className="text-xs text-muted-foreground mt-1"> .json </p>
</div>
</Dialog>
);
};

View File

@@ -1,5 +1,5 @@
import { Assistant, CallLog, KnowledgeBase, Voice } from '../types';
import { Assistant, CallLog, KnowledgeBase, Voice, Workflow, AutoTestAssistant, TestType, TestMethod } from '../types';
export const mockAssistants: Assistant[] = [
{
@@ -28,6 +28,50 @@ export const mockAssistants: Assistant[] = [
},
];
export let mockWorkflows: Workflow[] = [
{
id: 'wf1',
name: 'Lead Qualification Agent',
nodeCount: 11,
createdAt: '2024-03-01 10:00',
updatedAt: '2024-03-05 14:30',
nodes: [
{
name: "introduction",
type: "conversation",
isStart: true,
metadata: { position: { x: 100, y: 100 } },
prompt: "You are Morgan from GrowthPartners. Start with: 'Hello, this is Morgan from GrowthPartners. We help businesses improve their operational efficiency through custom software solutions. Do you have a few minutes to chat about how we might be able to help your business?' Use a friendly, consultative tone.",
messagePlan: { firstMessage: "Hello, this is Morgan from GrowthPartners. Do you have a few minutes to chat about how we might be able to help your business?" }
},
{
name: "need_discovery",
type: "conversation",
metadata: { position: { x: 400, y: 150 } },
prompt: "Conduct need discovery by asking about: 1) Their business and industry, 2) Current systems/processes they use, 3) Biggest challenges with current approach...",
variableExtractionPlan: {
output: [
{ type: "string", title: "industry", description: "the user's industry or business type" },
{ type: "string", title: "company_size", description: "approximate number of employees" }
]
}
}
],
edges: [
{ from: "introduction", to: "need_discovery" }
]
},
{
id: 'wf2',
name: '售后退款流程',
nodeCount: 5,
createdAt: '2024-03-01 10:00',
updatedAt: '2024-03-05 14:30',
nodes: [],
edges: []
},
];
export const mockKnowledgeBases: KnowledgeBase[] = [
{
id: 'kb1',
@@ -85,7 +129,28 @@ export const mockVoices: Voice[] = [
{ id: 'v5', name: 'Doubao', vendor: 'Volcano', gender: 'Female', language: 'zh', description: 'Cute and young.' },
];
// --- Dashboard Mock Data Helpers ---
export const mockAutoTestAssistants: AutoTestAssistant[] = [
{
id: 'at1',
name: '退款流程压力测试',
type: TestType.FIXED,
method: TestMethod.TEXT,
targetAssistantId: '1',
fixedWorkflowSteps: ['你好,我要退款', '订单号是123456', '谢谢'],
intelligentPrompt: '',
createdAt: '2024-03-10 09:00'
},
{
id: 'at2',
name: '愤怒的客户模拟',
type: TestType.INTELLIGENT,
method: TestMethod.AUDIO,
targetAssistantId: '1',
fixedWorkflowSteps: [],
intelligentPrompt: '你是一个非常愤怒的客户,因为订单延迟了一周。你需要表达你的不满,并要求立即解决。你的语气必须很冲,不接受简单的道歉。',
createdAt: '2024-03-11 14:20'
}
];
export interface DashboardStats {
totalCalls: number;
@@ -96,14 +161,11 @@ export interface DashboardStats {
}
export const getDashboardStats = (timeRange: 'week' | 'month' | 'year', assistantId: string): DashboardStats => {
// Simulate data variation based on inputs
const multiplier = assistantId === 'all' ? 1 : (assistantId === '1' ? 0.6 : 0.4);
const rangeMultiplier = timeRange === 'week' ? 1 : (timeRange === 'month' ? 4 : 52);
const baseCalls = Math.floor(100 * rangeMultiplier * multiplier);
const transfers = Math.floor(baseCalls * 0.15); // 15% transfer rate
const transfers = Math.floor(baseCalls * 0.15);
// Generate Trend Data
let points = 7;
if (timeRange === 'month') points = 30;
if (timeRange === 'year') points = 12;
@@ -122,7 +184,7 @@ export const getDashboardStats = (timeRange: 'week' | 'month' | 'year', assistan
return {
totalCalls: baseCalls,
answerRate: 85 + Math.floor(Math.random() * 10), // 85-95%
answerRate: 85 + Math.floor(Math.random() * 10),
avgDuration: `${Math.floor(2 + Math.random() * 3)}m ${Math.floor(Math.random() * 60)}s`,
humanTransferCount: transfers,
trend

View File

@@ -10,6 +10,16 @@ export interface Assistant {
voice: string;
speed: number;
hotwords: string[];
tools?: string[]; // IDs of enabled tools
}
export interface Voice {
id: string;
name: string;
vendor: string;
gender: string;
language: string;
description: string;
}
export interface KnowledgeBase {
@@ -36,24 +46,79 @@ export interface CallLog {
agentName: string;
}
export interface UserProfile {
username: string;
avatarUrl: string;
email: string;
language: 'zh' | 'en';
}
export interface Voice {
export interface Workflow {
id: string;
name: string;
vendor: 'Ali' | 'Volcano' | 'Minimax';
gender: 'Male' | 'Female';
language: 'zh' | 'en';
description?: string;
previewUrl?: string; // Mock url
nodeCount: number;
createdAt: string;
updatedAt: string;
nodes: WorkflowNode[];
edges: WorkflowEdge[];
globalPrompt?: string;
}
export interface WorkflowNode {
name: string;
type: 'conversation' | 'tool' | 'human' | 'end';
isStart?: boolean;
metadata: {
position: { x: number; y: number };
};
prompt?: string;
messagePlan?: {
firstMessage?: string;
};
variableExtractionPlan?: {
output: Array<{
type: string;
title: string;
description: string;
}>;
};
tool?: {
type: string;
function: {
name: string;
parameters: any;
};
destinations?: any[];
messages?: any[];
};
globalNodePlan?: {
enabled: boolean;
enterCondition: string;
};
}
export interface WorkflowEdge {
from: string;
to: string;
label?: string;
}
export enum TabValue {
GLOBAL = 'global',
VOICE = 'voice'
VOICE = 'voice',
TOOLS = 'tools'
}
export enum TestType {
FIXED = 'fixed',
INTELLIGENT = 'intelligent'
}
export enum TestMethod {
TEXT = 'text',
AUDIO = 'audio'
}
export interface AutoTestAssistant {
id: string;
name: string;
type: TestType;
method: TestMethod;
targetAssistantId: string;
fixedWorkflowSteps: string[];
intelligentPrompt: string;
createdAt: string;
}