refactor: 移除 Team 和 Swarm 协作功能
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled

功能论证结论:Team(团队)和 Swarm(协作)为零后端支持的
纯前端 localStorage 空壳,Pipeline 系统已完全覆盖其全部能力。

删除 16 个文件,约 7,950 行代码:
- 5 个组件:TeamCollaborationView, TeamOrchestrator, TeamList, DevQALoop, SwarmDashboard
- 1 个 Store:teamStore.ts
- 3 个 Client/库:team-client.ts, useTeamEvents.ts, agent-swarm.ts
- 1 个类型文件:team.ts
- 4 个测试文件
- 1 个文档(归档 swarm-coordination.md)

修改 4 个文件:
- Sidebar.tsx:移除"团队"和"协作"导航项
- App.tsx:移除 team/swarm 视图路由
- types/index.ts:移除 team 类型导出
- chatStore.ts:移除 dispatchSwarmTask 方法

更新 CHANGELOG.md 和功能文档 README.md
This commit is contained in:
iven
2026-03-26 20:27:19 +08:00
parent 978dc5cdd8
commit c3996573aa
22 changed files with 11 additions and 7689 deletions

View File

@@ -43,6 +43,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Stub Channel 适配器Telegram、Discord、Slack
- 未使用的 StoremeshStore、personaStore
- 不完整的 ActiveLearningPanel 和 skillMarketStore
- 未使用的 Feedback 组件目录
- Team团队和 Swarm协作功能~8,100 行前端代码零后端支持Pipeline 系统已覆盖其全部能力)
- 调试日志清理(~310 处 console/println 语句)
---

View File

@@ -6,9 +6,6 @@ import { ChatArea } from './components/ChatArea';
import { RightPanel } from './components/RightPanel';
import { SettingsLayout } from './components/Settings/SettingsLayout';
import { AutomationPanel } from './components/Automation';
import { TeamCollaborationView } from './components/TeamCollaborationView';
import { TeamOrchestrator } from './components/TeamOrchestrator';
import { SwarmDashboard } from './components/SwarmDashboard';
import { SkillMarket } from './components/SkillMarket';
import { AgentOnboardingWizard } from './components/AgentOnboardingWizard';
import { HandApprovalModal } from './components/HandApprovalModal';
@@ -16,13 +13,11 @@ import { TopBar } from './components/TopBar';
import { DetailDrawer } from './components/DetailDrawer';
import { useConnectionStore } from './store/connectionStore';
import { useHandStore, type HandRun } from './store/handStore';
import { useTeamStore } from './store/teamStore';
import { useChatStore } from './store/chatStore';
import { initializeStores } from './store';
import { getStoredGatewayToken } from './lib/gateway-client';
import { pageVariants, defaultTransition, fadeInVariants } from './lib/animations';
import { Users, Loader2, Settings } from 'lucide-react';
import { EmptyState } from './components/ui';
import { Loader2 } from 'lucide-react';
import { isTauriRuntime, getLocalGatewayStatus, startLocalGateway } from './lib/tauri-gateway';
import { useOnboarding } from './lib/use-onboarding';
import { intelligenceClient } from './lib/intelligence-client';
@@ -47,7 +42,6 @@ function BootstrapScreen({ status }: { status: string }) {
function App() {
const [view, setView] = useState<View>('main');
const [mainContentView, setMainContentView] = useState<MainViewType>('chat');
const [selectedTeamId, setSelectedTeamId] = useState<string | undefined>(undefined);
const [bootstrapping, setBootstrapping] = useState(true);
const [bootstrapStatus, setBootstrapStatus] = useState('Initializing...');
const [showOnboarding, setShowOnboarding] = useState(false);
@@ -56,13 +50,11 @@ function App() {
// Hand Approval state
const [pendingApprovalRun, setPendingApprovalRun] = useState<HandRun | null>(null);
const [showApprovalModal, setShowApprovalModal] = useState(false);
const [teamViewMode, setTeamViewMode] = useState<'collaboration' | 'orchestrator'>('collaboration');
const connect = useConnectionStore((s) => s.connect);
const hands = useHandStore((s) => s.hands);
const approveHand = useHandStore((s) => s.approveHand);
const loadHands = useHandStore((s) => s.loadHands);
const { activeTeam, setActiveTeam, teams } = useTeamStore();
const { setCurrentAgent, newConversation } = useChatStore();
const { isNeeded: onboardingNeeded, isLoading: onboardingLoading, markCompleted } = useOnboarding();
@@ -288,14 +280,6 @@ function App() {
setMainContentView('chat');
};
const handleSelectTeam = (teamId: string) => {
const team = teams.find(t => t.id === teamId);
if (team) {
setActiveTeam(team);
setSelectedTeamId(teamId);
}
};
if (view === 'settings') {
return <SettingsLayout onBack={() => setView('main')} />;
}
@@ -362,8 +346,6 @@ function App() {
<Sidebar
onOpenSettings={() => setView('settings')}
onMainViewChange={handleMainViewChange}
selectedTeamId={selectedTeamId}
onSelectTeam={handleSelectTeam}
onNewChat={handleNewChat}
/>
@@ -395,59 +377,6 @@ function App() {
>
<AutomationPanel />
</motion.div>
) : mainContentView === 'team' ? (
activeTeam ? (
<div className="h-full flex flex-col">
{/* Team View Tabs */}
<div className="flex border-b border-gray-200 dark:border-gray-700 px-4">
<button
onClick={() => setTeamViewMode('collaboration')}
className={`flex items-center gap-1.5 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
teamViewMode === 'collaboration'
? 'text-orange-600 dark:text-orange-400 border-orange-500'
: 'text-gray-500 dark:text-gray-400 border-transparent hover:text-gray-700 dark:hover:text-gray-300'
}`}
>
<Users className="w-4 h-4" />
</button>
<button
onClick={() => setTeamViewMode('orchestrator')}
className={`flex items-center gap-1.5 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
teamViewMode === 'orchestrator'
? 'text-orange-600 dark:text-orange-400 border-orange-500'
: 'text-gray-500 dark:text-gray-400 border-transparent hover:text-gray-700 dark:hover:text-gray-300'
}`}
>
<Settings className="w-4 h-4" />
</button>
</div>
{/* Tab Content */}
<div className="flex-1 overflow-hidden">
{teamViewMode === 'orchestrator' ? (
<TeamOrchestrator isOpen={true} onClose={() => setTeamViewMode('collaboration')} />
) : (
<TeamCollaborationView teamId={activeTeam.id} />
)}
</div>
</div>
) : (
<EmptyState
icon={<Users className="w-8 h-8" />}
title="选择或创建团队"
description="从左侧列表中选择一个团队,或点击 + 创建新的多 Agent 协作团队。"
/>
)
) : mainContentView === 'swarm' ? (
<motion.div
variants={fadeInVariants}
initial="initial"
animate="animate"
className="h-full overflow-hidden"
>
<SwarmDashboard />
</motion.div>
) : mainContentView === 'skills' ? (
<motion.div
variants={fadeInVariants}

View File

@@ -1,464 +0,0 @@
/**
* DevQALoop - Developer ↔ QA Review Loop Interface
*
* Visualizes the iterative review cycle between Developer and QA agents,
* showing iteration count, feedback history, and current state.
*
* @module components/DevQALoop
*/
import { useState } from 'react';
import { useTeamStore } from '../store/teamStore';
import type { DevQALoop as DevQALoopType, ReviewFeedback, ReviewIssue } from '../types/team';
import {
RefreshCw, CheckCircle, XCircle, AlertTriangle,
Clock, MessageSquare, FileCode, Bug, Lightbulb, ChevronDown, ChevronUp,
Send, ThumbsUp, ThumbsDown, AlertOctagon,
} from 'lucide-react';
// === Sub-Components ===
interface FeedbackItemProps {
feedback: ReviewFeedback;
iteration: number;
isExpanded: boolean;
onToggle: () => void;
}
function FeedbackItem({ feedback, iteration, isExpanded, onToggle }: FeedbackItemProps) {
const verdictColors = {
approved: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300',
needs_work: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300',
rejected: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300',
};
const verdictIcons = {
approved: <ThumbsUp className="w-4 h-4" />,
needs_work: <AlertTriangle className="w-4 h-4" />,
rejected: <ThumbsDown className="w-4 h-4" />,
};
const severityColors = {
critical: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300',
major: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300',
minor: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300',
suggestion: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300',
};
return (
<div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
<button
onClick={onToggle}
className="w-full px-4 py-3 flex items-center justify-between bg-gray-50 dark:bg-gray-800"
>
<div className="flex items-center gap-3">
<span className="w-6 h-6 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center text-xs font-medium">
{iteration}
</span>
<span className={`px-2 py-0.5 rounded text-xs font-medium flex items-center gap-1 ${verdictColors[feedback.verdict]}`}>
{verdictIcons[feedback.verdict]}
{feedback.verdict.replace('_', ' ')}
</span>
<span className="text-xs text-gray-500 dark:text-gray-400">
{new Date(feedback.reviewedAt).toLocaleString()}
</span>
</div>
{isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
</button>
{isExpanded && (
<div className="p-4 space-y-4">
{/* Comments */}
{feedback.comments.length > 0 && (
<div>
<h5 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Comments</h5>
<ul className="space-y-2">
{feedback.comments.map((comment, idx) => (
<li key={idx} className="text-sm text-gray-600 dark:text-gray-400 flex items-start gap-2">
<MessageSquare className="w-4 h-4 mt-0.5 text-gray-400" />
{comment}
</li>
))}
</ul>
</div>
)}
{/* Issues */}
{feedback.issues.length > 0 && (
<div>
<h5 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Issues ({feedback.issues.length})</h5>
<div className="space-y-2">
{feedback.issues.map((issue, idx) => (
<div key={idx} className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
<div className="flex items-center gap-2 mb-1">
<span className={`px-1.5 py-0.5 rounded text-xs font-medium ${severityColors[issue.severity]}`}>
{issue.severity}
</span>
{issue.file && (
<span className="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1">
<FileCode className="w-3 h-3" />
{issue.file}{issue.line ? `:${issue.line}` : ''}
</span>
)}
</div>
<p className="text-sm text-gray-700 dark:text-gray-300">{issue.description}</p>
{issue.suggestion && (
<p className="mt-1 text-xs text-blue-600 dark:text-blue-400 flex items-start gap-1">
<Lightbulb className="w-3 h-3 mt-0.5" />
{issue.suggestion}
</p>
)}
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
);
}
interface ReviewFormProps {
loopId: string;
teamId: string;
onSubmit: (feedback: Omit<ReviewFeedback, 'reviewedAt' | 'reviewerId'>) => void;
onCancel: () => void;
}
function ReviewForm({ loopId: _loopId, teamId: _teamId, onSubmit, onCancel }: ReviewFormProps) {
const [verdict, setVerdict] = useState<ReviewFeedback['verdict']>('needs_work');
const [comment, setComment] = useState('');
const [issues, setIssues] = useState<ReviewIssue[]>([]);
const [newIssue, setNewIssue] = useState<Partial<ReviewIssue>>({});
const handleAddIssue = () => {
if (!newIssue.description) return;
setIssues([...issues, {
severity: newIssue.severity || 'minor',
description: newIssue.description,
file: newIssue.file,
line: newIssue.line,
suggestion: newIssue.suggestion,
} as ReviewIssue]);
setNewIssue({});
};
const handleSubmit = () => {
onSubmit({
verdict,
comments: comment ? [comment] : [],
issues,
});
};
return (
<div className="p-4 bg-gray-50 dark:bg-gray-800 rounded-lg space-y-4">
<h4 className="font-medium text-gray-900 dark:text-white">Submit Review</h4>
{/* Verdict */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Verdict</label>
<div className="flex gap-2">
{(['approved', 'needs_work', 'rejected'] as const).map(v => (
<button
key={v}
onClick={() => setVerdict(v)}
className={`px-3 py-1.5 rounded-lg text-sm font-medium ${
verdict === v
? v === 'approved'
? 'bg-green-500 text-white'
: v === 'needs_work'
? 'bg-yellow-500 text-white'
: 'bg-red-500 text-white'
: 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
}`}
>
{v.replace('_', ' ')}
</button>
))}
</div>
</div>
{/* Comment */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Comment</label>
<textarea
value={comment}
onChange={(e) => setComment(e.target.value)}
placeholder="Overall feedback..."
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
rows={3}
/>
</div>
{/* Add Issue */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Add Issue</label>
<div className="grid grid-cols-2 gap-2">
<select
value={newIssue.severity || 'minor'}
onChange={(e) => setNewIssue({ ...newIssue, severity: e.target.value as ReviewIssue['severity'] })}
className="px-2 py-1.5 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm"
>
<option value="critical">Critical</option>
<option value="major">Major</option>
<option value="minor">Minor</option>
<option value="suggestion">Suggestion</option>
</select>
<input
type="text"
value={newIssue.file || ''}
onChange={(e) => setNewIssue({ ...newIssue, file: e.target.value })}
placeholder="File path"
className="px-2 py-1.5 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm"
/>
<input
type="number"
value={newIssue.line || ''}
onChange={(e) => setNewIssue({ ...newIssue, line: parseInt(e.target.value) || undefined })}
placeholder="Line"
className="px-2 py-1.5 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm"
/>
<input
type="text"
value={newIssue.description || ''}
onChange={(e) => setNewIssue({ ...newIssue, description: e.target.value })}
placeholder="Issue description"
className="px-2 py-1.5 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm"
/>
</div>
<input
type="text"
value={newIssue.suggestion || ''}
onChange={(e) => setNewIssue({ ...newIssue, suggestion: e.target.value })}
placeholder="Suggested fix (optional)"
className="w-full mt-2 px-2 py-1.5 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm"
/>
<button
onClick={handleAddIssue}
disabled={!newIssue.description}
className="mt-2 px-3 py-1.5 text-sm bg-gray-200 dark:bg-gray-700 rounded hover:bg-gray-300 dark:hover:bg-gray-600 disabled:opacity-50"
>
Add Issue
</button>
</div>
{/* Issues List */}
{issues.length > 0 && (
<div className="space-y-1">
{issues.map((issue, idx) => (
<div key={idx} className="flex items-center gap-2 text-sm p-2 bg-white dark:bg-gray-900 rounded">
<span className="px-1.5 py-0.5 rounded text-xs bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300">
{issue.severity}
</span>
<span className="flex-1 truncate">{issue.description}</span>
<button
onClick={() => setIssues(issues.filter((_, i) => i !== idx))}
className="text-gray-400 hover:text-red-500"
>
<XCircle className="w-4 h-4" />
</button>
</div>
))}
</div>
)}
{/* Actions */}
<div className="flex gap-2">
<button
onClick={handleSubmit}
className="flex-1 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center justify-center gap-2"
>
<Send className="w-4 h-4" />
Submit Review
</button>
<button
onClick={onCancel}
className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
>
Cancel
</button>
</div>
</div>
);
}
// === Main Component ===
interface DevQALoopPanelProps {
loop: DevQALoopType;
teamId: string;
developerName: string;
reviewerName: string;
taskTitle: string;
}
export function DevQALoopPanel({ loop, teamId, developerName, reviewerName, taskTitle }: DevQALoopPanelProps) {
const [expandedFeedback, setExpandedFeedback] = useState<number | null>(null);
const [showReviewForm, setShowReviewForm] = useState(false);
const { submitReview, updateLoopState } = useTeamStore();
const stateConfig = {
idle: { color: 'gray', icon: <Clock className="w-5 h-5" />, label: 'Idle' },
developing: { color: 'blue', icon: <FileCode className="w-5 h-5" />, label: 'Developing' },
reviewing: { color: 'yellow', icon: <RefreshCw className="w-5 h-5" />, label: 'Reviewing' },
revising: { color: 'orange', icon: <Bug className="w-5 h-5" />, label: 'Revising' },
approved: { color: 'green', icon: <CheckCircle className="w-5 h-5" />, label: 'Approved' },
escalated: { color: 'red', icon: <AlertOctagon className="w-5 h-5" />, label: 'Escalated' },
};
const config = stateConfig[loop.state];
const handleSubmitReview = async (feedback: Omit<ReviewFeedback, 'reviewedAt' | 'reviewerId'>) => {
await submitReview(teamId, loop.id, feedback);
setShowReviewForm(false);
};
const handleCompleteRevision = async () => {
await updateLoopState(teamId, loop.id, 'reviewing');
};
return (
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
{/* Header */}
<div className={`px-4 py-3 bg-${config.color}-50 dark:bg-${config.color}-900/20 border-b border-${config.color}-200 dark:border-${config.color}-800`}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className={`text-${config.color}-500`}>{config.icon}</div>
<div>
<h3 className="font-semibold text-gray-900 dark:text-white">DevQA Loop</h3>
<p className="text-sm text-gray-500 dark:text-gray-400">{taskTitle}</p>
</div>
</div>
<div className="flex items-center gap-2">
<span className={`px-2 py-1 rounded text-xs font-medium bg-${config.color}-100 text-${config.color}-700 dark:bg-${config.color}-900/30 dark:text-${config.color}-300`}>
{config.label}
</span>
<span className="text-sm text-gray-500 dark:text-gray-400">
Iteration {loop.iterationCount + 1}/{loop.maxIterations}
</span>
</div>
</div>
</div>
{/* Flow Visualization */}
<div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${
['developing', 'revising'].includes(loop.state) ? 'bg-blue-500 text-white' : 'bg-gray-200 dark:bg-gray-700'
}`}>
<FileCode className="w-4 h-4" />
</div>
<div className="text-sm">
<div className="font-medium text-gray-900 dark:text-white">{developerName}</div>
<div className="text-xs text-gray-500">Developer</div>
</div>
</div>
<div className="flex-1 mx-4 flex items-center">
<div className="flex-1 h-0.5 bg-gray-200 dark:bg-gray-700" />
<RefreshCw className={`w-5 h-5 mx-2 ${loop.state === 'reviewing' ? 'text-yellow-500 animate-spin' : 'text-gray-400'}`} />
<div className="flex-1 h-0.5 bg-gray-200 dark:bg-gray-700" />
</div>
<div className="flex items-center gap-2">
<div className="text-sm text-right">
<div className="font-medium text-gray-900 dark:text-white">{reviewerName}</div>
<div className="text-xs text-gray-500">QA Reviewer</div>
</div>
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${
loop.state === 'reviewing' ? 'bg-yellow-500 text-white' : 'bg-gray-200 dark:bg-gray-700'
}`}>
<Bug className="w-4 h-4" />
</div>
</div>
</div>
</div>
{/* Progress Bar */}
<div className="px-4 py-2 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-1">
{Array.from({ length: loop.maxIterations }).map((_, i) => (
<div
key={i}
className={`flex-1 h-2 rounded ${
i < loop.iterationCount
? 'bg-yellow-400'
: i === loop.iterationCount && ['developing', 'reviewing', 'revising'].includes(loop.state)
? 'bg-blue-400'
: 'bg-gray-200 dark:bg-gray-700'
}`}
/>
))}
</div>
</div>
{/* Feedback History */}
<div className="p-4 space-y-3 max-h-64 overflow-y-auto">
<h4 className="text-sm font-medium text-gray-700 dark:text-gray-300">Feedback History</h4>
{loop.feedbackHistory.length === 0 ? (
<div className="text-sm text-gray-500 dark:text-gray-400 text-center py-4">
No feedback yet. First review pending.
</div>
) : (
loop.feedbackHistory.map((feedback, idx) => (
<FeedbackItem
key={idx}
feedback={feedback}
iteration={idx + 1}
isExpanded={expandedFeedback === idx}
onToggle={() => setExpandedFeedback(expandedFeedback === idx ? null : idx)}
/>
))
)}
</div>
{/* Actions */}
<div className="p-4 border-t border-gray-200 dark:border-gray-700">
{loop.state === 'escalated' ? (
<div className="p-3 bg-red-50 dark:bg-red-900/20 rounded-lg text-center">
<AlertOctagon className="w-6 h-6 mx-auto mb-2 text-red-500" />
<p className="text-sm text-red-700 dark:text-red-300">
Maximum iterations reached. Human intervention required.
</p>
</div>
) : loop.state === 'approved' ? (
<div className="p-3 bg-green-50 dark:bg-green-900/20 rounded-lg text-center">
<CheckCircle className="w-6 h-6 mx-auto mb-2 text-green-500" />
<p className="text-sm text-green-700 dark:text-green-300">
Task approved and completed!
</p>
</div>
) : loop.state === 'reviewing' && !showReviewForm ? (
<button
onClick={() => setShowReviewForm(true)}
className="w-full px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 flex items-center justify-center gap-2"
>
<RefreshCw className="w-4 h-4" />
Submit Review
</button>
) : loop.state === 'revising' ? (
<button
onClick={handleCompleteRevision}
className="w-full px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center justify-center gap-2"
>
<CheckCircle className="w-4 h-4" />
Complete Revision
</button>
) : showReviewForm ? (
<ReviewForm
loopId={loop.id}
teamId={teamId}
onSubmit={handleSubmitReview}
onCancel={() => setShowReviewForm(false)}
/>
) : null}
</div>
</div>
);
}
export default DevQALoopPanel;

View File

@@ -1,25 +1,22 @@
import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
Users, Bot, Zap, Layers, Package,
Bot, Zap, Package,
Search, Sparkles, ChevronRight, X
} from 'lucide-react';
import { CloneManager } from './CloneManager';
import { TeamList } from './TeamList';
import { useConfigStore } from '../store/configStore';
import { containerVariants, defaultTransition } from '../lib/animations';
export type MainViewType = 'chat' | 'automation' | 'team' | 'swarm' | 'skills';
export type MainViewType = 'chat' | 'automation' | 'skills';
interface SidebarProps {
onOpenSettings?: () => void;
onMainViewChange?: (view: MainViewType) => void;
selectedTeamId?: string;
onSelectTeam?: (teamId: string) => void;
onNewChat?: () => void;
}
type Tab = 'chat' | 'clones' | 'automation' | 'team' | 'swarm' | 'skills';
type Tab = 'chat' | 'clones' | 'automation' | 'skills';
// 导航项配置 - WorkBuddy 风格
const NAV_ITEMS: {
@@ -31,15 +28,11 @@ const NAV_ITEMS: {
{ key: 'clones', label: '分身', icon: Bot },
{ key: 'automation', label: '自动化', icon: Zap, mainView: 'automation' },
{ key: 'skills', label: '技能', icon: Package, mainView: 'skills' },
{ key: 'team', label: '团队', icon: Users, mainView: 'team' },
{ key: 'swarm', label: '协作', icon: Layers, mainView: 'swarm' },
];
export function Sidebar({
onOpenSettings,
onMainViewChange,
selectedTeamId,
onSelectTeam,
onNewChat
}: SidebarProps) {
const [activeTab, setActiveTab] = useState<Tab>('clones');
@@ -55,12 +48,6 @@ export function Sidebar({
}
};
const handleSelectTeam = (teamId: string) => {
onSelectTeam?.(teamId);
setActiveTab('team');
onMainViewChange?.('team');
};
return (
<aside className="w-64 bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-700 flex flex-col flex-shrink-0">
{/* 搜索框 */}
@@ -123,7 +110,7 @@ export function Sidebar({
{/* 分隔线 */}
<div className="my-3 mx-3 border-t border-gray-100 dark:border-gray-800" />
{/* 内容区域 - 只显示分身、团队、协作的内容,自动化和技能在主内容区显示 */}
{/* 内容区域 - 只显示分身内容,自动化和技能在主内容区显示 */}
<div className="flex-1 overflow-hidden">
<AnimatePresence mode="wait">
<motion.div
@@ -136,13 +123,7 @@ export function Sidebar({
className="h-full overflow-y-auto"
>
{activeTab === 'clones' && <CloneManager />}
{/* skillsautomation 和 swarm 不在侧边栏显示内容,由主内容区显示 */}
{activeTab === 'team' && (
<TeamList
selectedTeamId={selectedTeamId}
onSelectTeam={handleSelectTeam}
/>
)}
{/* skillsautomation 不在侧边栏显示内容,由主内容区显示 */}
</motion.div>
</AnimatePresence>
</div>

View File

@@ -1,590 +0,0 @@
/**
* SwarmDashboard - Multi-Agent Collaboration Task Dashboard
*
* Visualizes swarm tasks, multi-agent collaboration) with real-time
* status updates, task history, and manual trigger functionality.
*
* Part of ZCLAW L4 Self-Evolution capability.
*/
import { useState, useEffect, useCallback, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
Users,
Play,
CheckCircle,
XCircle,
Clock,
ChevronDown,
ChevronRight,
Layers,
GitBranch,
MessageSquare,
RefreshCw,
Plus,
History,
Sparkles,
} from 'lucide-react';
import {
AgentSwarm,
type SwarmTask,
type Subtask,
type SwarmTaskStatus,
type CommunicationStyle,
} from '../lib/agent-swarm';
import { useAgentStore } from '../store/agentStore';
// === Types ===
interface SwarmDashboardProps {
className?: string;
onTaskSelect?: (task: SwarmTask) => void;
}
type FilterType = 'all' | 'active' | 'completed' | 'failed';
// === Status Config ===
const TASK_STATUS_CONFIG: Record<SwarmTaskStatus, { label: string; className: string; dotClass: string; icon: typeof CheckCircle }> = {
planning: {
label: '规划中',
className: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',
dotClass: 'bg-purple-500',
icon: Layers,
},
executing: {
label: '执行中',
className: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
dotClass: 'bg-blue-500 animate-pulse',
icon: Play,
},
aggregating: {
label: '汇总中',
className: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-400',
dotClass: 'bg-cyan-500 animate-pulse',
icon: RefreshCw,
},
done: {
label: '已完成',
className: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
dotClass: 'bg-green-500',
icon: CheckCircle,
},
failed: {
label: '失败',
className: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
dotClass: 'bg-red-500',
icon: XCircle,
},
};
const SUBTASK_STATUS_CONFIG: Record<string, { label: string; dotClass: string }> = {
pending: { label: '待执行', dotClass: 'bg-gray-400' },
running: { label: '执行中', dotClass: 'bg-blue-500 animate-pulse' },
done: { label: '完成', dotClass: 'bg-green-500' },
failed: { label: '失败', dotClass: 'bg-red-500' },
};
const COMMUNICATION_STYLE_CONFIG: Record<CommunicationStyle, { label: string; icon: typeof Users; description: string }> = {
sequential: {
label: '顺序执行',
icon: GitBranch,
description: '每个 Agent 依次处理,输出传递给下一个',
},
parallel: {
label: '并行执行',
icon: Layers,
description: '多个 Agent 同时处理不同子任务',
},
debate: {
label: '辩论模式',
icon: MessageSquare,
description: '多个 Agent 提供观点,协调者综合',
},
};
// === Components ===
function TaskStatusBadge({ status }: { status: SwarmTaskStatus }) {
const config = TASK_STATUS_CONFIG[status];
const Icon = config.icon;
return (
<span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${config.className}`}>
<Icon className="w-3 h-3" />
{config.label}
</span>
);
}
function SubtaskStatusDot({ status }: { status: string }) {
const config = SUBTASK_STATUS_CONFIG[status] || SUBTASK_STATUS_CONFIG.pending;
return <span className={`w-2 h-2 rounded-full ${config.dotClass}`} title={config.label} />;
}
function CommunicationStyleBadge({ style }: { style: CommunicationStyle }) {
const config = COMMUNICATION_STYLE_CONFIG[style];
const Icon = config.icon;
return (
<span
className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
title={config.description}
>
<Icon className="w-3 h-3" />
{config.label}
</span>
);
}
function SubtaskItem({
subtask,
agentName,
isExpanded,
onToggle,
}: {
subtask: Subtask;
agentName: string;
isExpanded: boolean;
onToggle: () => void;
}) {
const duration = useMemo(() => {
if (!subtask.startedAt) return null;
const start = new Date(subtask.startedAt).getTime();
const end = subtask.completedAt ? new Date(subtask.completedAt).getTime() : Date.now();
return Math.round((end - start) / 1000);
}, [subtask.startedAt, subtask.completedAt]);
return (
<div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
<button
onClick={onToggle}
className="w-full flex items-center gap-3 px-3 py-2 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors text-left"
>
<SubtaskStatusDot status={subtask.status} />
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
{subtask.description}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400">
: {agentName}
{duration !== null && <span className="ml-2">· {duration}s</span>}
</div>
</div>
{isExpanded ? (
<ChevronDown className="w-4 h-4 text-gray-400" />
) : (
<ChevronRight className="w-4 h-4 text-gray-400" />
)}
</button>
<AnimatePresence>
{isExpanded && subtask.result && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="border-t border-gray-200 dark:border-gray-700"
>
<div className="p-3 text-sm text-gray-600 dark:text-gray-300 whitespace-pre-wrap max-h-40 overflow-y-auto">
{subtask.result}
</div>
</motion.div>
)}
</AnimatePresence>
{subtask.error && (
<div className="px-3 py-2 bg-red-50 dark:bg-red-900/20 border-t border-gray-200 dark:border-gray-700">
<p className="text-xs text-red-600 dark:text-red-400">{subtask.error}</p>
</div>
)}
</div>
);
}
function TaskCard({
task,
isSelected,
onSelect,
}: {
task: SwarmTask;
isSelected: boolean;
onSelect: () => void;
}) {
const [expandedSubtasks, setExpandedSubtasks] = useState<Set<string>>(new Set());
const { clones } = useAgentStore();
const toggleSubtask = useCallback((subtaskId: string) => {
setExpandedSubtasks((prev) => {
const next = new Set(prev);
if (next.has(subtaskId)) {
next.delete(subtaskId);
} else {
next.add(subtaskId);
}
return next;
});
}, []);
const completedCount = task.subtasks.filter((s) => s.status === 'done').length;
const totalDuration = useMemo(() => {
if (!task.completedAt) return null;
const start = new Date(task.createdAt).getTime();
const end = new Date(task.completedAt).getTime();
return Math.round((end - start) / 1000);
}, [task.createdAt, task.completedAt]);
const getAgentName = (agentId: string) => {
const agent = clones.find((a) => a.id === agentId);
return agent?.name || agentId;
};
return (
<div
className={`border rounded-lg overflow-hidden transition-all ${
isSelected
? 'border-orange-500 dark:border-orange-400 ring-2 ring-orange-500/20'
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
>
<button
onClick={onSelect}
className="w-full p-4 text-left hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors"
>
<div className="flex items-start justify-between gap-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<TaskStatusBadge status={task.status} />
<CommunicationStyleBadge style={task.communicationStyle} />
</div>
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
{task.description}
</h3>
<div className="flex items-center gap-3 mt-1 text-xs text-gray-500 dark:text-gray-400">
<span className="flex items-center gap-1">
<Users className="w-3 h-3" />
{completedCount}/{task.subtasks.length}
</span>
{totalDuration !== null && (
<span className="flex items-center gap-1">
<Clock className="w-3 h-3" />
{totalDuration}s
</span>
)}
<span>{new Date(task.createdAt).toLocaleString('zh-CN')}</span>
</div>
</div>
{isSelected ? (
<ChevronDown className="w-4 h-4 text-gray-400 flex-shrink-0" />
) : (
<ChevronRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
)}
</div>
</button>
<AnimatePresence>
{isSelected && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="border-t border-gray-200 dark:border-gray-700"
>
<div className="p-4 space-y-3">
<h4 className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
</h4>
<div className="space-y-2">
{task.subtasks.map((subtask) => (
<SubtaskItem
key={subtask.id}
subtask={subtask}
agentName={getAgentName(subtask.assignedTo)}
isExpanded={expandedSubtasks.has(subtask.id)}
onToggle={() => toggleSubtask(subtask.id)}
/>
))}
</div>
{task.finalResult && (
<div className="mt-4 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
<h4 className="text-xs font-medium text-green-700 dark:text-green-400 mb-1">
</h4>
<p className="text-sm text-green-600 dark:text-green-300 whitespace-pre-wrap">
{task.finalResult}
</p>
</div>
)}
</div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
function CreateTaskForm({
onSubmit,
onCancel,
}: {
onSubmit: (description: string, style: CommunicationStyle) => void;
onCancel: () => void;
}) {
const [description, setDescription] = useState('');
const [style, setStyle] = useState<CommunicationStyle>('sequential');
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (description.trim()) {
onSubmit(description.trim(), style);
}
};
return (
<form onSubmit={handleSubmit} className="p-4 bg-gray-50 dark:bg-gray-800/50 rounded-lg space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="描述需要协作完成的任务..."
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-orange-500 focus:border-transparent text-sm"
rows={3}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
</label>
<div className="grid grid-cols-3 gap-2">
{(Object.keys(COMMUNICATION_STYLE_CONFIG) as CommunicationStyle[]).map((s) => {
const config = COMMUNICATION_STYLE_CONFIG[s];
const Icon = config.icon;
return (
<button
key={s}
type="button"
onClick={() => setStyle(s)}
className={`flex flex-col items-center gap-1 p-2 rounded-lg border transition-all ${
style === s
? 'border-orange-500 bg-orange-50 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400'
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 text-gray-600 dark:text-gray-400'
}`}
>
<Icon className="w-4 h-4" />
<span className="text-xs">{config.label}</span>
</button>
);
})}
</div>
</div>
<div className="flex justify-end gap-2">
<button
type="button"
onClick={onCancel}
className="px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
>
</button>
<button
type="submit"
disabled={!description.trim()}
className="px-4 py-1.5 text-sm bg-orange-500 hover:bg-orange-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white rounded-lg transition-colors flex items-center gap-1.5"
>
<Sparkles className="w-4 h-4" />
</button>
</div>
</form>
);
}
// === Main Component ===
export function SwarmDashboard({ className = '', onTaskSelect }: SwarmDashboardProps) {
const [swarm] = useState(() => new AgentSwarm());
const [tasks, setTasks] = useState<SwarmTask[]>([]);
const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);
const [filter, setFilter] = useState<FilterType>('all');
const [showCreateForm, setShowCreateForm] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
// Load tasks from swarm history
useEffect(() => {
const history = swarm.getHistory();
setTasks([...history].reverse()); // Most recent first
}, [swarm]);
const filteredTasks = useMemo(() => {
switch (filter) {
case 'active':
return tasks.filter((t) => ['planning', 'executing', 'aggregating'].includes(t.status));
case 'completed':
return tasks.filter((t) => t.status === 'done');
case 'failed':
return tasks.filter((t) => t.status === 'failed');
default:
return tasks;
}
}, [tasks, filter]);
const stats = useMemo(() => {
const active = tasks.filter((t) => ['planning', 'executing', 'aggregating'].includes(t.status)).length;
const completed = tasks.filter((t) => t.status === 'done').length;
const failed = tasks.filter((t) => t.status === 'failed').length;
return { total: tasks.length, active, completed, failed };
}, [tasks]);
const handleRefresh = useCallback(async () => {
setIsRefreshing(true);
// Simulate refresh delay
await new Promise((resolve) => setTimeout(resolve, 500));
const history = swarm.getHistory();
setTasks([...history].reverse());
setIsRefreshing(false);
}, [swarm]);
const handleCreateTask = useCallback(
(description: string, style: CommunicationStyle) => {
const task = swarm.createTask(description, { communicationStyle: style });
setTasks((prev) => [task, ...prev]);
setSelectedTaskId(task.id);
setShowCreateForm(false);
onTaskSelect?.(task);
// Note: Actual execution should be triggered via chatStore.dispatchSwarmTask
console.log('[SwarmDashboard] Task created:', task.id, 'Style:', style);
},
[swarm, onTaskSelect]
);
const handleSelectTask = useCallback(
(taskId: string) => {
setSelectedTaskId((prev) => (prev === taskId ? null : taskId));
const task = tasks.find((t) => t.id === taskId);
if (task && selectedTaskId !== taskId) {
onTaskSelect?.(task);
}
},
[tasks, onTaskSelect, selectedTaskId]
);
return (
<div className={`flex flex-col h-full ${className}`}>
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2">
<Users className="w-5 h-5 text-orange-500" />
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100"></h2>
</div>
<div className="flex items-center gap-2">
<button
onClick={handleRefresh}
disabled={isRefreshing}
className="p-1.5 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 disabled:opacity-50"
title="刷新"
>
<RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
</button>
<button
onClick={() => setShowCreateForm((prev) => !prev)}
className="flex items-center gap-1 px-3 py-1.5 text-sm bg-orange-500 hover:bg-orange-600 text-white rounded-lg transition-colors"
>
<Plus className="w-4 h-4" />
</button>
</div>
</div>
{/* Stats Bar */}
<div className="flex items-center gap-4 px-4 py-2 bg-gray-50 dark:bg-gray-800/50 border-b border-gray-200 dark:border-gray-700 text-xs">
<span className="text-gray-500 dark:text-gray-400">
: <span className="font-medium text-gray-900 dark:text-gray-100">{stats.total}</span>
</span>
<span className="text-blue-600 dark:text-blue-400">
: <span className="font-medium">{stats.active}</span>
</span>
<span className="text-green-600 dark:text-green-400">
: <span className="font-medium">{stats.completed}</span>
</span>
{stats.failed > 0 && (
<span className="text-red-600 dark:text-red-400">
: <span className="font-medium">{stats.failed}</span>
</span>
)}
</div>
{/* Filter Tabs */}
<div className="flex gap-1 px-4 py-2 border-b border-gray-200 dark:border-gray-700">
{(['all', 'active', 'completed', 'failed'] as FilterType[]).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-1 text-xs rounded-full transition-colors ${
filter === f
? 'bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-400'
: 'text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800'
}`}
>
{f === 'all' ? '全部' : f === 'active' ? '活跃' : f === 'completed' ? '已完成' : '失败'}
</button>
))}
</div>
{/* Create Form */}
<AnimatePresence>
{showCreateForm && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="border-b border-gray-200 dark:border-gray-700 overflow-hidden"
>
<CreateTaskForm
onSubmit={handleCreateTask}
onCancel={() => setShowCreateForm(false)}
/>
</motion.div>
)}
</AnimatePresence>
{/* Task List */}
<div className="flex-1 overflow-y-auto p-4 space-y-3">
{filteredTasks.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full text-gray-500 dark:text-gray-400">
<History className="w-8 h-8 mb-2 opacity-50" />
<p className="text-sm">
{filter === 'all'
? '暂无协作任务'
: filter === 'active'
? '暂无活跃任务'
: filter === 'completed'
? '暂无已完成任务'
: '暂无失败任务'}
</p>
<button
onClick={() => setShowCreateForm(true)}
className="mt-2 text-orange-500 hover:text-orange-600 text-sm"
>
</button>
</div>
) : (
filteredTasks.map((task) => (
<TaskCard
key={task.id}
task={task}
isSelected={selectedTaskId === task.id}
onSelect={() => handleSelectTask(task.id)}
/>
))
)}
</div>
</div>
);
}
export default SwarmDashboard;

View File

@@ -1,401 +0,0 @@
/**
* TeamCollaborationView - Real-time Team Collaboration Status
*
* Displays live collaboration events, member status, task progress,
* and team metrics in a unified dashboard view.
*
* @module components/TeamCollaborationView
*/
import { useState, useEffect, useRef } from 'react';
import { useTeamStore } from '../store/teamStore';
import type { Team, TeamMember, TeamTask, CollaborationEvent } from '../types/team';
import {
Activity, Users, CheckCircle, AlertTriangle, Play,
ArrowRight, GitBranch, MessageSquare, FileCode, Bot, Zap,
TrendingUp, TrendingDown, Minus, Circle,
} from 'lucide-react';
// === Sub-Components ===
interface EventFeedItemProps {
event: CollaborationEvent;
team: Team;
}
function EventFeedItem({ event, team }: EventFeedItemProps) {
const sourceMember = team.members.find(m => m.agentId === event.sourceAgentId);
const eventIcons: Record<CollaborationEvent['type'], React.ReactNode> = {
task_assigned: <ArrowRight className="w-4 h-4 text-blue-500" />,
task_started: <Play className="w-4 h-4 text-green-500" />,
task_completed: <CheckCircle className="w-4 h-4 text-green-600" />,
review_requested: <MessageSquare className="w-4 h-4 text-yellow-500" />,
review_submitted: <FileCode className="w-4 h-4 text-purple-500" />,
loop_state_change: <RefreshCw className="w-4 h-4 text-orange-500" />,
member_status_change: <Users className="w-4 h-4 text-gray-500" />,
};
const formatTime = (timestamp: string) => {
const diff = Date.now() - new Date(timestamp).getTime();
if (diff < 60000) return 'Just now';
if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
return new Date(timestamp).toLocaleTimeString();
};
return (
<div className="flex items-start gap-3 p-3 hover:bg-gray-50 dark:hover:bg-gray-800 rounded-lg">
<div className="mt-0.5">{eventIcons[event.type]}</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium text-gray-900 dark:text-white text-sm">
{sourceMember?.name || 'System'}
</span>
<span className="text-xs text-gray-500 dark:text-gray-400">
{event.type.replace(/_/g, ' ')}
</span>
</div>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-0.5 line-clamp-2">
{typeof event.payload.description === 'string'
? event.payload.description
: JSON.stringify(event.payload).slice(0, 100)}
</p>
</div>
<span className="text-xs text-gray-400 whitespace-nowrap">
{formatTime(event.timestamp)}
</span>
</div>
);
}
function RefreshCw({ className }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 2v6h-6M3 22v-6h6M21 12A9 9 0 0 0 6 5.3L3 8M3 12a9 9 0 0 0 15 6.7l3-2.7" />
</svg>
);
}
interface MemberStatusBadgeProps {
member: TeamMember;
}
function MemberStatusBadge({ member }: MemberStatusBadgeProps) {
const statusConfig = {
idle: { color: 'bg-gray-400', label: 'Idle' },
running: { color: 'bg-green-500 animate-pulse', label: 'Active' },
paused: { color: 'bg-yellow-500', label: 'Paused' },
error: { color: 'bg-red-500', label: 'Error' },
};
const config = statusConfig[member.status];
return (
<div className="flex items-center gap-2 p-2 rounded-lg bg-gray-50 dark:bg-gray-800">
<div className="relative">
<div className={`w-3 h-3 rounded-full ${config.color}`} />
{member.currentTasks.length > 0 && (
<div className="absolute -top-1 -right-1 w-4 h-4 bg-blue-500 rounded-full flex items-center justify-center">
<span className="text-[10px] text-white font-bold">{member.currentTasks.length}</span>
</div>
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-gray-900 dark:text-white truncate">
{member.name}
</span>
<span className="text-xs text-gray-500">{config.label}</span>
</div>
<div className="mt-1 h-1 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
<div
className="h-full bg-blue-500 transition-all"
style={{ width: `${member.workload}%` }}
/>
</div>
</div>
</div>
);
}
interface TaskProgressCardProps {
task: TeamTask;
assignee?: TeamMember;
}
function TaskProgressCard({ task, assignee }: TaskProgressCardProps) {
const statusConfig: Record<TeamTask['status'], { color: string; icon: React.ReactNode }> = {
pending: { color: 'text-gray-400', icon: <Circle className="w-4 h-4" /> },
assigned: { color: 'text-blue-400', icon: <ArrowRight className="w-4 h-4" /> },
in_progress: { color: 'text-green-500', icon: <Play className="w-4 h-4" /> },
review: { color: 'text-yellow-500', icon: <MessageSquare className="w-4 h-4" /> },
blocked: { color: 'text-red-500', icon: <AlertTriangle className="w-4 h-4" /> },
completed: { color: 'text-green-600', icon: <CheckCircle className="w-4 h-4" /> },
failed: { color: 'text-red-600', icon: <AlertTriangle className="w-4 h-4" /> },
};
const config = statusConfig[task.status];
return (
<div className="p-3 rounded-lg border border-gray-200 dark:border-gray-700">
<div className="flex items-start gap-2">
<div className={config.color}>{config.icon}</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-gray-900 dark:text-white truncate">
{task.title}
</span>
<span className={`text-xs px-1.5 py-0.5 rounded ${
task.priority === 'critical' ? 'bg-red-100 text-red-700' :
task.priority === 'high' ? 'bg-orange-100 text-orange-700' :
task.priority === 'medium' ? 'bg-yellow-100 text-yellow-700' :
'bg-gray-100 text-gray-700'
}`}>
{task.priority}
</span>
</div>
<div className="mt-1 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
<span>{task.type}</span>
{assignee && (
<>
<span>·</span>
<span>{assignee.name}</span>
</>
)}
</div>
</div>
</div>
</div>
);
}
interface MetricCardProps {
label: string;
value: number | string;
trend?: 'up' | 'down' | 'neutral';
format?: 'number' | 'percent' | 'time';
}
function MetricCard({ label, value, trend, format = 'number' }: MetricCardProps) {
const formattedValue = format === 'percent' ? `${value}%` :
format === 'time' ? `${Math.floor((value as number) / 60000)}m` :
value;
return (
<div className="p-3 rounded-lg bg-gray-50 dark:bg-gray-800">
<div className="flex items-center justify-between">
<span className="text-xs text-gray-500 dark:text-gray-400">{label}</span>
{trend && (
trend === 'up' ? <TrendingUp className="w-3 h-3 text-green-500" /> :
trend === 'down' ? <TrendingDown className="w-3 h-3 text-red-500" /> :
<Minus className="w-3 h-3 text-gray-400" />
)}
</div>
<div className="mt-1 text-xl font-bold text-gray-900 dark:text-white">
{formattedValue}
</div>
</div>
);
}
// === Main Component ===
interface TeamCollaborationViewProps {
teamId: string;
compact?: boolean;
}
export function TeamCollaborationView({ teamId, compact = false }: TeamCollaborationViewProps) {
const { teams, recentEvents, metrics, activeTeam } = useTeamStore();
const [autoScroll, setAutoScroll] = useState(true);
const eventFeedRef = useRef<HTMLDivElement>(null);
const team = teams.find(t => t.id === teamId) || activeTeam;
useEffect(() => {
if (autoScroll && eventFeedRef.current) {
eventFeedRef.current.scrollTop = 0;
}
}, [recentEvents, autoScroll]);
if (!team) {
return (
<div className="p-6 text-center text-gray-500 dark:text-gray-400">
<Users className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
<p>No team selected</p>
</div>
);
}
const tasksByStatus = {
active: team.tasks.filter(t => ['in_progress', 'review'].includes(t.status)),
pending: team.tasks.filter(t => ['pending', 'assigned'].includes(t.status)),
completed: team.tasks.filter(t => t.status === 'completed'),
blocked: team.tasks.filter(t => ['blocked', 'failed'].includes(t.status)),
};
if (compact) {
return (
<div className="p-4 space-y-4">
{/* Quick Stats */}
<div className="grid grid-cols-4 gap-2">
<div className="text-center">
<div className="text-2xl font-bold text-blue-500">{tasksByStatus.active.length}</div>
<div className="text-xs text-gray-500">Active</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-gray-400">{tasksByStatus.pending.length}</div>
<div className="text-xs text-gray-500">Pending</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-green-500">{tasksByStatus.completed.length}</div>
<div className="text-xs text-gray-500">Done</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-red-500">{tasksByStatus.blocked.length}</div>
<div className="text-xs text-gray-500">Blocked</div>
</div>
</div>
{/* Member Status */}
<div className="grid grid-cols-2 gap-2">
{team.members.slice(0, 4).map(member => (
<MemberStatusBadge key={member.id} member={member} />
))}
</div>
</div>
);
}
return (
<div className="h-full flex flex-col bg-white dark:bg-gray-900">
{/* Header */}
<div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Users className="w-5 h-5 text-blue-500" />
<h3 className="font-semibold text-gray-900 dark:text-white">{team.name}</h3>
<span className={`px-2 py-0.5 rounded text-xs font-medium ${
team.status === 'active' ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300' :
team.status === 'paused' ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300' :
'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300'
}`}>
{team.status}
</span>
</div>
<div className="flex items-center gap-2 text-sm text-gray-500">
<GitBranch className="w-4 h-4" />
<span>{team.pattern}</span>
</div>
</div>
</div>
{/* Metrics */}
{metrics && (
<div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<div className="grid grid-cols-5 gap-3">
<MetricCard label="Completed" value={metrics.tasksCompleted} />
<MetricCard label="Pass Rate" value={metrics.passRate.toFixed(0)} format="percent" trend={metrics.passRate > 80 ? 'up' : 'down'} />
<MetricCard label="Avg Time" value={metrics.avgCompletionTime} format="time" />
<MetricCard label="Iterations" value={metrics.avgIterations.toFixed(1)} trend={metrics.avgIterations < 2 ? 'up' : 'neutral'} />
<MetricCard label="Efficiency" value={metrics.efficiency.toFixed(0)} format="percent" trend={metrics.efficiency > 70 ? 'up' : 'down'} />
</div>
</div>
)}
{/* Main Content */}
<div className="flex-1 flex overflow-hidden">
{/* Left: Members & Tasks */}
<div className="w-1/2 border-r border-gray-200 dark:border-gray-700 flex flex-col overflow-hidden">
{/* Members */}
<div className="p-4 border-b border-gray-200 dark:border-gray-700">
<h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3 flex items-center gap-2">
<Bot className="w-4 h-4" />
Team Members ({team.members.length})
</h4>
<div className="space-y-2 max-h-32 overflow-y-auto">
{team.members.map(member => (
<MemberStatusBadge key={member.id} member={member} />
))}
</div>
</div>
{/* Tasks */}
<div className="flex-1 p-4 overflow-y-auto">
<h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3 flex items-center gap-2">
<Activity className="w-4 h-4" />
Active Tasks ({tasksByStatus.active.length})
</h4>
<div className="space-y-2">
{tasksByStatus.active.map(task => (
<TaskProgressCard
key={task.id}
task={task}
assignee={team.members.find(m => m.id === task.assigneeId)}
/>
))}
{tasksByStatus.active.length === 0 && (
<p className="text-sm text-gray-500 dark:text-gray-400 text-center py-4">
No active tasks
</p>
)}
</div>
{tasksByStatus.blocked.length > 0 && (
<>
<h4 className="text-sm font-medium text-red-600 dark:text-red-400 mt-4 mb-2 flex items-center gap-2">
<AlertTriangle className="w-4 h-4" />
Blocked ({tasksByStatus.blocked.length})
</h4>
<div className="space-y-2">
{tasksByStatus.blocked.map(task => (
<TaskProgressCard
key={task.id}
task={task}
assignee={team.members.find(m => m.id === task.assigneeId)}
/>
))}
</div>
</>
)}
</div>
</div>
{/* Right: Event Feed */}
<div className="w-1/2 flex flex-col overflow-hidden">
<div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
<h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2">
<Zap className="w-4 h-4" />
Live Events
</h4>
<label className="flex items-center gap-2 text-xs text-gray-500">
<input
type="checkbox"
checked={autoScroll}
onChange={(e) => setAutoScroll(e.target.checked)}
className="rounded"
/>
Auto-scroll
</label>
</div>
<div ref={eventFeedRef} className="flex-1 overflow-y-auto p-2">
{recentEvents.filter(e => e.teamId === teamId).length === 0 ? (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
<Activity className="w-8 h-8 mx-auto mb-2 text-gray-300 dark:text-gray-600" />
<p className="text-sm">No recent activity</p>
</div>
) : (
recentEvents
.filter(e => e.teamId === teamId)
.map((event, idx) => (
<EventFeedItem key={`${event.timestamp}-${idx}`} event={event} team={team} />
))
)}
</div>
</div>
</div>
</div>
);
}
export default TeamCollaborationView;

View File

@@ -1,294 +0,0 @@
/**
* TeamList - Sidebar Team List Component
*
* Displays a compact list of teams for the sidebar navigation.
*
* @module components/TeamList
*/
import { useEffect, useState } from 'react';
import { useTeamStore } from '../store/teamStore';
import { useAgentStore } from '../store/agentStore';
import { useChatStore } from '../store/chatStore';
import { Users, Plus, Activity, CheckCircle, AlertTriangle, X, Bot } from 'lucide-react';
import type { TeamMemberRole } from '../types/team';
interface TeamListProps {
onSelectTeam?: (teamId: string) => void;
selectedTeamId?: string;
}
export function TeamList({ onSelectTeam, selectedTeamId }: TeamListProps) {
const { teams, loadTeams, setActiveTeam, createTeam, isLoading } = useTeamStore();
const clones = useAgentStore((s) => s.clones);
const { agents } = useChatStore();
const [showCreateModal, setShowCreateModal] = useState(false);
const [teamName, setTeamName] = useState('');
const [teamDescription, setTeamDescription] = useState('');
const [teamPattern, setTeamPattern] = useState<'sequential' | 'parallel' | 'pipeline'>('sequential');
const [selectedAgents, setSelectedAgents] = useState<string[]>([]);
const [isCreating, setIsCreating] = useState(false);
useEffect(() => {
try {
loadTeams();
} catch (err) {
console.error('[TeamList] Failed to load teams:', err);
}
}, [loadTeams]);
const handleSelectTeam = (teamId: string) => {
const team = teams.find(t => t.id === teamId);
if (team) {
setActiveTeam(team);
onSelectTeam?.(teamId);
}
};
const handleCreateTeam = async () => {
if (!teamName.trim() || selectedAgents.length === 0) return;
setIsCreating(true);
try {
const roleAssignments: { agentId: string; role: TeamMemberRole }[] = selectedAgents.map((agentId, index) => ({
agentId,
role: (index === 0 ? 'orchestrator' : index === 1 ? 'reviewer' : 'worker') as TeamMemberRole,
}));
const team = await createTeam({
name: teamName.trim(),
description: teamDescription.trim() || undefined,
pattern: teamPattern,
memberAgents: roleAssignments,
});
if (team) {
setShowCreateModal(false);
setTeamName('');
setTeamDescription('');
setSelectedAgents([]);
setTeamPattern('sequential');
setActiveTeam(team);
onSelectTeam?.(team.id);
}
} finally {
setIsCreating(false);
}
};
const toggleAgentSelection = (agentId: string) => {
setSelectedAgents(prev =>
prev.includes(agentId)
? prev.filter(id => id !== agentId)
: [...prev, agentId]
);
};
const getStatusIcon = (status: string) => {
switch (status) {
case 'active':
return <Activity className="w-3 h-3 text-green-500" />;
case 'paused':
return <AlertTriangle className="w-3 h-3 text-yellow-500" />;
case 'completed':
return <CheckCircle className="w-3 h-3 text-blue-500" />;
default:
return <Activity className="w-3 h-3 text-gray-400" />;
}
};
// Merge clones and agents for display - normalize to common type with defensive checks
const availableAgents: Array<{ id: string; name: string; role?: string }> =
(clones && clones.length > 0)
? clones.map(c => ({ id: c.id, name: c.name, role: c.role }))
: (agents && agents.length > 0)
? agents.map(a => ({
id: a.id,
name: a.name,
role: '默认助手',
}))
: [];
return (
<div className="h-full flex flex-col">
{/* Header */}
<div className="p-3 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between">
<h3 className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
</h3>
<button
onClick={() => setShowCreateModal(true)}
className="p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded transition-colors"
title="创建团队"
>
<Plus className="w-4 h-4 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200" />
</button>
</div>
</div>
{/* Create Team Modal */}
{showCreateModal && (
<div className="absolute inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-80 max-h-[90vh] overflow-y-auto">
<div className="p-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-gray-900 dark:text-white"></h3>
<button
onClick={() => setShowCreateModal(false)}
className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
>
<X className="w-4 h-4 text-gray-400" />
</button>
</div>
</div>
<div className="p-4 space-y-4">
{/* Team Name */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
*
</label>
<input
type="text"
value={teamName}
onChange={(e) => setTeamName(e.target.value)}
placeholder="例如:开发团队 Alpha"
className="w-full px-3 py-2 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-gray-400"
/>
</div>
{/* Team Description */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
</label>
<textarea
value={teamDescription}
onChange={(e) => setTeamDescription(e.target.value)}
placeholder="这个团队将负责什么工作?"
rows={2}
className="w-full px-3 py-2 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-gray-400 resize-none"
/>
</div>
{/* Collaboration Pattern */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
</label>
<select
value={teamPattern}
onChange={(e) => setTeamPattern(e.target.value as typeof teamPattern)}
className="w-full px-3 py-2 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-gray-400"
>
<option value="sequential"></option>
<option value="parallel"></option>
<option value="pipeline">线</option>
</select>
</div>
{/* Agent Selection */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">
( {selectedAgents.length} ) *
</label>
<div className="space-y-2 max-h-40 overflow-y-auto">
{availableAgents.map((agent) => (
<button
key={agent.id}
onClick={() => toggleAgentSelection(agent.id)}
className={`w-full p-2 rounded-lg text-left text-sm transition-colors flex items-center gap-2 ${
selectedAgents.includes(agent.id)
? 'bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800'
: 'bg-gray-50 dark:bg-gray-700 border border-transparent hover:bg-gray-100 dark:hover:bg-gray-600'
}`}
>
<div className="w-6 h-6 rounded-full bg-gray-600 flex items-center justify-center text-white text-xs">
<Bot className="w-3 h-3" />
</div>
<span className="text-gray-900 dark:text-white truncate">{agent.name}</span>
{selectedAgents.includes(agent.id) && (
<CheckCircle className="w-4 h-4 text-blue-500 ml-auto" />
)}
</button>
))}
{availableAgents.length === 0 && (
<p className="text-xs text-gray-500 dark:text-gray-400 text-center py-2">
</p>
)}
</div>
</div>
</div>
{/* Footer */}
<div className="p-4 border-t border-gray-200 dark:border-gray-700 flex gap-2">
<button
onClick={() => setShowCreateModal(false)}
className="flex-1 px-4 py-2 text-sm text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
>
</button>
<button
onClick={handleCreateTeam}
disabled={!teamName.trim() || selectedAgents.length === 0 || isCreating}
className="flex-1 px-4 py-2 text-sm text-white bg-gray-700 dark:bg-gray-600 rounded-lg hover:bg-gray-800 dark:hover:bg-gray-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{isCreating ? '创建中...' : '创建'}
</button>
</div>
</div>
</div>
)}
{/* Team List */}
<div className="flex-1 overflow-y-auto">
{isLoading ? (
<div className="p-4 text-center text-gray-400 text-sm">...</div>
) : !Array.isArray(teams) || teams.length === 0 ? (
<div className="p-4 text-center">
<Users className="w-8 h-8 mx-auto mb-2 text-gray-300 dark:text-gray-600" />
<p className="text-xs text-gray-400 dark:text-gray-500">
</p>
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
+
</p>
</div>
) : (
<div className="space-y-1 p-2">
{teams.map((team) => (
<button
key={team.id}
onClick={() => handleSelectTeam(team.id)}
className={`w-full p-2 rounded-lg text-left transition-colors ${
selectedTeamId === team.id
? 'bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800'
: 'hover:bg-gray-100 dark:hover:bg-gray-800'
}`}
>
<div className="flex items-center gap-2">
{getStatusIcon(team.status)}
<span className="text-sm font-medium text-gray-900 dark:text-white truncate">
{team.name}
</span>
</div>
<div className="mt-1 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
<span className="flex items-center gap-1">
<Users className="w-3 h-3" />
{team.members.length}
</span>
<span>·</span>
<span>{team.tasks.length} </span>
</div>
</button>
))}
</div>
)}
</div>
</div>
);
}
export default TeamList;

View File

@@ -1,580 +0,0 @@
/**
* TeamOrchestrator - Multi-Agent Team Orchestration UI
*
* Provides an interface for creating teams, assigning agents,
* managing tasks, and monitoring collaboration workflows.
*
* @module components/TeamOrchestrator
*/
import { useState, useEffect } from 'react';
import { useTeamStore } from '../store/teamStore';
import { useAgentStore } from '../store/agentStore';
import { DevQALoopPanel } from './DevQALoop';
import type {
TeamMember,
TeamTask,
TeamMemberRole,
TaskPriority,
CollaborationPattern,
} from '../types/team';
import {
Users, Plus, Trash2, X,
Bot, Clock, AlertTriangle, CheckCircle,
Play, UserPlus, FileText, RefreshCw,
} from 'lucide-react';
// === Sub-Components ===
interface MemberCardProps {
member: TeamMember;
isSelected: boolean;
onSelect: () => void;
onRoleChange: (role: TeamMemberRole) => void;
onRemove: () => void;
}
function MemberCard({ member, isSelected, onSelect, onRoleChange, onRemove }: MemberCardProps) {
const [showRoleMenu, setShowRoleMenu] = useState(false);
const roleColors: Record<TeamMemberRole, string> = {
orchestrator: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300',
developer: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300',
reviewer: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300',
tester: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300',
architect: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300',
specialist: 'bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-300',
};
const statusColors = {
idle: 'bg-gray-400',
running: 'bg-green-500 animate-pulse',
paused: 'bg-yellow-500',
error: 'bg-red-500',
};
return (
<div
className={`p-3 rounded-lg border cursor-pointer transition-all ${
isSelected
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
onClick={onSelect}
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className={`w-2 h-2 rounded-full ${statusColors[member.status]}`} />
<Bot className="w-4 h-4 text-gray-500" />
<span className="font-medium text-gray-900 dark:text-white">{member.name}</span>
</div>
<div className="flex items-center gap-1">
<button
onClick={(e) => { e.stopPropagation(); setShowRoleMenu(!showRoleMenu); }}
className={`px-2 py-0.5 rounded text-xs font-medium ${roleColors[member.role]}`}
>
{member.role}
</button>
<button
onClick={(e) => { e.stopPropagation(); onRemove(); }}
className="p-1 text-gray-400 hover:text-red-500"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
</div>
{showRoleMenu && (
<div className="mt-2 flex flex-wrap gap-1">
{(['orchestrator', 'developer', 'reviewer', 'tester', 'architect', 'specialist'] as TeamMemberRole[]).map(role => (
<button
key={role}
onClick={(e) => { e.stopPropagation(); onRoleChange(role); setShowRoleMenu(false); }}
className={`px-2 py-0.5 rounded text-xs ${roleColors[role]} hover:opacity-80`}
>
{role}
</button>
))}
</div>
)}
<div className="mt-2 flex items-center gap-3 text-xs text-gray-500 dark:text-gray-400">
<span>Workload: {member.workload}%</span>
<span>Tasks: {member.currentTasks.length}</span>
</div>
</div>
);
}
interface TaskCardProps {
task: TeamTask;
members: TeamMember[];
isSelected: boolean;
onSelect: () => void;
onAssign: (memberId: string) => void;
onStatusChange: (status: TeamTask['status']) => void;
}
function TaskCard({ task, members, isSelected, onSelect, onAssign, onStatusChange: _onStatusChange }: TaskCardProps) {
const [showAssignMenu, setShowAssignMenu] = useState(false);
const priorityColors: Record<TaskPriority, string> = {
critical: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300',
high: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300',
medium: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300',
low: 'bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-300',
};
const statusIcons: Record<TeamTask['status'], React.ReactNode> = {
pending: <Clock className="w-4 h-4 text-gray-400" />,
assigned: <UserPlus className="w-4 h-4 text-blue-400" />,
in_progress: <Play className="w-4 h-4 text-green-400" />,
review: <FileText className="w-4 h-4 text-yellow-400" />,
blocked: <AlertTriangle className="w-4 h-4 text-red-400" />,
completed: <CheckCircle className="w-4 h-4 text-green-500" />,
failed: <X className="w-4 h-4 text-red-500" />,
};
const assignee = members.find(m => m.id === task.assigneeId);
return (
<div
className={`p-3 rounded-lg border cursor-pointer transition-all ${
isSelected
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
onClick={onSelect}
>
<div className="flex items-start justify-between gap-2">
<div className="flex-1">
<div className="flex items-center gap-2">
{statusIcons[task.status]}
<span className="font-medium text-gray-900 dark:text-white">{task.title}</span>
</div>
{task.description && (
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400 line-clamp-2">
{task.description}
</p>
)}
</div>
<span className={`px-2 py-0.5 rounded text-xs font-medium ${priorityColors[task.priority]}`}>
{task.priority}
</span>
</div>
<div className="mt-2 flex items-center justify-between">
<div className="flex items-center gap-2">
<button
onClick={(e) => { e.stopPropagation(); setShowAssignMenu(!showAssignMenu); }}
className={`px-2 py-1 rounded text-xs border ${
assignee
? 'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/30 dark:text-blue-300'
: 'border-gray-200 text-gray-500 hover:border-gray-300 dark:border-gray-700 dark:text-gray-400'
}`}
>
{assignee ? assignee.name : 'Assign...'}
</button>
<span className="text-xs text-gray-400">{task.type}</span>
</div>
{task.estimate && (
<span className="text-xs text-gray-400">{task.estimate}pts</span>
)}
</div>
{showAssignMenu && (
<div className="mt-2 flex flex-wrap gap-1">
{members.map(member => (
<button
key={member.id}
onClick={(e) => { e.stopPropagation(); onAssign(member.id); setShowAssignMenu(false); }}
className="px-2 py-1 rounded text-xs border border-gray-200 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800"
>
{member.name}
</button>
))}
</div>
)}
</div>
);
}
// === Main Component ===
interface TeamOrchestratorProps {
isOpen: boolean;
onClose: () => void;
}
export function TeamOrchestrator({ isOpen, onClose }: TeamOrchestratorProps) {
const [view, setView] = useState<'teams' | 'tasks' | 'members' | 'review'>('teams');
const [isCreating, setIsCreating] = useState(false);
const [newTeamName, setNewTeamName] = useState('');
const [newTeamPattern, setNewTeamPattern] = useState<CollaborationPattern>('sequential');
const {
teams,
activeTeam,
metrics,
error,
selectedTaskId,
selectedMemberId,
loadTeams,
createTeam,
deleteTeam,
setActiveTeam,
addTask,
updateTaskStatus,
assignTask,
addMember,
removeMember,
updateMemberRole,
setSelectedTask,
setSelectedMember,
startDevQALoop,
} = useTeamStore();
const clones = useAgentStore((s) => s.clones);
useEffect(() => {
if (isOpen) {
loadTeams();
}
}, [isOpen, loadTeams]);
const handleCreateTeam = async () => {
if (!newTeamName.trim()) return;
const team = await createTeam({
name: newTeamName.trim(),
pattern: newTeamPattern,
memberAgents: [],
});
if (team) {
setActiveTeam(team);
setNewTeamName('');
setIsCreating(false);
}
};
const handleAddMember = async (agentId: string) => {
if (!activeTeam) return;
await addMember(activeTeam.id, agentId, 'developer');
};
const handleAddTask = async () => {
if (!activeTeam) return;
await addTask({
teamId: activeTeam.id,
title: `Task ${activeTeam.tasks.length + 1}`,
priority: 'medium',
type: 'implementation',
});
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-900 rounded-xl shadow-2xl w-[90vw] h-[85vh] flex flex-col overflow-hidden">
{/* Header */}
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
<div className="flex items-center gap-3">
<Users className="w-6 h-6 text-blue-500" />
<h2 className="text-xl font-bold text-gray-900 dark:text-white">Team Orchestrator</h2>
</div>
<div className="flex items-center gap-2">
{metrics && (
<div className="flex items-center gap-4 mr-4 text-sm text-gray-500 dark:text-gray-400">
<span>Completed: {metrics.tasksCompleted}</span>
<span>Pass Rate: {metrics.passRate.toFixed(0)}%</span>
<span>Efficiency: {metrics.efficiency.toFixed(0)}%</span>
</div>
)}
<button onClick={onClose} className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
</div>
{/* Content */}
<div className="flex-1 flex overflow-hidden">
{/* Sidebar - Team List */}
<div className="w-64 border-r border-gray-200 dark:border-gray-700 p-4 overflow-y-auto">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-gray-900 dark:text-white">Teams</h3>
<button
onClick={() => setIsCreating(true)}
className="p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded"
>
<Plus className="w-4 h-4 text-gray-500" />
</button>
</div>
{isCreating && (
<div className="mb-4 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
<input
type="text"
value={newTeamName}
onChange={(e) => setNewTeamName(e.target.value)}
placeholder="Team name..."
className="w-full px-2 py-1 text-sm border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white"
/>
<select
value={newTeamPattern}
onChange={(e) => setNewTeamPattern(e.target.value as CollaborationPattern)}
className="w-full mt-2 px-2 py-1 text-sm border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white"
>
<option value="sequential">Sequential</option>
<option value="parallel">Parallel</option>
<option value="pipeline">Pipeline</option>
<option value="review_loop">DevQA Loop</option>
</select>
<div className="mt-2 flex gap-2">
<button
onClick={handleCreateTeam}
className="flex-1 px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600"
>
Create
</button>
<button
onClick={() => setIsCreating(false)}
className="flex-1 px-2 py-1 text-xs border rounded hover:bg-gray-100 dark:hover:bg-gray-700"
>
Cancel
</button>
</div>
</div>
)}
<div className="space-y-2">
{teams.map(team => (
<div
key={team.id}
onClick={() => setActiveTeam(team)}
className={`p-3 rounded-lg cursor-pointer transition-all ${
activeTeam?.id === team.id
? 'bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800'
: 'hover:bg-gray-50 dark:hover:bg-gray-800'
}`}
>
<div className="flex items-center justify-between">
<span className="font-medium text-gray-900 dark:text-white">{team.name}</span>
<button
onClick={(e) => { e.stopPropagation(); deleteTeam(team.id); }}
className="p-1 text-gray-400 hover:text-red-500"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
<div className="mt-1 flex items-center gap-2 text-xs text-gray-500">
<Users className="w-3 h-3" />
<span>{team.members.length} members</span>
<span>·</span>
<span>{team.tasks.length} tasks</span>
</div>
<div className="mt-1">
<span className="px-1.5 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 rounded">
{team.pattern}
</span>
</div>
</div>
))}
</div>
</div>
{/* Main Content */}
{activeTeam ? (
<div className="flex-1 flex flex-col overflow-hidden">
{/* View Tabs */}
<div className="px-6 py-3 border-b border-gray-200 dark:border-gray-700 flex items-center gap-4">
<button
onClick={() => setView('tasks')}
className={`px-3 py-1.5 rounded-lg text-sm font-medium ${
view === 'tasks'
? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300'
: 'text-gray-500 hover:text-gray-700 dark:text-gray-400'
}`}
>
Tasks
</button>
<button
onClick={() => setView('members')}
className={`px-3 py-1.5 rounded-lg text-sm font-medium ${
view === 'members'
? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300'
: 'text-gray-500 hover:text-gray-700 dark:text-gray-400'
}`}
>
Members
</button>
<button
onClick={() => setView('review')}
className={`px-3 py-1.5 rounded-lg text-sm font-medium flex items-center gap-1 ${
view === 'review'
? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300'
: 'text-gray-500 hover:text-gray-700 dark:text-gray-400'
}`}
>
<RefreshCw className="w-4 h-4" />
Review
{activeTeam.activeLoops.length > 0 && (
<span className="ml-1 px-1.5 py-0.5 text-xs bg-yellow-200 dark:bg-yellow-800 rounded-full">
{activeTeam.activeLoops.length}
</span>
)}
</button>
</div>
{/* Tasks View */}
{view === 'tasks' && (
<div className="flex-1 p-6 overflow-y-auto">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-gray-900 dark:text-white">Tasks</h3>
<button
onClick={handleAddTask}
className="flex items-center gap-1 px-3 py-1.5 text-sm bg-blue-500 text-white rounded-lg hover:bg-blue-600"
>
<Plus className="w-4 h-4" />
Add Task
</button>
</div>
<div className="space-y-3">
{activeTeam.tasks.length === 0 ? (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
No tasks yet. Click "Add Task" to create one.
</div>
) : (
activeTeam.tasks.map(task => (
<TaskCard
key={task.id}
task={task}
members={activeTeam.members}
isSelected={selectedTaskId === task.id}
onSelect={() => setSelectedTask(task.id)}
onAssign={(memberId) => assignTask(activeTeam.id, task.id, memberId)}
onStatusChange={(status) => updateTaskStatus(activeTeam.id, task.id, status)}
/>
))
)}
</div>
</div>
)}
{/* Members View */}
{view === 'members' && (
<div className="flex-1 p-6 overflow-y-auto">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-gray-900 dark:text-white">Members</h3>
<div className="flex items-center gap-2">
<select
className="px-3 py-1.5 text-sm border rounded-lg dark:bg-gray-800 dark:border-gray-700 dark:text-white"
onChange={(e) => handleAddMember(e.target.value)}
value=""
>
<option value="">Add Agent...</option>
{clones.map(clone => (
<option key={clone.id} value={clone.id}>
{clone.name || clone.nickname || clone.id}
</option>
))}
</select>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
{activeTeam.members.length === 0 ? (
<div className="col-span-2 text-center py-8 text-gray-500 dark:text-gray-400">
No members yet. Select an agent to add.
</div>
) : (
activeTeam.members.map(member => (
<MemberCard
key={member.id}
member={member}
isSelected={selectedMemberId === member.id}
onSelect={() => setSelectedMember(member.id)}
onRoleChange={(role) => updateMemberRole(activeTeam.id, member.id, role)}
onRemove={() => removeMember(activeTeam.id, member.id)}
/>
))
)}
</div>
</div>
)}
{/* Review View - Dev↔QA Loop */}
{view === 'review' && (
<div className="flex-1 p-6 overflow-y-auto">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-gray-900 dark:text-white">DevQA Review Loops</h3>
<button
onClick={async () => {
// Start a new Dev↔QA loop with the first available task and members
if (activeTeam.tasks.length > 0 && activeTeam.members.length >= 2) {
const devMember = activeTeam.members.find(m => m.role === 'developer');
const reviewerMember = activeTeam.members.find(m => m.role === 'reviewer');
if (devMember && reviewerMember) {
const task = activeTeam.tasks.find(t => t.status === 'pending' || t.status === 'in_progress');
if (task) {
await startDevQALoop(activeTeam.id, task.id, devMember.id, reviewerMember.id);
}
}
}
}}
disabled={activeTeam.tasks.length === 0 || activeTeam.members.length < 2}
className="flex items-center gap-1 px-3 py-1.5 text-sm bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 disabled:opacity-50 disabled:cursor-not-allowed"
>
<Plus className="w-4 h-4" />
Start Review Loop
</button>
</div>
{activeTeam.activeLoops.length === 0 ? (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
<RefreshCw className="w-12 h-12 mx-auto mb-4 text-gray-300 dark:text-gray-600" />
<p>No active review loops.</p>
<p className="text-sm mt-2">Add tasks and members, then start a DevQA loop.</p>
</div>
) : (
<div className="space-y-4">
{activeTeam.activeLoops.map(loop => {
const task = activeTeam.tasks.find(t => t.id === loop.taskId);
const developer = activeTeam.members.find(m => m.id === loop.developerId);
const reviewer = activeTeam.members.find(m => m.id === loop.reviewerId);
return (
<DevQALoopPanel
key={loop.id}
loop={loop}
teamId={activeTeam.id}
developerName={developer?.name || 'Unknown Developer'}
reviewerName={reviewer?.name || 'Unknown Reviewer'}
taskTitle={task?.title || 'Unknown Task'}
/>
);
})}
</div>
)}
</div>
)}
</div>
) : (
<div className="flex-1 flex items-center justify-center text-gray-500 dark:text-gray-400">
<div className="text-center">
<Users className="w-12 h-12 mx-auto mb-4 text-gray-300 dark:text-gray-600" />
<p>Select or create a team to get started</p>
</div>
</div>
)}
</div>
{/* Footer */}
<div className="px-6 py-3 border-t border-gray-200 dark:border-gray-700 flex items-center justify-between text-sm text-gray-500 dark:text-gray-400">
<span>{teams.length} teams total</span>
{error && <span className="text-red-500">{error}</span>}
</div>
</div>
</div>
);
}

View File

@@ -1,549 +0,0 @@
/**
* Agent Swarm - Multi-Agent collaboration framework for ZCLAW
*
* Enables multiple agents (clones) to collaborate on complex tasks through:
* - Sequential: Agents process in chain, each building on the previous
* - Parallel: Agents work simultaneously on different subtasks
* - Debate: Agents provide competing perspectives, coordinator synthesizes
*
* Integrates with existing Clone/Agent infrastructure via agentStore/gatewayStore.
*
* Reference: ZCLAW_AGENT_INTELLIGENCE_EVOLUTION.md §6.5.1
*/
import { intelligenceClient } from './intelligence-client';
// === Types ===
export type CommunicationStyle = 'sequential' | 'parallel' | 'debate';
export type TaskDecomposition = 'auto' | 'manual';
export type SubtaskStatus = 'pending' | 'running' | 'done' | 'failed';
export type SwarmTaskStatus = 'planning' | 'executing' | 'aggregating' | 'done' | 'failed';
export interface SwarmSpecialist {
agentId: string;
role: string;
capabilities: string[];
model?: string;
}
export interface SwarmConfig {
coordinator: string;
specialists: SwarmSpecialist[];
taskDecomposition: TaskDecomposition;
communicationStyle: CommunicationStyle;
maxRoundsDebate: number;
timeoutPerSubtaskMs: number;
}
export interface Subtask {
id: string;
assignedTo: string;
description: string;
status: SubtaskStatus;
result?: string;
error?: string;
startedAt?: string;
completedAt?: string;
round?: number;
}
export interface SwarmTask {
id: string;
description: string;
subtasks: Subtask[];
status: SwarmTaskStatus;
communicationStyle: CommunicationStyle;
finalResult?: string;
createdAt: string;
completedAt?: string;
metadata?: Record<string, unknown>;
}
export interface SwarmExecutionResult {
task: SwarmTask;
summary: string;
participantCount: number;
totalDurationMs: number;
}
export type AgentExecutor = (
agentId: string,
prompt: string,
context?: string
) => Promise<string>;
// === Default Config ===
export const DEFAULT_SWARM_CONFIG: SwarmConfig = {
coordinator: 'zclaw-main',
specialists: [],
taskDecomposition: 'auto',
communicationStyle: 'sequential',
maxRoundsDebate: 3,
timeoutPerSubtaskMs: 60_000,
};
// === Storage ===
const SWARM_HISTORY_KEY = 'zclaw-swarm-history';
// === Swarm Engine ===
export class AgentSwarm {
private config: SwarmConfig;
private history: SwarmTask[] = [];
private executor: AgentExecutor | null = null;
constructor(config?: Partial<SwarmConfig>) {
this.config = { ...DEFAULT_SWARM_CONFIG, ...config };
this.loadHistory();
}
/**
* Set the executor function used to dispatch prompts to individual agents.
* This decouples the swarm from the gateway transport layer.
*/
setExecutor(executor: AgentExecutor): void {
this.executor = executor;
}
// === Task Creation ===
/**
* Create a new swarm task. If taskDecomposition is 'auto', subtasks are
* generated based on specialist capabilities and the task description.
*/
createTask(
description: string,
options?: {
subtasks?: Array<{ assignedTo: string; description: string }>;
communicationStyle?: CommunicationStyle;
metadata?: Record<string, unknown>;
}
): SwarmTask {
const style = options?.communicationStyle || this.config.communicationStyle;
const taskId = `swarm_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
let subtasks: Subtask[];
if (options?.subtasks && options.subtasks.length > 0) {
// Manual decomposition
subtasks = options.subtasks.map((st, i) => ({
id: `${taskId}_sub_${i}`,
assignedTo: st.assignedTo,
description: st.description,
status: 'pending' as SubtaskStatus,
}));
} else {
// Auto decomposition based on specialists
subtasks = this.autoDecompose(taskId, description, style);
}
const task: SwarmTask = {
id: taskId,
description,
subtasks,
status: 'planning',
communicationStyle: style,
createdAt: new Date().toISOString(),
metadata: options?.metadata,
};
return task;
}
/**
* Execute a swarm task using the configured communication style.
*/
async execute(task: SwarmTask): Promise<SwarmExecutionResult> {
if (!this.executor) {
throw new Error('[AgentSwarm] No executor set. Call setExecutor() first.');
}
const startTime = Date.now();
task.status = 'executing';
try {
switch (task.communicationStyle) {
case 'sequential':
await this.executeSequential(task);
break;
case 'parallel':
await this.executeParallel(task);
break;
case 'debate':
await this.executeDebate(task);
break;
}
// Aggregation phase
task.status = 'aggregating';
task.finalResult = await this.aggregate(task);
task.status = 'done';
task.completedAt = new Date().toISOString();
} catch (err) {
task.status = 'failed';
task.finalResult = `执行失败: ${err instanceof Error ? err.message : String(err)}`;
task.completedAt = new Date().toISOString();
}
const totalDurationMs = Date.now() - startTime;
// Store in history
this.history.push(task);
if (this.history.length > 50) {
this.history = this.history.slice(-25);
}
this.saveHistory();
// Save task result as memory
try {
await intelligenceClient.memory.store({
agent_id: this.config.coordinator,
memory_type: 'lesson',
content: `协作任务完成: "${task.description}" — ${task.subtasks.length}个子任务, 模式: ${task.communicationStyle}, 结果: ${(task.finalResult || '').slice(0, 200)}`,
importance: 6,
source: 'auto',
tags: ['swarm', task.communicationStyle],
});
} catch { /* non-critical */ }
const result: SwarmExecutionResult = {
task,
summary: task.finalResult || '',
participantCount: new Set(task.subtasks.map(s => s.assignedTo)).size,
totalDurationMs,
};
console.log(
`[AgentSwarm] Task "${task.description}" completed in ${totalDurationMs}ms, ` +
`${result.participantCount} participants, ${task.subtasks.length} subtasks`
);
return result;
}
// === Execution Strategies ===
/**
* Sequential: Each agent runs in order, receiving the previous agent's output as context.
*/
private async executeSequential(task: SwarmTask): Promise<void> {
let previousResult = '';
for (const subtask of task.subtasks) {
subtask.status = 'running';
subtask.startedAt = new Date().toISOString();
try {
const context = previousResult
? `前一个Agent的输出:\n${previousResult}\n\n请基于以上内容继续完成你的部分。`
: '';
const result = await this.executeSubtask(subtask, context);
subtask.result = result;
subtask.status = 'done';
previousResult = result;
} catch (err) {
subtask.status = 'failed';
subtask.error = err instanceof Error ? err.message : String(err);
}
subtask.completedAt = new Date().toISOString();
}
}
/**
* Parallel: All agents run simultaneously, results collected independently.
*/
private async executeParallel(task: SwarmTask): Promise<void> {
const promises = task.subtasks.map(async (subtask) => {
subtask.status = 'running';
subtask.startedAt = new Date().toISOString();
try {
const result = await this.executeSubtask(subtask);
subtask.result = result;
subtask.status = 'done';
} catch (err) {
subtask.status = 'failed';
subtask.error = err instanceof Error ? err.message : String(err);
}
subtask.completedAt = new Date().toISOString();
});
await Promise.allSettled(promises);
}
/**
* Debate: All agents respond to the same prompt in multiple rounds.
* Each round, agents can see previous round results.
*/
private async executeDebate(task: SwarmTask): Promise<void> {
const maxRounds = this.config.maxRoundsDebate;
const agents = [...new Set(task.subtasks.map(s => s.assignedTo))];
for (let round = 1; round <= maxRounds; round++) {
const roundContext = round > 1
? this.buildDebateContext(task, round - 1)
: '';
const roundPromises = agents.map(async (agentId) => {
const subtaskId = `${task.id}_debate_r${round}_${agentId}`;
const subtask: Subtask = {
id: subtaskId,
assignedTo: agentId,
description: task.description,
status: 'running',
startedAt: new Date().toISOString(),
round,
};
try {
const prompt = round === 1
? task.description
: `这是第${round}轮讨论。请参考其他Agent的观点给出你的更新后的分析。\n\n${roundContext}`;
const result = await this.executeSubtask(subtask, '', prompt);
subtask.result = result;
subtask.status = 'done';
} catch (err) {
subtask.status = 'failed';
subtask.error = err instanceof Error ? err.message : String(err);
}
subtask.completedAt = new Date().toISOString();
task.subtasks.push(subtask);
});
await Promise.allSettled(roundPromises);
// Check if consensus reached (all agents give similar answers)
if (round < maxRounds && this.checkConsensus(task, round)) {
console.log(`[AgentSwarm] Debate consensus reached at round ${round}`);
break;
}
}
}
// === Helpers ===
private async executeSubtask(
subtask: Subtask,
context?: string,
promptOverride?: string
): Promise<string> {
if (!this.executor) throw new Error('No executor');
const prompt = promptOverride || subtask.description;
return this.executor(subtask.assignedTo, prompt, context);
}
/**
* Auto-decompose a task into subtasks based on specialist roles.
*/
private autoDecompose(
taskId: string,
description: string,
style: CommunicationStyle
): Subtask[] {
const specialists = this.config.specialists;
if (specialists.length === 0) {
// Single agent fallback
return [{
id: `${taskId}_sub_0`,
assignedTo: this.config.coordinator,
description,
status: 'pending',
}];
}
if (style === 'debate') {
// In debate mode, all specialists get the same task
return specialists.map((spec, i) => ({
id: `${taskId}_sub_${i}`,
assignedTo: spec.agentId,
description: `作为${spec.role},请分析以下问题: ${description}`,
status: 'pending' as SubtaskStatus,
round: 1,
}));
}
if (style === 'parallel') {
// In parallel, assign based on capabilities
return specialists.map((spec, i) => ({
id: `${taskId}_sub_${i}`,
assignedTo: spec.agentId,
description: `${spec.role}的角度完成: ${description}`,
status: 'pending' as SubtaskStatus,
}));
}
// Sequential: chain through specialists
return specialists.map((spec, i) => ({
id: `${taskId}_sub_${i}`,
assignedTo: spec.agentId,
description: i === 0
? `作为${spec.role},请首先分析: ${description}`
: `作为${spec.role},请基于前一位同事的分析继续深化: ${description}`,
status: 'pending' as SubtaskStatus,
}));
}
private buildDebateContext(task: SwarmTask, upToRound: number): string {
const roundSubtasks = task.subtasks.filter(
s => s.round && s.round <= upToRound && s.status === 'done'
);
if (roundSubtasks.length === 0) return '';
const lines = roundSubtasks.map(s => {
const specialist = this.config.specialists.find(sp => sp.agentId === s.assignedTo);
const role = specialist?.role || s.assignedTo;
return `**${role}** (第${s.round}轮):\n${s.result || '(无输出)'}`;
});
return `其他Agent的观点:\n\n${lines.join('\n\n---\n\n')}`;
}
private checkConsensus(task: SwarmTask, round: number): boolean {
const roundResults = task.subtasks
.filter(s => s.round === round && s.status === 'done' && s.result)
.map(s => s.result!);
if (roundResults.length < 2) return false;
// Simple heuristic: if all results share > 60% keywords, consider consensus
const tokenSets = roundResults.map(r =>
new Set(r.toLowerCase().split(/[\s,;.!?。,;!?]+/).filter(t => t.length > 1))
);
for (let i = 1; i < tokenSets.length; i++) {
const common = [...tokenSets[0]].filter(t => tokenSets[i].has(t));
const similarity = (2 * common.length) / (tokenSets[0].size + tokenSets[i].size);
if (similarity < 0.6) return false;
}
return true;
}
/**
* Aggregate subtask results into a final summary.
* Phase 4: rule-based. Future: LLM-powered synthesis.
*/
private async aggregate(task: SwarmTask): Promise<string> {
const completedSubtasks = task.subtasks.filter(s => s.status === 'done' && s.result);
const failedSubtasks = task.subtasks.filter(s => s.status === 'failed');
if (completedSubtasks.length === 0) {
return failedSubtasks.length > 0
? `所有子任务失败: ${failedSubtasks.map(s => s.error).join('; ')}`
: '无结果';
}
const sections: string[] = [];
sections.push(`## 协作任务: ${task.description}`);
sections.push(`**模式**: ${task.communicationStyle} | **参与者**: ${new Set(completedSubtasks.map(s => s.assignedTo)).size}`);
if (task.communicationStyle === 'debate') {
// Group by round
const maxRound = Math.max(...completedSubtasks.map(s => s.round || 1));
for (let r = 1; r <= maxRound; r++) {
const roundResults = completedSubtasks.filter(s => s.round === r);
if (roundResults.length > 0) {
sections.push(`\n### 第${r}轮讨论`);
for (const s of roundResults) {
const spec = this.config.specialists.find(sp => sp.agentId === s.assignedTo);
sections.push(`**${spec?.role || s.assignedTo}**:\n${s.result}`);
}
}
}
} else {
for (const s of completedSubtasks) {
const spec = this.config.specialists.find(sp => sp.agentId === s.assignedTo);
sections.push(`\n### ${spec?.role || s.assignedTo}\n${s.result}`);
}
}
if (failedSubtasks.length > 0) {
sections.push(`\n### 失败的子任务 (${failedSubtasks.length})`);
for (const s of failedSubtasks) {
sections.push(`- ${s.assignedTo}: ${s.error}`);
}
}
return sections.join('\n');
}
// === Query ===
getHistory(limit: number = 20): SwarmTask[] {
return this.history.slice(-limit);
}
getTask(taskId: string): SwarmTask | undefined {
return this.history.find(t => t.id === taskId);
}
getSpecialists(): SwarmSpecialist[] {
return [...this.config.specialists];
}
addSpecialist(specialist: SwarmSpecialist): void {
const existing = this.config.specialists.findIndex(s => s.agentId === specialist.agentId);
if (existing >= 0) {
this.config.specialists[existing] = specialist;
} else {
this.config.specialists.push(specialist);
}
}
removeSpecialist(agentId: string): void {
this.config.specialists = this.config.specialists.filter(s => s.agentId !== agentId);
}
// === Config ===
getConfig(): SwarmConfig {
return { ...this.config, specialists: [...this.config.specialists] };
}
updateConfig(updates: Partial<SwarmConfig>): void {
this.config = { ...this.config, ...updates };
}
// === Persistence ===
private loadHistory(): void {
try {
const raw = localStorage.getItem(SWARM_HISTORY_KEY);
if (raw) this.history = JSON.parse(raw);
} catch {
this.history = [];
}
}
private saveHistory(): void {
try {
localStorage.setItem(SWARM_HISTORY_KEY, JSON.stringify(this.history.slice(-25)));
} catch { /* silent */ }
}
}
// === Singleton ===
let _instance: AgentSwarm | null = null;
export function getAgentSwarm(config?: Partial<SwarmConfig>): AgentSwarm {
if (!_instance) {
_instance = new AgentSwarm(config);
}
return _instance;
}
export function resetAgentSwarm(): void {
_instance = null;
}

View File

@@ -1,440 +0,0 @@
/**
* OpenFang Team API Client
*
* REST API client for multi-agent team collaboration endpoints.
* Communicates with OpenFang Kernel for team management,
* task coordination, and Dev↔QA loops.
*
* @module lib/team-client
*/
import type {
Team,
TeamMember,
TeamTask,
TeamMemberRole,
DevQALoop,
CreateTeamRequest,
AddTeamTaskRequest,
TeamResponse,
ReviewFeedback,
TaskDeliverable,
CollaborationEvent,
TeamMetrics,
} from '../types/team';
// Re-export types for consumers
export type { CollaborationEvent } from '../types/team';
// === Configuration ===
const API_BASE = '/api'; // Uses Vite proxy
// === Error Types ===
export class TeamAPIError extends Error {
constructor(
message: string,
public statusCode: number,
public endpoint: string,
public details?: unknown
) {
super(message);
this.name = 'TeamAPIError';
}
}
// === Helper Functions ===
async function request<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const url = `${API_BASE}${endpoint}`;
try {
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
...options.headers,
},
...options,
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new TeamAPIError(
errorData.message || `HTTP ${response.status}`,
response.status,
endpoint,
errorData
);
}
return response.json();
} catch (error) {
if (error instanceof TeamAPIError) {
throw error;
}
throw new TeamAPIError(
(error as Error).message,
0,
endpoint,
error
);
}
}
// === Team API ===
/**
* List all teams
*/
export async function listTeams(): Promise<{ teams: Team[]; total: number }> {
return request<{ teams: Team[]; total: number }>('/teams');
}
/**
* Get a specific team by ID
*/
export async function getTeam(teamId: string): Promise<TeamResponse> {
return request<TeamResponse>(`/teams/${teamId}`);
}
/**
* Create a new team
*/
export async function createTeam(data: CreateTeamRequest): Promise<TeamResponse> {
return request<TeamResponse>('/teams', {
method: 'POST',
body: JSON.stringify(data),
});
}
/**
* Update a team
*/
export async function updateTeam(
teamId: string,
data: Partial<Pick<Team, 'name' | 'description' | 'pattern' | 'status'>>
): Promise<TeamResponse> {
return request<TeamResponse>(`/teams/${teamId}`, {
method: 'PUT',
body: JSON.stringify(data),
});
}
/**
* Delete a team
*/
export async function deleteTeam(teamId: string): Promise<{ success: boolean }> {
return request<{ success: boolean }>(`/teams/${teamId}`, {
method: 'DELETE',
});
}
// === Team Member API ===
/**
* Add a member to a team
*/
export async function addTeamMember(
teamId: string,
agentId: string,
role: TeamMemberRole
): Promise<{ member: TeamMember; success: boolean }> {
return request<{ member: TeamMember; success: boolean }>(
`/teams/${teamId}/members`,
{
method: 'POST',
body: JSON.stringify({ agentId, role }),
}
);
}
/**
* Remove a member from a team
*/
export async function removeTeamMember(
teamId: string,
memberId: string
): Promise<{ success: boolean }> {
return request<{ success: boolean }>(
`/teams/${teamId}/members/${memberId}`,
{ method: 'DELETE' }
);
}
/**
* Update a member's role
*/
export async function updateMemberRole(
teamId: string,
memberId: string,
role: TeamMemberRole
): Promise<{ member: TeamMember; success: boolean }> {
return request<{ member: TeamMember; success: boolean }>(
`/teams/${teamId}/members/${memberId}`,
{
method: 'PUT',
body: JSON.stringify({ role }),
}
);
}
// === Team Task API ===
/**
* Add a task to a team
*/
export async function addTeamTask(
data: AddTeamTaskRequest
): Promise<{ task: TeamTask; success: boolean }> {
return request<{ task: TeamTask; success: boolean }>(
`/teams/${data.teamId}/tasks`,
{
method: 'POST',
body: JSON.stringify({
title: data.title,
description: data.description,
priority: data.priority,
type: data.type,
assigneeId: data.assigneeId,
dependencies: data.dependencies,
estimate: data.estimate,
}),
}
);
}
/**
* Update a task's status
*/
export async function updateTaskStatus(
teamId: string,
taskId: string,
status: TeamTask['status']
): Promise<{ task: TeamTask; success: boolean }> {
return request<{ task: TeamTask; success: boolean }>(
`/teams/${teamId}/tasks/${taskId}`,
{
method: 'PUT',
body: JSON.stringify({ status }),
}
);
}
/**
* Assign a task to a member
*/
export async function assignTask(
teamId: string,
taskId: string,
memberId: string
): Promise<{ task: TeamTask; success: boolean }> {
return request<{ task: TeamTask; success: boolean }>(
`/teams/${teamId}/tasks/${taskId}/assign`,
{
method: 'POST',
body: JSON.stringify({ memberId }),
}
);
}
/**
* Submit a deliverable for a task
*/
export async function submitDeliverable(
teamId: string,
taskId: string,
deliverable: TaskDeliverable
): Promise<{ task: TeamTask; success: boolean }> {
return request<{ task: TeamTask; success: boolean }>(
`/teams/${teamId}/tasks/${taskId}/deliverable`,
{
method: 'POST',
body: JSON.stringify(deliverable),
}
);
}
// === Dev↔QA Loop API ===
/**
* Start a Dev↔QA loop for a task
*/
export async function startDevQALoop(
teamId: string,
taskId: string,
developerId: string,
reviewerId: string
): Promise<{ loop: DevQALoop; success: boolean }> {
return request<{ loop: DevQALoop; success: boolean }>(
`/teams/${teamId}/loops`,
{
method: 'POST',
body: JSON.stringify({ taskId, developerId, reviewerId }),
}
);
}
/**
* Submit a review for a Dev↔QA loop
*/
export async function submitReview(
teamId: string,
loopId: string,
feedback: Omit<ReviewFeedback, 'reviewedAt' | 'reviewerId'>
): Promise<{ loop: DevQALoop; success: boolean }> {
return request<{ loop: DevQALoop; success: boolean }>(
`/teams/${teamId}/loops/${loopId}/review`,
{
method: 'POST',
body: JSON.stringify(feedback),
}
);
}
/**
* Update a Dev↔QA loop state
*/
export async function updateLoopState(
teamId: string,
loopId: string,
state: DevQALoop['state']
): Promise<{ loop: DevQALoop; success: boolean }> {
return request<{ loop: DevQALoop; success: boolean }>(
`/teams/${teamId}/loops/${loopId}`,
{
method: 'PUT',
body: JSON.stringify({ state }),
}
);
}
// === Metrics & Events ===
/**
* Get team metrics
*/
export async function getTeamMetrics(teamId: string): Promise<TeamMetrics> {
return request<TeamMetrics>(`/teams/${teamId}/metrics`);
}
/**
* Get recent collaboration events
*/
export async function getTeamEvents(
teamId: string,
limit?: number
): Promise<{ events: CollaborationEvent[]; total: number }> {
const query = limit ? `?limit=${limit}` : '';
return request<{ events: CollaborationEvent[]; total: number }>(
`/teams/${teamId}/events${query}`
);
}
// === WebSocket Event Subscription ===
export type TeamEventType =
| 'team.created'
| 'team.updated'
| 'team.deleted'
| 'member.added'
| 'member.removed'
| 'member.status_changed'
| 'task.created'
| 'task.assigned'
| 'task.status_changed'
| 'task.completed'
| 'loop.started'
| 'loop.state_changed'
| 'loop.completed'
| 'review.submitted';
export interface TeamEventMessage {
type: 'team_event';
eventType: TeamEventType;
teamId: string;
payload: Record<string, unknown>;
timestamp: string;
}
/**
* Subscribe to team events via WebSocket
* Returns an unsubscribe function
*/
export function subscribeToTeamEvents(
teamId: string | null, // null = all teams
callback: (event: TeamEventMessage) => void,
ws: WebSocket
): () => void {
const handleMessage = (event: MessageEvent) => {
try {
const data = JSON.parse(event.data);
if (data.type === 'team_event') {
// Filter by teamId if specified
if (teamId === null || data.teamId === teamId) {
callback(data as TeamEventMessage);
}
}
} catch {
// Ignore non-JSON messages
}
};
ws.addEventListener('message', handleMessage);
// Send subscription message
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: 'subscribe',
topic: teamId ? `team:${teamId}` : 'teams',
}));
}
// Return unsubscribe function
return () => {
ws.removeEventListener('message', handleMessage);
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: 'unsubscribe',
topic: teamId ? `team:${teamId}` : 'teams',
}));
}
};
}
// === Export singleton client ===
export const teamClient = {
// Teams
listTeams,
getTeam,
createTeam,
updateTeam,
deleteTeam,
// Members
addTeamMember,
removeTeamMember,
updateMemberRole,
// Tasks
addTeamTask,
updateTaskStatus,
assignTask,
submitDeliverable,
// Dev↔QA Loops
startDevQALoop,
submitReview,
updateLoopState,
// Metrics & Events
getTeamMetrics,
getTeamEvents,
subscribeToTeamEvents,
};
export default teamClient;

View File

@@ -1,202 +0,0 @@
/**
* useTeamEvents - WebSocket Real-time Event Sync Hook
*
* Subscribes to team collaboration events via WebSocket
* and updates the team store in real-time.
*
* @module lib/useTeamEvents
*/
import { useEffect, useRef, useCallback } from 'react';
import { useTeamStore } from '../store/teamStore';
import { useGatewayStore } from '../store/gatewayStore';
import type { TeamEventMessage, TeamEventType, CollaborationEvent } from '../lib/team-client';
import { silentErrorHandler } from './error-utils';
interface UseTeamEventsOptions {
/** Subscribe to specific team only, or null for all teams */
teamId?: string | null;
/** Event types to subscribe to (default: all) */
eventTypes?: TeamEventType[];
/** Maximum events to keep in history (default: 100) */
maxEvents?: number;
}
/**
* Hook for subscribing to real-time team collaboration events
*/
export function useTeamEvents(options: UseTeamEventsOptions = {}) {
const { teamId = null, eventTypes } = options;
const unsubscribeRef = useRef<(() => void) | null>(null);
const {
addEvent,
updateTaskStatus,
updateLoopState,
loadTeams,
} = useTeamStore();
const { connectionState } = useGatewayStore();
const handleTeamEvent = useCallback(
(message: TeamEventMessage) => {
// Filter by event types if specified
if (eventTypes && !eventTypes.includes(message.eventType)) {
return;
}
// Create collaboration event for store
const event = {
type: mapEventType(message.eventType),
teamId: message.teamId,
sourceAgentId: (message.payload.sourceAgentId as string) || 'system',
payload: message.payload,
timestamp: message.timestamp,
};
// Add to event history
addEvent(event);
// Handle specific event types
switch (message.eventType) {
case 'task.status_changed':
if (message.payload.taskId && message.payload.status) {
updateTaskStatus(
message.teamId,
message.payload.taskId as string,
message.payload.status as any
);
}
break;
case 'loop.state_changed':
if (message.payload.loopId && message.payload.state) {
updateLoopState(
message.teamId,
message.payload.loopId as string,
message.payload.state as any
);
}
break;
case 'team.updated':
case 'member.added':
case 'member.removed':
// Reload teams to get updated data
loadTeams().catch(silentErrorHandler('useTeamEvents'));
break;
}
},
[eventTypes, addEvent, updateTaskStatus, updateLoopState, loadTeams]
);
useEffect(() => {
// Only subscribe when connected
if (connectionState !== 'connected') {
return;
}
// Get WebSocket from gateway client
const client = getGatewayClientSafe();
if (!client || !client.ws) {
return;
}
const ws = client.ws;
// Subscribe to team events
const handleMessage = (event: MessageEvent) => {
try {
const data = JSON.parse(event.data);
if (data.type === 'team_event') {
handleTeamEvent(data as TeamEventMessage);
}
} catch {
// Ignore non-JSON messages
}
};
ws.addEventListener('message', handleMessage);
// Send subscription message
if (ws.readyState === WebSocket.OPEN) {
ws.send(
JSON.stringify({
type: 'subscribe',
topic: teamId ? `team:${teamId}` : 'teams',
})
);
}
unsubscribeRef.current = () => {
ws.removeEventListener('message', handleMessage);
if (ws.readyState === WebSocket.OPEN) {
ws.send(
JSON.stringify({
type: 'unsubscribe',
topic: teamId ? `team:${teamId}` : 'teams',
})
);
}
};
return () => {
if (unsubscribeRef.current) {
unsubscribeRef.current();
unsubscribeRef.current = null;
}
};
}, [connectionState, teamId, handleTeamEvent]);
return {
isConnected: connectionState === 'connected',
};
}
/**
* Hook for subscribing to a specific team's events
*/
export function useTeamEventStream(teamId: string) {
return useTeamEvents({ teamId });
}
/**
* Hook for subscribing to all team events
*/
export function useAllTeamEvents(options: Omit<UseTeamEventsOptions, 'teamId'> = {}) {
return useTeamEvents({ ...options, teamId: null });
}
// === Helper Functions ===
function mapEventType(eventType: TeamEventType): CollaborationEvent['type'] {
const mapping: Record<TeamEventType, CollaborationEvent['type']> = {
'team.created': 'member_status_change',
'team.updated': 'member_status_change',
'team.deleted': 'member_status_change',
'member.added': 'member_status_change',
'member.removed': 'member_status_change',
'member.status_changed': 'member_status_change',
'task.created': 'task_assigned',
'task.assigned': 'task_assigned',
'task.status_changed': 'task_started',
'task.completed': 'task_completed',
'loop.started': 'loop_state_change',
'loop.state_changed': 'loop_state_change',
'loop.completed': 'loop_state_change',
'review.submitted': 'review_submitted',
};
return mapping[eventType] || 'task_started';
}
function getGatewayClientSafe() {
try {
// Dynamic import to avoid circular dependency
const { getClient } = require('../store/connectionStore');
return getClient();
} catch {
return null;
}
}
export default useTeamEvents;

View File

@@ -4,7 +4,6 @@ import type { AgentStreamDelta } from '../lib/gateway-client';
import { getClient } from './connectionStore';
import { intelligenceClient } from '../lib/intelligence-client';
import { getMemoryExtractor } from '../lib/memory-extractor';
import { getAgentSwarm } from '../lib/agent-swarm';
import { getSkillDiscovery } from '../lib/skill-discovery';
import { useOfflineStore, isOffline } from './offlineStore';
import { useConnectionStore } from './connectionStore';
@@ -98,7 +97,6 @@ interface ChatState {
newConversation: () => void;
switchConversation: (id: string) => void;
deleteConversation: (id: string) => void;
dispatchSwarmTask: (description: string, style?: 'sequential' | 'parallel' | 'debate') => Promise<string | null>;
searchSkills: (query: string) => { results: Array<{ id: string; name: string; description: string }>; totalAvailable: number };
}
@@ -545,39 +543,6 @@ export const useChatStore = create<ChatState>()(
}
},
dispatchSwarmTask: async (description: string, style?: 'sequential' | 'parallel' | 'debate') => {
try {
const swarm = getAgentSwarm();
const task = swarm.createTask(description, {
communicationStyle: style || 'parallel',
});
// Set up executor that uses the connected client
swarm.setExecutor(async (agentId: string, prompt: string, context?: string) => {
const client = getClient();
const fullPrompt = context ? `${context}\n\n${prompt}` : prompt;
const result = await client.chat(fullPrompt, { agentId: agentId.startsWith('clone_') ? undefined : agentId });
return result?.response || '(无响应)';
});
const result = await swarm.execute(task);
// Add swarm result as assistant message
const swarmMsg: Message = {
id: `swarm_${Date.now()}`,
role: 'assistant',
content: result.summary || '协作任务完成',
timestamp: new Date(),
};
get().addMessage(swarmMsg);
return result.task.id;
} catch (err) {
log.warn('Swarm dispatch failed:', err);
return null;
}
},
searchSkills: (query: string) => {
const discovery = getSkillDiscovery();
const result = discovery.searchSkills(query);

View File

@@ -1,608 +0,0 @@
/**
* Team Store - Multi-Agent Team Collaboration State Management
*
* Manages team orchestration, task assignment, Dev↔QA loops,
* and real-time collaboration state.
*
* @module store/teamStore
*/
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type {
Team,
TeamMember,
TeamTask,
TeamTaskStatus,
TeamMemberRole,
DevQALoop,
DevQALoopState,
CreateTeamRequest,
AddTeamTaskRequest,
TeamMetrics,
CollaborationEvent,
ReviewFeedback,
TaskDeliverable,
} from '../types/team';
// === Store State ===
interface TeamStoreState {
// Data
teams: Team[];
activeTeam: Team | null;
metrics: TeamMetrics | null;
// UI State
isLoading: boolean;
error: string | null;
selectedTaskId: string | null;
selectedMemberId: string | null;
// Real-time events
recentEvents: CollaborationEvent[];
// Actions - Team Management
loadTeams: () => Promise<void>;
createTeam: (request: CreateTeamRequest) => Promise<Team | null>;
deleteTeam: (teamId: string) => Promise<boolean>;
setActiveTeam: (team: Team | null) => void;
// Actions - Member Management
addMember: (teamId: string, agentId: string, role: TeamMemberRole) => Promise<TeamMember | null>;
removeMember: (teamId: string, memberId: string) => Promise<boolean>;
updateMemberRole: (teamId: string, memberId: string, role: TeamMemberRole) => Promise<boolean>;
// Actions - Task Management
addTask: (request: AddTeamTaskRequest) => Promise<TeamTask | null>;
updateTaskStatus: (teamId: string, taskId: string, status: TeamTaskStatus) => Promise<boolean>;
assignTask: (teamId: string, taskId: string, memberId: string) => Promise<boolean>;
submitDeliverable: (teamId: string, taskId: string, deliverable: TaskDeliverable) => Promise<boolean>;
// Actions - Dev↔QA Loop
startDevQALoop: (teamId: string, taskId: string, developerId: string, reviewerId: string) => Promise<DevQALoop | null>;
submitReview: (teamId: string, loopId: string, feedback: Omit<ReviewFeedback, 'reviewedAt' | 'reviewerId'>) => Promise<boolean>;
updateLoopState: (teamId: string, loopId: string, state: DevQALoopState) => Promise<boolean>;
// Actions - Events
addEvent: (event: CollaborationEvent) => void;
clearEvents: () => void;
// Actions - UI
setSelectedTask: (taskId: string | null) => void;
setSelectedMember: (memberId: string | null) => void;
clearError: () => void;
}
// === Helper Functions ===
const generateId = () => `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const calculateMetrics = (team: Team): TeamMetrics => {
const completedTasks = team.tasks.filter(t => t.status === 'completed');
const totalTasks = team.tasks.length;
const reviewedTasks = completedTasks.filter(t => t.reviewFeedback);
const avgCompletionTime = completedTasks.length > 0
? completedTasks.reduce((sum, t) => {
if (t.startedAt && t.completedAt) {
return sum + (new Date(t.completedAt).getTime() - new Date(t.startedAt).getTime());
}
return sum;
}, 0) / completedTasks.length
: 0;
const approvedReviews = reviewedTasks.filter(t => t.reviewFeedback?.verdict === 'approved');
const passRate = reviewedTasks.length > 0
? (approvedReviews.length / reviewedTasks.length) * 100
: 0;
const totalIterations = team.activeLoops.reduce((sum, loop) => sum + loop.iterationCount, 0);
const avgIterations = team.activeLoops.length > 0
? totalIterations / team.activeLoops.length
: 0;
const escalations = team.activeLoops.filter(loop => loop.state === 'escalated').length;
const efficiency = totalTasks > 0
? Math.min(100, (completedTasks.length / totalTasks) * 100 * (passRate / 100))
: 0;
return {
tasksCompleted: completedTasks.length,
avgCompletionTime,
passRate,
avgIterations,
escalations,
efficiency,
};
};
// === Store Implementation ===
export const useTeamStore = create<TeamStoreState>()(
persist(
(set, get) => ({
// Initial State
teams: [],
activeTeam: null,
metrics: null,
isLoading: false,
error: null,
selectedTaskId: null,
selectedMemberId: null,
recentEvents: [],
// Team Management
loadTeams: async () => {
set({ isLoading: true, error: null });
try {
// For now, load from localStorage until API is available
// Note: persist middleware stores data as { state: { teams: [...] }, version: ... }
const stored = localStorage.getItem('zclaw-teams');
let teams: Team[] = [];
if (stored) {
const parsed = JSON.parse(stored);
// Handle persist middleware format
if (parsed?.state?.teams && Array.isArray(parsed.state.teams)) {
teams = parsed.state.teams;
} else if (Array.isArray(parsed)) {
// Direct array format (legacy)
teams = parsed;
}
}
set({ teams, isLoading: false });
} catch (error) {
console.error('[TeamStore] Failed to load teams:', error);
set({ teams: [], isLoading: false });
}
},
createTeam: async (request: CreateTeamRequest) => {
set({ isLoading: true, error: null });
try {
const now = new Date().toISOString();
const members: TeamMember[] = request.memberAgents.map((m) => ({
id: generateId(),
agentId: m.agentId,
name: `Agent-${m.agentId.slice(0, 4)}`,
role: m.role,
skills: [],
workload: 0,
status: 'idle',
maxConcurrentTasks: m.role === 'orchestrator' ? 5 : 2,
currentTasks: [],
}));
const team: Team = {
id: generateId(),
name: request.name,
description: request.description,
members,
tasks: [],
pattern: request.pattern,
activeLoops: [],
status: 'active',
createdAt: now,
updatedAt: now,
};
set(state => {
const teams = [...state.teams, team];
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return { teams, activeTeam: team, isLoading: false };
});
return team;
} catch (error) {
set({ error: (error as Error).message, isLoading: false });
return null;
}
},
deleteTeam: async (teamId: string) => {
set({ isLoading: true, error: null });
try {
set(state => {
const teams = state.teams.filter(t => t.id !== teamId);
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return {
teams,
activeTeam: state.activeTeam?.id === teamId ? null : state.activeTeam,
isLoading: false
};
});
return true;
} catch (error) {
set({ error: (error as Error).message, isLoading: false });
return false;
}
},
setActiveTeam: (team: Team | null) => {
set(() => ({
activeTeam: team,
metrics: team ? calculateMetrics(team) : null,
}));
},
// Member Management
addMember: async (teamId: string, agentId: string, role: TeamMemberRole) => {
const state = get();
const team = state.teams.find(t => t.id === teamId);
if (!team) return null;
const member: TeamMember = {
id: generateId(),
agentId,
name: `Agent-${agentId.slice(0, 4)}`,
role,
skills: [],
workload: 0,
status: 'idle',
maxConcurrentTasks: role === 'orchestrator' ? 5 : 2,
currentTasks: [],
};
const updatedTeam = {
...team,
members: [...team.members, member],
updatedAt: new Date().toISOString(),
};
set(state => {
const teams = state.teams.map(t => t.id === teamId ? updatedTeam : t);
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return {
teams,
activeTeam: state.activeTeam?.id === teamId ? updatedTeam : state.activeTeam,
};
});
return member;
},
removeMember: async (teamId: string, memberId: string) => {
const state = get();
const team = state.teams.find(t => t.id === teamId);
if (!team) return false;
const updatedTeam = {
...team,
members: team.members.filter(m => m.id !== memberId),
updatedAt: new Date().toISOString(),
};
set(state => {
const teams = state.teams.map(t => t.id === teamId ? updatedTeam : t);
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return {
teams,
activeTeam: state.activeTeam?.id === teamId ? updatedTeam : state.activeTeam,
};
});
return true;
},
updateMemberRole: async (teamId: string, memberId: string, role: TeamMemberRole) => {
const state = get();
const team = state.teams.find(t => t.id === teamId);
if (!team) return false;
const updatedTeam = {
...team,
members: team.members.map(m =>
m.id === memberId ? { ...m, role, maxConcurrentTasks: role === 'orchestrator' ? 5 : 2 } : m
),
updatedAt: new Date().toISOString(),
};
set(state => {
const teams = state.teams.map(t => t.id === teamId ? updatedTeam : t);
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return {
teams,
activeTeam: state.activeTeam?.id === teamId ? updatedTeam : state.activeTeam,
};
});
return true;
},
// Task Management
addTask: async (request: AddTeamTaskRequest) => {
const state = get();
const team = state.teams.find(t => t.id === request.teamId);
if (!team) return null;
const now = new Date().toISOString();
const task: TeamTask = {
id: generateId(),
title: request.title,
description: request.description,
status: request.assigneeId ? 'assigned' : 'pending',
priority: request.priority,
assigneeId: request.assigneeId,
dependencies: request.dependencies || [],
type: request.type,
estimate: request.estimate,
createdAt: now,
updatedAt: now,
};
const updatedTeam = {
...team,
tasks: [...team.tasks, task],
updatedAt: now,
};
set(state => {
const teams = state.teams.map(t => t.id === request.teamId ? updatedTeam : t);
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return {
teams,
activeTeam: state.activeTeam?.id === request.teamId ? updatedTeam : state.activeTeam,
metrics: state.activeTeam?.id === request.teamId ? calculateMetrics(updatedTeam) : state.metrics,
};
});
return task;
},
updateTaskStatus: async (teamId: string, taskId: string, status: TeamTaskStatus) => {
const state = get();
const team = state.teams.find(t => t.id === teamId);
if (!team) return false;
const now = new Date().toISOString();
const updatedTeam = {
...team,
tasks: team.tasks.map(t => {
if (t.id !== taskId) return t;
const updates: Partial<TeamTask> = { status, updatedAt: now };
if (status === 'in_progress' && !t.startedAt) {
updates.startedAt = now;
}
if (status === 'completed') {
updates.completedAt = now;
}
return { ...t, ...updates };
}),
updatedAt: now,
};
set(state => {
const teams = state.teams.map(t => t.id === teamId ? updatedTeam : t);
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return {
teams,
activeTeam: state.activeTeam?.id === teamId ? updatedTeam : state.activeTeam,
metrics: state.activeTeam?.id === teamId ? calculateMetrics(updatedTeam) : state.metrics,
};
});
return true;
},
assignTask: async (teamId: string, taskId: string, memberId: string) => {
const state = get();
const team = state.teams.find(t => t.id === teamId);
if (!team) return false;
const now = new Date().toISOString();
const updatedTeam = {
...team,
tasks: team.tasks.map(t =>
t.id === taskId
? { ...t, assigneeId: memberId, status: 'assigned' as TeamTaskStatus, updatedAt: now }
: t
),
members: team.members.map(m =>
m.id === memberId
? { ...m, currentTasks: [...m.currentTasks, taskId], workload: (m.workload + 25) }
: m
),
updatedAt: now,
};
set(state => {
const teams = state.teams.map(t => t.id === teamId ? updatedTeam : t);
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return {
teams,
activeTeam: state.activeTeam?.id === teamId ? updatedTeam : state.activeTeam,
};
});
return true;
},
submitDeliverable: async (teamId: string, taskId: string, deliverable: TaskDeliverable) => {
const state = get();
const team = state.teams.find(t => t.id === teamId);
if (!team) return false;
const now = new Date().toISOString();
const updatedTeam = {
...team,
tasks: team.tasks.map(t =>
t.id === taskId
? { ...t, deliverable, status: 'review' as TeamTaskStatus, updatedAt: now }
: t
),
updatedAt: now,
};
set(state => {
const teams = state.teams.map(t => t.id === teamId ? updatedTeam : t);
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return {
teams,
activeTeam: state.activeTeam?.id === teamId ? updatedTeam : state.activeTeam,
};
});
return true;
},
// Dev↔QA Loop
startDevQALoop: async (teamId: string, taskId: string, developerId: string, reviewerId: string) => {
const state = get();
const team = state.teams.find(t => t.id === teamId);
if (!team) return null;
const now = new Date().toISOString();
const loop: DevQALoop = {
id: generateId(),
developerId,
reviewerId,
taskId,
state: 'developing',
iterationCount: 0,
maxIterations: 3,
feedbackHistory: [],
startedAt: now,
lastUpdatedAt: now,
};
const updatedTeam = {
...team,
activeLoops: [...team.activeLoops, loop],
updatedAt: now,
};
set(state => {
const teams = state.teams.map(t => t.id === teamId ? updatedTeam : t);
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return {
teams,
activeTeam: state.activeTeam?.id === teamId ? updatedTeam : state.activeTeam,
};
});
return loop;
},
submitReview: async (teamId: string, loopId: string, feedback: Omit<ReviewFeedback, 'reviewedAt' | 'reviewerId'>) => {
const state = get();
const team = state.teams.find(t => t.id === teamId);
if (!team) return false;
const loop = team.activeLoops.find(l => l.id === loopId);
if (!loop) return false;
const now = new Date().toISOString();
const fullFeedback: ReviewFeedback = {
...feedback,
reviewedAt: now,
reviewerId: loop.reviewerId,
};
let newState: DevQALoopState;
let newIterationCount = loop.iterationCount;
if (feedback.verdict === 'approved') {
newState = 'approved';
} else if (newIterationCount >= loop.maxIterations - 1) {
newState = 'escalated';
} else {
newState = 'revising';
newIterationCount++;
}
const updatedTeam = {
...team,
tasks: team.tasks.map(t =>
t.id === loop.taskId
? { ...t, reviewFeedback: fullFeedback, updatedAt: now }
: t
),
activeLoops: team.activeLoops.map(l =>
l.id === loopId
? {
...l,
state: newState,
iterationCount: newIterationCount,
feedbackHistory: [...l.feedbackHistory, fullFeedback],
lastUpdatedAt: now,
}
: l
),
updatedAt: now,
};
set(state => {
const teams = state.teams.map(t => t.id === teamId ? updatedTeam : t);
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return {
teams,
activeTeam: state.activeTeam?.id === teamId ? updatedTeam : state.activeTeam,
metrics: state.activeTeam?.id === teamId ? calculateMetrics(updatedTeam) : state.metrics,
};
});
return true;
},
updateLoopState: async (teamId: string, loopId: string, state: DevQALoopState) => {
const teamStore = get();
const team = teamStore.teams.find(t => t.id === teamId);
if (!team) return false;
const now = new Date().toISOString();
const updatedTeam = {
...team,
activeLoops: team.activeLoops.map(l =>
l.id === loopId
? { ...l, state, lastUpdatedAt: now }
: l
),
updatedAt: now,
};
set(state => {
const teams = state.teams.map(t => t.id === teamId ? updatedTeam : t);
localStorage.setItem('zclaw-teams', JSON.stringify(teams));
return {
teams,
activeTeam: state.activeTeam?.id === teamId ? updatedTeam : state.activeTeam,
};
});
return true;
},
// Events
addEvent: (event: CollaborationEvent) => {
set(state => ({
recentEvents: [event, ...state.recentEvents].slice(0, 100),
}));
},
clearEvents: () => {
set({ recentEvents: [] });
},
// UI
setSelectedTask: (taskId: string | null) => {
set({ selectedTaskId: taskId });
},
setSelectedMember: (memberId: string | null) => {
set({ selectedMemberId: memberId });
},
clearError: () => {
set({ error: null });
},
}),
{
name: 'zclaw-teams',
partialize: (state) => ({
teams: state.teams,
activeTeam: state.activeTeam,
}),
},
));

View File

@@ -57,27 +57,6 @@ export type {
WorkflowControlResponse,
} from './workflow';
// Team Collaboration Types
export type {
TeamMemberRole,
TeamTaskStatus,
TaskPriority,
TeamMember,
TeamTask,
TaskDeliverable,
ReviewFeedback,
ReviewIssue,
DevQALoopState,
DevQALoop,
CollaborationPattern,
Team,
CollaborationEvent,
TeamMetrics,
CreateTeamRequest,
AddTeamTaskRequest,
TeamResponse,
} from './team';
// Error Types
export {
// Error Code Enum

View File

@@ -1,296 +0,0 @@
/**
* Multi-Agent Team Collaboration Types for OpenFang
*
* This module defines types for multi-agent team orchestration,
* collaboration workflows, and Dev↔QA loops.
*
* @module types/team
*/
import type { AgentStatus } from './agent';
// === Team Definition ===
/**
* Role of an agent within a team
*/
export type TeamMemberRole =
| 'orchestrator' // Team coordinator - assigns tasks, manages flow
| 'developer' // Primary implementation agent
| 'reviewer' // Code review and quality assurance
| 'tester' // Testing and validation
| 'architect' // System design and architecture
| 'specialist'; // Domain-specific expertise
/**
* Possible states for a team task
*/
export type TeamTaskStatus =
| 'pending' // Waiting to be assigned
| 'assigned' // Assigned to an agent but not started
| 'in_progress' // Currently being worked on
| 'review' // Under review by another agent
| 'blocked' // Blocked by dependency or issue
| 'completed' // Successfully completed
| 'failed'; // Failed with error
/**
* Priority levels for team tasks
*/
export type TaskPriority = 'critical' | 'high' | 'medium' | 'low';
/**
* A member of a team (an agent with a specific role)
*/
export interface TeamMember {
/** Unique identifier for this team member */
id: string;
/** ID of the underlying agent */
agentId: string;
/** Agent display name */
name: string;
/** Role within the team */
role: TeamMemberRole;
/** Skills this member contributes */
skills: string[];
/** Current workload (0-100%) */
workload: number;
/** Current status */
status: AgentStatus;
/** Maximum concurrent tasks */
maxConcurrentTasks: number;
/** Current assigned task IDs */
currentTasks: string[];
}
/**
* A task that can be assigned to team members
*/
export interface TeamTask {
/** Unique task identifier */
id: string;
/** Task title */
title: string;
/** Detailed task description */
description?: string;
/** Current status */
status: TeamTaskStatus;
/** Priority level */
priority: TaskPriority;
/** ID of assigned team member */
assigneeId?: string;
/** IDs of tasks this depends on */
dependencies: string[];
/** Task type classification */
type: 'implementation' | 'review' | 'testing' | 'design' | 'deployment';
/** Estimated effort (story points or hours) */
estimate?: number;
/** ISO timestamp of creation */
createdAt: string;
/** ISO timestamp of last update */
updatedAt?: string;
/** ISO timestamp when work started */
startedAt?: string;
/** ISO timestamp of completion */
completedAt?: string;
/** Result or deliverable */
deliverable?: TaskDeliverable;
/** Review feedback if in review */
reviewFeedback?: ReviewFeedback;
}
/**
* Deliverable produced by a task
*/
export interface TaskDeliverable {
/** Type of deliverable */
type: 'code' | 'document' | 'test' | 'config' | 'report';
/** Description of what was produced */
description: string;
/** File paths modified/created */
files?: string[];
/** Key metrics or outcomes */
metrics?: Record<string, number | string>;
}
/**
* Feedback from a review
*/
export interface ReviewFeedback {
/** Review verdict */
verdict: 'approved' | 'needs_work' | 'rejected';
/** Detailed feedback */
comments: string[];
/** Issues found */
issues: ReviewIssue[];
/** ISO timestamp of review */
reviewedAt: string;
/** ID of reviewer */
reviewerId: string;
}
/**
* An issue found during review
*/
export interface ReviewIssue {
/** Issue severity */
severity: 'critical' | 'major' | 'minor' | 'suggestion';
/** Issue description */
description: string;
/** File location if applicable */
file?: string;
/** Line number if applicable */
line?: number;
/** Suggested fix */
suggestion?: string;
}
// === Dev↔QA Loop ===
/**
* States in the Dev↔QA loop
*/
export type DevQALoopState =
| 'idle' // No active loop
| 'developing' // Developer is implementing
| 'reviewing' // QA is reviewing
| 'revising' // Developer is fixing issues
| 'approved' // QA approved the work
| 'escalated'; // Too many retries, needs human intervention
/**
* A Dev↔QA loop instance
*/
export interface DevQALoop {
/** Unique loop identifier */
id: string;
/** ID of the developer agent */
developerId: string;
/** ID of the QA/reviewer agent */
reviewerId: string;
/** Task being worked on */
taskId: string;
/** Current state */
state: DevQALoopState;
/** Number of revision cycles */
iterationCount: number;
/** Maximum iterations before escalation */
maxIterations: number;
/** All feedback history */
feedbackHistory: ReviewFeedback[];
/** ISO timestamp of loop start */
startedAt: string;
/** ISO timestamp of last state change */
lastUpdatedAt: string;
}
// === Team Collaboration ===
/**
* Possible collaboration patterns
*/
export type CollaborationPattern =
| 'sequential' // Tasks completed one after another
| 'parallel' // Tasks completed simultaneously
| 'pipeline' // Output of one feeds into next
| 'review_loop'; // Dev↔QA iteration pattern
/**
* A team collaboration session
*/
export interface Team {
/** Unique team identifier */
id: string;
/** Team name */
name: string;
/** Team description */
description?: string;
/** Team members */
members: TeamMember[];
/** Active tasks */
tasks: TeamTask[];
/** Collaboration pattern */
pattern: CollaborationPattern;
/** Active Dev↔QA loops */
activeLoops: DevQALoop[];
/** Team status */
status: 'active' | 'paused' | 'completed' | 'error';
/** ISO timestamp of creation */
createdAt: string;
/** ISO timestamp of last activity */
updatedAt?: string;
}
/**
* Real-time collaboration event
*/
export interface CollaborationEvent {
/** Event type */
type: 'task_assigned' | 'task_started' | 'task_completed' |
'review_requested' | 'review_submitted' |
'loop_state_change' | 'member_status_change';
/** ID of the team */
teamId: string;
/** ID of the source agent */
sourceAgentId: string;
/** Event payload */
payload: Record<string, unknown>;
/** ISO timestamp */
timestamp: string;
}
/**
* Team performance metrics
*/
export interface TeamMetrics {
/** Total tasks completed */
tasksCompleted: number;
/** Average task completion time (ms) */
avgCompletionTime: number;
/** Review pass rate (0-100) */
passRate: number;
/** Average iterations per task */
avgIterations: number;
/** Escalation count */
escalations: number;
/** Team efficiency score (0-100) */
efficiency: number;
}
// === API Types ===
/**
* Request to create a new team
*/
export interface CreateTeamRequest {
name: string;
description?: string;
memberAgents: Array<{
agentId: string;
role: TeamMemberRole;
}>;
pattern: CollaborationPattern;
}
/**
* Request to add a task to a team
*/
export interface AddTeamTaskRequest {
teamId: string;
title: string;
description?: string;
priority: TaskPriority;
type: TeamTask['type'];
assigneeId?: string;
dependencies?: string[];
estimate?: number;
}
/**
* Response for team operations
*/
export interface TeamResponse {
team: Team;
success: boolean;
error?: string;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,594 +0,0 @@
/**
* Team Client Tests
*
* Tests for OpenFang Team API client.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
TeamAPIError,
listTeams,
getTeam,
createTeam,
updateTeam,
deleteTeam,
addTeamMember,
removeTeamMember,
updateMemberRole,
addTeamTask,
updateTaskStatus,
assignTask,
submitDeliverable,
startDevQALoop,
submitReview,
updateLoopState,
getTeamMetrics,
getTeamEvents,
subscribeToTeamEvents,
teamClient,
} from '../../src/lib/team-client';
import type { Team, TeamMember, TeamTask, TeamMemberRole, DevQALoop } from '../../src/types/team';
// Mock fetch globally
const mockFetch = vi.fn();
const originalFetch = global.fetch;
describe('team-client', () => {
beforeEach(() => {
global.fetch = mockFetch;
mockFetch.mockClear();
});
afterEach(() => {
global.fetch = originalFetch;
mockFetch.mockReset();
});
describe('TeamAPIError', () => {
it('should create error with all properties', () => {
const error = new TeamAPIError('Test error', 404, '/teams/test', { detail: 'test detail' });
expect(error.message).toBe('Test error');
expect(error.statusCode).toBe(404);
expect(error.endpoint).toBe('/teams/test');
expect(error.details).toEqual({ detail: 'test detail' });
});
});
describe('listTeams', () => {
it('should fetch teams list', async () => {
const mockTeams: Team[] = [
{
id: 'team-1',
name: 'Test Team',
members: [],
tasks: [],
pattern: 'sequential',
activeLoops: [],
status: 'active',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T00:00:00Z',
},
];
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => ({ teams: mockTeams, total: 1 }),
});
const result = await listTeams();
expect(mockFetch.mock.calls[0][0]).toContain('/api/teams');
expect(result).toEqual({ teams: mockTeams, total: 1 });
});
});
describe('getTeam', () => {
it('should fetch single team', async () => {
const mockTeam = {
team: {
id: 'team-1',
name: 'Test Team',
members: [],
tasks: [],
pattern: 'sequential' as const,
activeLoops: [],
status: 'active',
createdAt: '2024-01-01T00:00:00Z',
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => mockTeam,
});
const result = await getTeam('team-1');
expect(mockFetch.mock.calls[0][0]).toContain('/api/teams/team-1');
expect(result).toEqual(mockTeam);
});
});
describe('createTeam', () => {
it('should create a new team', async () => {
const createRequest = {
name: 'New Team',
description: 'Test description',
memberAgents: [],
pattern: 'parallel' as const,
};
const mockResponse = {
team: {
id: 'new-team-id',
name: 'New Team',
description: 'Test description',
members: [],
tasks: [],
pattern: 'parallel',
activeLoops: [],
status: 'active',
createdAt: '2024-01-01T00:00:00Z',
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 201,
statusText: 'Created',
json: async () => mockResponse,
});
const result = await createTeam(createRequest);
expect(mockFetch).toHaveBeenCalledWith('/api/teams', expect.objectContaining({
method: 'POST',
}));
expect(result).toEqual(mockResponse);
});
});
describe('updateTeam', () => {
it('should update a team', async () => {
const updateData = { name: 'Updated Team' };
const mockResponse = {
team: {
id: 'team-1',
name: 'Updated Team',
description: 'Test',
members: [],
tasks: [],
pattern: 'sequential' as const,
activeLoops: [],
status: 'active',
createdAt: '2024-01-01T00:00:00Z',
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => mockResponse,
});
const result = await updateTeam('team-1', updateData);
expect(mockFetch).toHaveBeenCalledWith('/api/teams/team-1', expect.objectContaining({
method: 'PUT',
}));
expect(result).toEqual(mockResponse);
});
});
describe('deleteTeam', () => {
it('should delete a team', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => ({ success: true }),
});
const result = await deleteTeam('team-1');
expect(mockFetch).toHaveBeenCalledWith('/api/teams/team-1', expect.objectContaining({
method: 'DELETE',
}));
expect(result).toEqual({ success: true });
});
});
describe('addTeamMember', () => {
it('should add a member to team', async () => {
const mockResponse = {
member: {
id: 'member-1',
agentId: 'agent-1',
name: 'Agent 1',
role: 'developer',
skills: [],
workload: 0,
status: 'idle',
maxConcurrentTasks: 2,
currentTasks: [],
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => mockResponse,
});
const result = await addTeamMember('team-1', 'agent-1', 'developer');
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/teams/team-1/members'),
expect.objectContaining({ method: 'POST' })
);
expect(result).toEqual(mockResponse);
});
});
describe('removeTeamMember', () => {
it('should remove a member from team', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => ({ success: true }),
});
const result = await removeTeamMember('team-1', 'member-1');
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/teams/team-1/members/member-1'),
expect.objectContaining({ method: 'DELETE' })
);
expect(result).toEqual({ success: true });
});
});
describe('updateMemberRole', () => {
it('should update member role', async () => {
const mockResponse = {
member: {
id: 'member-1',
agentId: 'agent-1',
name: 'Agent 1',
role: 'reviewer',
skills: [],
workload: 0,
status: 'idle',
maxConcurrentTasks: 2,
currentTasks: [],
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => mockResponse,
});
const result = await updateMemberRole('team-1', 'member-1', 'reviewer');
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/teams/team-1/members/member-1'),
expect.objectContaining({ method: 'PUT' })
);
expect(result).toEqual(mockResponse);
});
});
describe('addTeamTask', () => {
it('should add a task to team', async () => {
const taskRequest = {
teamId: 'team-1',
title: 'Test Task',
description: 'Test task description',
priority: 'high',
type: 'implementation',
};
const mockResponse = {
task: {
id: 'task-1',
title: 'Test Task',
description: 'Test task description',
status: 'pending',
priority: 'high',
dependencies: [],
type: 'implementation',
createdAt: '2024-01-01T00:00:00Z',
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 201,
statusText: 'Created',
json: async () => mockResponse,
});
const result = await addTeamTask(taskRequest);
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/teams/team-1/tasks'),
expect.objectContaining({ method: 'POST' })
);
expect(result).toEqual(mockResponse);
});
});
describe('updateTaskStatus', () => {
it('should update task status', async () => {
const mockResponse = {
task: {
id: 'task-1',
title: 'Test Task',
status: 'in_progress',
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => mockResponse,
});
const result = await updateTaskStatus('team-1', 'task-1', 'in_progress');
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/teams/team-1/tasks/task-1'),
expect.objectContaining({ method: 'PUT' })
);
expect(result).toEqual(mockResponse);
});
});
describe('assignTask', () => {
it('should assign task to member', async () => {
const mockResponse = {
task: {
id: 'task-1',
title: 'Test Task',
assigneeId: 'member-1',
status: 'assigned',
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => mockResponse,
});
const result = await assignTask('team-1', 'task-1', 'member-1');
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/teams/team-1/tasks/task-1/assign'),
expect.objectContaining({ method: 'POST' })
);
expect(result).toEqual(mockResponse);
});
});
describe('submitDeliverable', () => {
it('should submit deliverable for task', async () => {
const deliverable = {
type: 'code',
description: 'Test deliverable',
files: ['/test/file.ts'],
};
const mockResponse = {
task: {
id: 'task-1',
title: 'Test Task',
deliverable,
status: 'review',
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => mockResponse,
});
const result = await submitDeliverable('team-1', 'task-1', deliverable);
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/teams/team-1/tasks/task-1/deliverable'),
expect.objectContaining({ method: 'POST' })
);
expect(result).toEqual(mockResponse);
});
});
describe('startDevQALoop', () => {
it('should start a DevQA loop', async () => {
const mockResponse = {
loop: {
id: 'loop-1',
developerId: 'dev-1',
reviewerId: 'reviewer-1',
taskId: 'task-1',
state: 'developing',
iterationCount: 0,
maxIterations: 3,
feedbackHistory: [],
startedAt: '2024-01-01T00:00:00Z',
lastUpdatedAt: '2024-01-01T00:00:00Z',
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 201,
statusText: 'Created',
json: async () => mockResponse,
});
const result = await startDevQALoop('team-1', 'task-1', 'dev-1', 'reviewer-1');
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/teams/team-1/loops'),
expect.objectContaining({ method: 'POST' })
);
expect(result).toEqual(mockResponse);
});
});
describe('submitReview', () => {
it('should submit a review', async () => {
const feedback = {
verdict: 'approved',
comments: ['LGTM!'],
issues: [],
};
const mockResponse = {
loop: {
id: 'loop-1',
state: 'approved',
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => mockResponse,
});
const result = await submitReview('team-1', 'loop-1', feedback);
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/teams/team-1/loops/loop-1/review'),
expect.objectContaining({ method: 'POST' })
);
expect(result).toEqual(mockResponse);
});
});
describe('updateLoopState', () => {
it('should update loop state', async () => {
const mockResponse = {
loop: {
id: 'loop-1',
state: 'reviewing',
},
success: true,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => mockResponse,
});
const result = await updateLoopState('team-1', 'loop-1', 'reviewing');
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/teams/team-1/loops/loop-1'),
expect.objectContaining({ method: 'PUT' })
);
expect(result).toEqual(mockResponse);
});
});
describe('getTeamMetrics', () => {
it('should get team metrics', async () => {
const mockMetrics = {
tasksCompleted: 10,
avgCompletionTime: 1000,
passRate: 85,
avgIterations: 1.5,
escalations: 0,
efficiency: 80,
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => mockMetrics,
});
const result = await getTeamMetrics('team-1');
expect(mockFetch.mock.calls[0][0]).toContain('/api/teams/team-1/metrics');
expect(result).toEqual(mockMetrics);
});
});
describe('getTeamEvents', () => {
it('should get team events', async () => {
const mockEvents = [
{
type: 'task_assigned',
teamId: 'team-1',
sourceAgentId: 'agent-1',
payload: {},
timestamp: '2024-01-01T00:00:00Z',
},
];
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
json: async () => ({ events: mockEvents, total: 1 }),
});
const result = await getTeamEvents('team-1', 10);
expect(mockFetch.mock.calls[0][0]).toContain('/api/teams/team-1/events');
expect(result).toEqual({ events: mockEvents, total: 1 });
});
});
describe('subscribeToTeamEvents', () => {
it('should subscribe to team events', () => {
const mockWs = {
readyState: WebSocket.OPEN,
send: vi.fn(),
addEventListener: vi.fn((event, handler) => {
handler('message');
return mockWs;
}),
removeEventListener: vi.fn(),
};
const callback = vi.fn();
const unsubscribe = subscribeToTeamEvents('team-1', callback, mockWs as unknown as WebSocket);
expect(mockWs.send).toHaveBeenCalledWith(JSON.stringify({
type: 'subscribe',
topic: 'team:team-1',
}));
unsubscribe();
expect(mockWs.removeEventListener).toHaveBeenCalled();
expect(mockWs.send).toHaveBeenCalledWith(JSON.stringify({
type: 'unsubscribe',
topic: 'team:team-1',
}));
});
});
describe('teamClient', () => {
it('should export all API functions', () => {
expect(teamClient.listTeams).toBe(listTeams);
expect(teamClient.getTeam).toBe(getTeam);
expect(teamClient.createTeam).toBe(createTeam);
expect(teamClient.updateTeam).toBe(updateTeam);
expect(teamClient.deleteTeam).toBe(deleteTeam);
expect(teamClient.addTeamMember).toBe(addTeamMember);
expect(teamClient.removeTeamMember).toBe(removeTeamMember);
expect(teamClient.updateMemberRole).toBe(updateMemberRole);
expect(teamClient.addTeamTask).toBe(addTeamTask);
expect(teamClient.updateTaskStatus).toBe(updateTaskStatus);
expect(teamClient.assignTask).toBe(assignTask);
expect(teamClient.submitDeliverable).toBe(submitDeliverable);
expect(teamClient.startDevQALoop).toBe(startDevQALoop);
expect(teamClient.submitReview).toBe(submitReview);
expect(teamClient.updateLoopState).toBe(updateLoopState);
expect(teamClient.getTeamMetrics).toBe(getTeamMetrics);
expect(teamClient.getTeamEvents).toBe(getTeamEvents);
expect(teamClient.subscribeToTeamEvents).toBe(subscribeToTeamEvents);
});
});
});

View File

@@ -1,373 +0,0 @@
/**
* Team Store Tests
*
* Tests for multi-agent team collaboration state management.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { useTeamStore } from '../../src/store/teamStore';
import type { Team, TeamMember, TeamTask, CreateTeamRequest, AddTeamTaskRequest, TeamMemberRole } from '../../src/types/team';
import { localStorageMock } from '../setup';
// Mock fetch globally
const mockFetch = vi.fn();
const originalFetch = global.fetch;
describe('teamStore', () => {
beforeEach(() => {
global.fetch = mockFetch;
mockFetch.mockClear();
localStorageMock.clear();
});
afterEach(() => {
global.fetch = originalFetch;
mockFetch.mockReset();
});
describe('Initial State', () => {
it('should have correct initial state', () => {
const store = useTeamStore.getState();
expect(store.teams).toEqual([]);
expect(store.activeTeam).toBeNull();
expect(store.metrics).toBeNull();
expect(store.isLoading).toBe(false);
expect(store.error).toBeNull();
expect(store.selectedTaskId).toBeNull();
expect(store.selectedMemberId).toBeNull();
expect(store.recentEvents).toEqual([]);
});
});
describe('loadTeams', () => {
// Note: This test is skipped because the zustand persist middleware
// interferes with manual localStorage manipulation in tests.
// The persist middleware handles loading automatically.
it.skip('should load teams from localStorage', async () => {
const mockTeams: Team[] = [
{
id: 'team-1',
name: 'Test Team',
members: [],
tasks: [],
pattern: 'sequential',
activeLoops: [],
status: 'active',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T00:00:00Z',
},
];
// Clear any existing data
localStorageMock.clear();
// Set localStorage in the format that zustand persist middleware uses
localStorageMock.setItem('zclaw-teams', JSON.stringify({
state: {
teams: mockTeams,
activeTeam: null
},
version: 0
}));
await useTeamStore.getState().loadTeams();
const store = useTeamStore.getState();
// Check that teams were loaded
expect(store.teams).toHaveLength(1);
expect(store.teams[0].name).toBe('Test Team');
expect(store.isLoading).toBe(false);
});
});
describe('createTeam', () => {
it('should create a new team with members', async () => {
const request: CreateTeamRequest = {
name: 'Dev Team',
description: 'Development team',
memberAgents: [
{ agentId: 'agent-1', role: 'developer' },
{ agentId: 'agent-2', role: 'reviewer' },
],
pattern: 'review_loop',
};
const team = await useTeamStore.getState().createTeam(request);
expect(team).not.toBeNull();
expect(team.name).toBe('Dev Team');
expect(team.description).toBe('Development team');
expect(team.pattern).toBe('review_loop');
expect(team.members).toHaveLength(2);
expect(team.status).toBe('active');
const store = useTeamStore.getState();
expect(store.teams).toHaveLength(1);
expect(store.activeTeam?.id).toBe(team.id);
});
});
describe('deleteTeam', () => {
it('should delete a team', async () => {
// First create a team
const request: CreateTeamRequest = {
name: 'Team to Delete',
memberAgents: [],
pattern: 'sequential',
};
await useTeamStore.getState().createTeam(request);
// Then delete it
const result = await useTeamStore.getState().deleteTeam('team-to-delete-id');
expect(result).toBe(true);
const store = useTeamStore.getState();
expect(store.teams.find(t => t.id === 'team-to-delete-id')).toBeUndefined();
});
});
describe('setActiveTeam', () => {
it('should set active team and update metrics', () => {
const team: Team = {
id: 'team-1',
name: 'Test Team',
members: [],
tasks: [],
pattern: 'sequential',
activeLoops: [],
status: 'active',
createdAt: '2024-01-01T00:00:00Z',
};
useTeamStore.getState().setActiveTeam(team);
const store = useTeamStore.getState();
expect(store.activeTeam).toEqual(team);
expect(store.metrics).not.toBeNull();
});
});
describe('addMember', () => {
let team: Team;
beforeEach(async () => {
const request: CreateTeamRequest = {
name: 'Test Team',
memberAgents: [],
pattern: 'sequential',
};
team = (await useTeamStore.getState().createTeam(request))!;
});
it('should add a member to team', async () => {
const member = await useTeamStore.getState().addMember(team.id, 'agent-1', 'developer');
expect(member).not.toBeNull();
expect(member.agentId).toBe('agent-1');
expect(member.role).toBe('developer');
const store = useTeamStore.getState();
const updatedTeam = store.teams.find(t => t.id === team.id);
expect(updatedTeam?.members).toHaveLength(1);
});
});
describe('removeMember', () => {
let team: Team;
let memberId: string;
beforeEach(async () => {
const request: CreateTeamRequest = {
name: 'Test Team',
memberAgents: [{ agentId: 'agent-1', role: 'developer' }],
pattern: 'sequential',
};
team = (await useTeamStore.getState().createTeam(request))!;
memberId = team.members[0].id;
});
it('should remove a member from team', async () => {
const result = await useTeamStore.getState().removeMember(team.id, memberId);
expect(result).toBe(true);
const store = useTeamStore.getState();
const updatedTeam = store.teams.find(t => t.id === team.id);
expect(updatedTeam?.members).toHaveLength(0);
});
});
describe('addTask', () => {
let team: Team;
beforeEach(async () => {
const request: CreateTeamRequest = {
name: 'Test Team',
memberAgents: [],
pattern: 'sequential',
};
team = (await useTeamStore.getState().createTeam(request))!;
});
it('should add a task to team', async () => {
const taskRequest: AddTeamTaskRequest = {
teamId: team.id,
title: 'Test Task',
description: 'Test task description',
priority: 'high',
type: 'implementation',
};
const task = await useTeamStore.getState().addTask(taskRequest);
expect(task).not.toBeNull();
expect(task.title).toBe('Test Task');
expect(task.status).toBe('pending');
const store = useTeamStore.getState();
const updatedTeam = store.teams.find(t => t.id === team.id);
expect(updatedTeam?.tasks).toHaveLength(1);
});
});
describe('updateTaskStatus', () => {
let team: Team;
let taskId: string;
beforeEach(async () => {
const teamRequest: CreateTeamRequest = {
name: 'Test Team',
memberAgents: [],
pattern: 'sequential',
};
team = (await useTeamStore.getState().createTeam(teamRequest))!;
const taskRequest: AddTeamTaskRequest = {
teamId: team.id,
title: 'Test Task',
priority: 'medium',
type: 'implementation',
};
const task = await useTeamStore.getState().addTask(taskRequest);
taskId = task!.id;
});
it('should update task status to in_progress', async () => {
const result = await useTeamStore.getState().updateTaskStatus(team.id, taskId, 'in_progress');
expect(result).toBe(true);
const store = useTeamStore.getState();
const updatedTeam = store.teams.find(t => t.id === team.id);
const updatedTask = updatedTeam?.tasks.find(t => t.id === taskId);
expect(updatedTask?.status).toBe('in_progress');
expect(updatedTask?.startedAt).toBeDefined();
});
});
describe('startDevQALoop', () => {
let team: Team;
let taskId: string;
let memberId: string;
beforeEach(async () => {
const teamRequest: CreateTeamRequest = {
name: 'Test Team',
memberAgents: [
{ agentId: 'dev-agent', role: 'developer' },
{ agentId: 'qa-agent', role: 'reviewer' },
],
pattern: 'review_loop',
};
team = (await useTeamStore.getState().createTeam(teamRequest))!;
const taskRequest: AddTeamTaskRequest = {
teamId: team.id,
title: 'Test Task',
priority: 'high',
type: 'implementation',
assigneeId: team.members[0].id,
};
const task = await useTeamStore.getState().addTask(taskRequest);
taskId = task!.id;
memberId = team.members[0].id;
});
it('should start a Dev-QA loop', async () => {
const loop = await useTeamStore.getState().startDevQALoop(
team.id,
taskId,
team.members[0].id,
team.members[1].id
);
expect(loop).not.toBeNull();
expect(loop.state).toBe('developing');
expect(loop.developerId).toBe(team.members[0].id);
expect(loop.reviewerId).toBe(team.members[1].id);
const store = useTeamStore.getState();
const updatedTeam = store.teams.find(t => t.id === team.id);
expect(updatedTeam?.activeLoops).toHaveLength(1);
});
});
describe('submitReview', () => {
let team: Team;
let loop: any;
beforeEach(async () => {
const teamRequest: CreateTeamRequest = {
name: 'Test Team',
memberAgents: [
{ agentId: 'dev-agent', role: 'developer' },
{ agentId: 'qa-agent', role: 'reviewer' },
],
pattern: 'review_loop',
};
team = (await useTeamStore.getState().createTeam(teamRequest))!;
const taskRequest: AddTeamTaskRequest = {
teamId: team.id,
title: 'Test Task',
priority: 'high',
type: 'implementation',
assigneeId: team.members[0].id,
};
const task = await useTeamStore.getState().addTask(taskRequest);
loop = await useTeamStore.getState().startDevQALoop(
team.id,
task!.id,
team.members[0].id,
team.members[1].id
);
});
it('should submit review and update loop state', async () => {
const feedback = {
verdict: 'approved',
comments: ['Good work!'],
issues: [],
};
const result = await useTeamStore.getState().submitReview(team.id, loop.id, feedback);
expect(result).toBe(true);
const store = useTeamStore.getState();
const updatedTeam = store.teams.find(t => t.id === team.id);
const updatedLoop = updatedTeam?.activeLoops.find(l => l.id === loop.id);
expect(updatedLoop?.state).toBe('approved');
});
});
describe('addEvent', () => {
it('should add event to recent events', () => {
const event = {
type: 'task_completed',
teamId: 'team-1',
sourceAgentId: 'agent-1',
payload: { taskId: 'task-1' },
timestamp: new Date().toISOString(),
};
useTeamStore.getState().addEvent(event);
const store = useTeamStore.getState();
expect(store.recentEvents).toHaveLength(1);
expect(store.recentEvents[0]).toEqual(event);
});
});
describe('clearEvents', () => {
it('should clear all events', () => {
const event = {
type: 'task_completed',
teamId: 'team-1',
sourceAgentId: 'agent-1',
payload: {},
timestamp: new Date().toISOString(),
};
useTeamStore.getState().addEvent(event);
useTeamStore.getState().clearEvents();
const store = useTeamStore.getState();
expect(store.recentEvents).toHaveLength(0);
});
});
describe('UI Actions', () => {
it('should set selected task', () => {
useTeamStore.getState().setSelectedTask('task-1');
expect(useTeamStore.getState().selectedTaskId).toBe('task-1');
});
it('should set selected member', () => {
useTeamStore.getState().setSelectedMember('member-1');
expect(useTeamStore.getState().selectedMemberId).toBe('member-1');
});
it('should clear error', () => {
useTeamStore.setState({ error: 'Test error' });
useTeamStore.getState().clearError();
expect(useTeamStore.getState().error).toBeNull();
});
});
});

View File

@@ -27,8 +27,6 @@
| [01-agent-clones.md](01-core-features/01-agent-clones.md) | Agent 分身 | L4 | 高 |
| [02-hands-system.md](01-core-features/02-hands-system.md) | Hands 系统 | L3 | 中 |
| [03-workflow-engine.md](01-core-features/03-workflow-engine.md) | 工作流引擎 | L3 | 中 |
| [04-team-collaboration.md](01-core-features/04-team-collaboration.md) | 团队协作 | L3 | 中 |
| [05-swarm-coordination.md](01-core-features/05-swarm-coordination.md) | 多 Agent 协作 | L4 | 高 |
### 1.3 智能层 (Intelligence Layer) - ✅ 完全集成 (2026-03-24 更新)
@@ -164,7 +162,7 @@
| 身份演化 | 8 | 9 | 9 | 648 | 已完成 |
| 上下文压缩 | 9 | 8 | 6 | 432 | 已完成 |
| 心跳巡检 | 9 | 8 | 6 | 432 | 已完成 |
| 多 Agent 协作 | 9 | 6 | 4 | 216 | 已完成 |
| 多 Agent 协作 | 9 | 6 | 4 | 216 | 已移除Pipeline 替代) |
| 自主授权 | 8 | 7 | 5 | 280 | 已完成 |
| 向量记忆 | 9 | 7 | 5 | 315 | 已完成 |
| 会话持久化 | 7 | 9 | 8 | 504 | 已完成 |
@@ -194,7 +192,7 @@
```
┌─────────────────────────────────────────────────────────────┐
│ UI 组件层 │
│ ChatArea │ SwarmDashboard │ RightPanel │ Settings │
│ ChatArea │ PipelinesPanel │ RightPanel │ Settings │
└─────────────────────────────┬───────────────────────────────┘
┌─────────────────────────────▼───────────────────────────────┐
@@ -280,6 +278,7 @@ skills hands protocols pipeline growth channels
| 日期 | 版本 | 变更内容 |
|------|------|---------|
| 2026-03-26 | v0.1.0 | **v1.0 发布准备**:移除 Team/Swarm 功能(~8,100 行Pipeline 替代安全修复CI/CD 建立 |
| 2026-03-26 | v0.5.0 | **Smart Presentation Layer**自动类型检测Chart/Quiz/Slideshow/Document 渲染器PresentationAnalyzer Rust 后端 |
| 2026-03-25 | v0.4.0 | **代码现状深度分析**8 个 Rust Crates 完整度评估78+ 技能确认18+ Store 状态管理,新增 Mesh/Persona 智能组件 |
| 2026-03-25 | v0.3.0 | **Pipeline DSL 系统实现**5 类 Pipeline 模板Agent 智能推荐,结果预览组件 |

View File

@@ -1,138 +0,0 @@
# 团队功能开发笔记
**完成日期**: 2026-03-19
**任务**: 修复团队功能页面空白问题
---
## 一、问题描述
点击"团队"导航后,页面显示空白,控制台报错 `teams.map is not a function`
## 二、根因分析
### 2.1 数据格式冲突
Zustand 的 `persist` 中间件存储格式为:
```json
{
"state": { "teams": [...], "activeTeam": ... },
"version": 0
}
```
`loadTeams` 函数期望的是直接的数组格式 `Team[]`
### 2.2 类型安全问题
TeamList 组件中的 `availableAgents` 变量使用了条件表达式,返回类型不一致:
- `clones``Clone[]` 类型
- `agents.map(...)` 返回的是 `{ id, name, role }[]` 类型
TypeScript 无法推断统一类型,运行时可能导致错误。
## 三、解决方案
### 3.1 修复 loadTeams 函数
```typescript
loadTeams: async () => {
set({ isLoading: true, error: null });
try {
const stored = localStorage.getItem('zclaw-teams');
let teams: Team[] = [];
if (stored) {
const parsed = JSON.parse(stored);
// 处理 persist 中间件格式
if (parsed?.state?.teams && Array.isArray(parsed.state.teams)) {
teams = parsed.state.teams;
} else if (Array.isArray(parsed)) {
teams = parsed;
}
}
set({ teams, isLoading: false });
} catch (error) {
set({ teams: [], isLoading: false });
}
},
```
### 3.2 修复 availableAgents 类型
```typescript
const availableAgents: Array<{ id: string; name: string; role?: string }> =
(clones && clones.length > 0)
? clones.map(c => ({ id: c.id, name: c.name, role: c.role }))
: (agents && agents.length > 0)
? agents.map(a => ({ id: a.id, name: a.name, role: '默认助手' }))
: [];
```
### 3.3 添加防御性检查
```typescript
// TeamList.tsx
{!Array.isArray(teams) || teams.length === 0 ? (
<EmptyState ... />
) : (
teams.map(...)
)}
```
## 四、相关文件
| 文件 | 修改内容 |
|------|----------|
| `store/teamStore.ts` | loadTeams 函数处理 persist 格式 |
| `components/TeamList.tsx` | 类型修复、防御性检查、中文化 |
| `components/ui/EmptyState.tsx` | CSS 修复 (flex-1 → h-full) |
| `App.tsx` | motion.main 添加 flex flex-col |
## 五、经验教训
1. **persist 中间件存储格式**: Zustand persist 存储的是 `{ state, version }` 结构,不是直接的状态值
2. **条件表达式类型一致性**: 三元表达式的两个分支必须返回相同类型
3. **防御性编程**: 对从 store 获取的数据进行 Array.isArray 检查
---
*文档创建: 2026-03-19*
---
## 六、协作功能修复 (2026-03-19)
### 6.1 问题描述
1. **UI 颜色不一致**: SwarmDashboard 使用蓝色(blue-500)作为主色调,与系统的橙色/灰色风格不匹配
2. **内容重复渲染**: 左侧边栏和主内容区同时渲染 SwarmDashboard导致内容重复
### 6.2 解决方案
**问题 1: 内容重复**
-`Sidebar.tsx` 移除 `{activeTab === 'swarm' && <SwarmDashboard />}` 渲染
- 只保留 `App.tsx` 中的主内容区渲染
- 移除未使用的 `import { SwarmDashboard }` 语句
**问题 2: 颜色一致性**
修改 `SwarmDashboard.tsx` 中的配色:
- 主色调: `blue-500``orange-500`
- 按钮背景: `bg-blue-500``bg-orange-500`
- Filter tabs: `bg-blue-100``bg-orange-100`
- 选中边框: `border-blue-500``border-orange-500`
- Focus ring: `ring-blue-500``ring-orange-500`
- 保留执行状态(`executing`/`running`)的蓝色作为状态指示色
### 6.3 相关文件
| 文件 | 修改内容 |
|------|----------|
| `components/Sidebar.tsx` | 移除 SwarmDashboard 渲染和 import |
| `components/SwarmDashboard.tsx` | 配色从蓝色改为橙色 |
### 6.4 设计原则
1. **单一渲染原则**: 每个视图组件只在唯一位置渲染,避免多处同时显示
2. **颜色一致性**: 交互元素使用系统主色调(橙色),状态指示可保留语义色(蓝色=执行中,绿色=完成,红色=失败)

View File

@@ -1,517 +0,0 @@
/**
* Team Store Tests
*
* Unit tests for multi-agent team collaboration state management.
*
* @module tests/desktop/teamStore.test
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
// Mock localStorage
const localStorageMock = (() => {
let store: Record<string, string> = {};
return {
getItem: vi.fn((key: string) => store[key] || null),
setItem: vi.fn((key: string, value: string) => {
store[key] = value;
}),
removeItem: vi.fn((key: string) => {
delete store[key];
}),
clear: vi.fn(() => {
store = {};
}),
};
})();
Object.defineProperty(global, 'localStorage', {
value: localStorageMock,
});
// Import store after mocking
import { useTeamStore } from '../../desktop/src/store/teamStore';
import type { Team, TeamMember, TeamTask, DevQALoop } from '../../desktop/src/types/team';
describe('TeamStore', () => {
beforeEach(() => {
// Reset store state and localStorage
localStorageMock.clear();
useTeamStore.setState({
teams: [],
activeTeam: null,
metrics: null,
isLoading: false,
error: null,
selectedTaskId: null,
selectedMemberId: null,
recentEvents: [],
});
});
describe('loadTeams', () => {
it('should load teams from localStorage', async () => {
const mockTeams: Team[] = [
{
id: 'team-1',
name: 'Test Team',
description: 'A test team',
status: 'active',
pattern: 'sequential',
members: [],
tasks: [],
loops: [],
createdAt: '2026-03-15T00:00:00Z',
},
];
localStorageMock.getItem.mockReturnValueOnce(JSON.stringify(mockTeams));
const { loadTeams } = useTeamStore.getState();
await loadTeams();
const state = useTeamStore.getState();
expect(state.teams).toHaveLength(1);
expect(state.teams[0].name).toBe('Test Team');
});
it('should handle empty localStorage', async () => {
localStorageMock.getItem.mockReturnValueOnce(null);
const { loadTeams } = useTeamStore.getState();
await loadTeams();
const state = useTeamStore.getState();
expect(state.teams).toHaveLength(0);
});
});
describe('createTeam', () => {
it('should create a new team with members', async () => {
const request = {
name: 'New Team',
description: 'A new team for testing',
pattern: 'parallel' as const,
memberAgents: [
{ agentId: 'agent-1', role: 'orchestrator' as const },
{ agentId: 'agent-2', role: 'developer' as const },
],
};
const { createTeam } = useTeamStore.getState();
const team = await createTeam(request);
expect(team).not.toBeNull();
expect(team?.name).toBe('New Team');
expect(team?.pattern).toBe('parallel');
expect(team?.members).toHaveLength(2);
expect(team?.members[0].role).toBe('orchestrator');
const state = useTeamStore.getState();
expect(state.teams).toHaveLength(1);
});
});
describe('setActiveTeam', () => {
it('should set active team and calculate metrics', () => {
const mockTeam: Team = {
id: 'team-1',
name: 'Test Team',
description: 'A test team',
status: 'active',
pattern: 'sequential',
members: [
{
id: 'member-1',
agentId: 'agent-1',
name: 'Developer 1',
role: 'developer',
status: 'idle',
skills: [],
workload: 0,
currentTasks: [],
maxConcurrentTasks: 2,
},
],
tasks: [
{
id: 'task-1',
title: 'Completed Task',
description: 'A completed task',
status: 'completed',
priority: 'medium',
type: 'feature',
assigneeId: 'member-1',
createdAt: '2026-03-15T00:00:00Z',
updatedAt: '2026-03-15T01:00:00Z',
},
],
activeLoops: [],
createdAt: '2026-03-15T00:00:00Z',
};
const { setActiveTeam } = useTeamStore.getState();
setActiveTeam(mockTeam);
const state = useTeamStore.getState();
expect(state.activeTeam).toEqual(mockTeam);
expect(state.metrics).not.toBeNull();
expect(state.metrics?.tasksCompleted).toBe(1);
});
it('should clear active team when passed null', () => {
const { setActiveTeam } = useTeamStore.getState();
// First set a team
setActiveTeam({
id: 'team-1',
name: 'Test',
description: '',
status: 'active',
pattern: 'sequential',
members: [],
tasks: [],
activeLoops: [],
createdAt: '2026-03-15T00:00:00Z',
});
// Then clear it
setActiveTeam(null);
const state = useTeamStore.getState();
expect(state.activeTeam).toBeNull();
expect(state.metrics).toBeNull();
});
});
describe('addMember', () => {
it('should add a member to a team', async () => {
// Setup: create a team first
const { createTeam, addMember } = useTeamStore.getState();
await createTeam({
name: 'Test Team',
description: '',
pattern: 'sequential',
memberAgents: [{ agentId: 'agent-1', role: 'orchestrator' }],
});
const teamId = useTeamStore.getState().teams[0].id;
const member = await addMember(teamId, 'agent-2', 'developer');
expect(member).not.toBeNull();
expect(member?.role).toBe('developer');
expect(member?.agentId).toBe('agent-2');
const state = useTeamStore.getState();
expect(state.teams[0].members).toHaveLength(2);
});
});
describe('addTask', () => {
it('should add a task to a team', async () => {
const { createTeam, addTask } = useTeamStore.getState();
await createTeam({
name: 'Test Team',
description: '',
pattern: 'sequential',
memberAgents: [{ agentId: 'agent-1', role: 'orchestrator' }],
});
const teamId = useTeamStore.getState().teams[0].id;
const task = await addTask({
teamId,
title: 'New Task',
description: 'A new task for testing',
priority: 'high',
type: 'feature',
});
expect(task).not.toBeNull();
expect(task?.title).toBe('New Task');
expect(task?.status).toBe('pending');
const state = useTeamStore.getState();
expect(state.teams[0].tasks).toHaveLength(1);
});
});
describe('updateTaskStatus', () => {
it('should update task status', async () => {
const { createTeam, addTask, updateTaskStatus } = useTeamStore.getState();
await createTeam({
name: 'Test Team',
description: '',
pattern: 'sequential',
memberAgents: [{ agentId: 'agent-1', role: 'orchestrator' }],
});
const teamId = useTeamStore.getState().teams[0].id;
await addTask({
teamId,
title: 'Test Task',
description: '',
priority: 'medium',
type: 'feature',
});
const taskId = useTeamStore.getState().teams[0].tasks[0].id;
await updateTaskStatus(teamId, taskId, 'in_progress');
const state = useTeamStore.getState();
expect(state.teams[0].tasks[0].status).toBe('in_progress');
});
});
describe('assignTask', () => {
it('should assign task to a member', async () => {
const { createTeam, addTask, assignTask } = useTeamStore.getState();
await createTeam({
name: 'Test Team',
description: '',
pattern: 'sequential',
memberAgents: [
{ agentId: 'agent-1', role: 'orchestrator' },
{ agentId: 'agent-2', role: 'developer' },
],
});
const state1 = useTeamStore.getState();
const teamId = state1.teams[0].id;
const memberId = state1.teams[0].members[1].id;
await addTask({
teamId,
title: 'Test Task',
description: '',
priority: 'medium',
type: 'feature',
});
const taskId = useTeamStore.getState().teams[0].tasks[0].id;
await assignTask(teamId, taskId, memberId);
const state2 = useTeamStore.getState();
expect(state2.teams[0].tasks[0].assigneeId).toBe(memberId);
expect(state2.teams[0].tasks[0].status).toBe('assigned');
});
});
describe('startDevQALoop', () => {
it('should start a Dev↔QA loop', async () => {
const { createTeam, addTask, startDevQALoop } = useTeamStore.getState();
await createTeam({
name: 'Test Team',
description: '',
pattern: 'review_loop',
memberAgents: [
{ agentId: 'agent-1', role: 'orchestrator' },
{ agentId: 'agent-2', role: 'developer' },
{ agentId: 'agent-3', role: 'reviewer' },
],
});
const state1 = useTeamStore.getState();
const teamId = state1.teams[0].id;
const developerId = state1.teams[0].members[1].id;
const reviewerId = state1.teams[0].members[2].id;
await addTask({
teamId,
title: 'Code Task',
description: '',
priority: 'high',
type: 'feature',
});
const taskId = useTeamStore.getState().teams[0].tasks[0].id;
const loop = await startDevQALoop(teamId, taskId, developerId, reviewerId);
expect(loop).not.toBeNull();
expect(loop?.state).toBe('developing');
expect(loop?.developerId).toBe(developerId);
expect(loop?.reviewerId).toBe(reviewerId);
const state2 = useTeamStore.getState();
expect(state2.teams[0].activeLoops).toHaveLength(1);
});
});
describe('submitReview', () => {
it('should submit review feedback', async () => {
const { createTeam, addTask, startDevQALoop, submitReview } = useTeamStore.getState();
await createTeam({
name: 'Test Team',
description: '',
pattern: 'review_loop',
memberAgents: [
{ agentId: 'agent-1', role: 'orchestrator' },
{ agentId: 'agent-2', role: 'developer' },
{ agentId: 'agent-3', role: 'reviewer' },
],
});
const state1 = useTeamStore.getState();
const teamId = state1.teams[0].id;
const developerId = state1.teams[0].members[1].id;
const reviewerId = state1.teams[0].members[2].id;
await addTask({
teamId,
title: 'Code Task',
description: '',
priority: 'high',
type: 'feature',
});
const taskId = useTeamStore.getState().teams[0].tasks[0].id;
await startDevQALoop(teamId, taskId, developerId, reviewerId);
const loopId = useTeamStore.getState().teams[0].activeLoops[0].id;
await submitReview(teamId, loopId, {
verdict: 'needs_work',
comments: ['Please fix the bug'],
issues: [
{ severity: 'major', description: 'Null pointer exception', file: 'main.ts', line: 42 },
],
});
const state2 = useTeamStore.getState();
expect(state2.teams[0].activeLoops[0].state).toBe('revising');
expect(state2.teams[0].activeLoops[0].feedbackHistory).toHaveLength(1);
});
it('should approve task when verdict is approved', async () => {
const { createTeam, addTask, startDevQALoop, submitReview } = useTeamStore.getState();
await createTeam({
name: 'Test Team',
description: '',
pattern: 'review_loop',
memberAgents: [
{ agentId: 'agent-1', role: 'orchestrator' },
{ agentId: 'agent-2', role: 'developer' },
{ agentId: 'agent-3', role: 'reviewer' },
],
});
const state1 = useTeamStore.getState();
const teamId = state1.teams[0].id;
const developerId = state1.teams[0].members[1].id;
const reviewerId = state1.teams[0].members[2].id;
await addTask({
teamId,
title: 'Code Task',
description: '',
priority: 'high',
type: 'feature',
});
const taskId = useTeamStore.getState().teams[0].tasks[0].id;
await startDevQALoop(teamId, taskId, developerId, reviewerId);
const loopId = useTeamStore.getState().teams[0].activeLoops[0].id;
await submitReview(teamId, loopId, {
verdict: 'approved',
comments: ['Great work!'],
issues: [],
});
const state2 = useTeamStore.getState();
expect(state2.teams[0].activeLoops[0].state).toBe('approved');
});
});
describe('addEvent', () => {
it('should add collaboration event', () => {
const { addEvent } = useTeamStore.getState();
addEvent({
type: 'task_assigned',
teamId: 'team-1',
sourceAgentId: 'agent-1',
payload: { taskId: 'task-1' },
timestamp: new Date().toISOString(),
});
const state = useTeamStore.getState();
expect(state.recentEvents).toHaveLength(1);
expect(state.recentEvents[0].type).toBe('task_assigned');
});
it('should limit events to max 100', () => {
const { addEvent } = useTeamStore.getState();
// Add 105 events
for (let i = 0; i < 105; i++) {
addEvent({
type: 'task_assigned',
teamId: 'team-1',
sourceAgentId: 'agent-1',
payload: { index: i },
timestamp: new Date().toISOString(),
});
}
const state = useTeamStore.getState();
expect(state.recentEvents).toHaveLength(100);
// Most recent event should be at index 0
expect(state.recentEvents[0].payload.index).toBe(104);
// Oldest kept event should be at index 99 (events 0-4 are discarded)
expect(state.recentEvents[99].payload.index).toBe(5);
});
});
describe('deleteTeam', () => {
it('should delete a team', async () => {
const { createTeam, deleteTeam } = useTeamStore.getState();
await createTeam({
name: 'Team to Delete',
description: '',
pattern: 'sequential',
memberAgents: [{ agentId: 'agent-1', role: 'orchestrator' }],
});
const teamId = useTeamStore.getState().teams[0].id;
await deleteTeam(teamId);
const state = useTeamStore.getState();
expect(state.teams).toHaveLength(0);
});
it('should clear active team if deleted', async () => {
const { createTeam, setActiveTeam, deleteTeam } = useTeamStore.getState();
await createTeam({
name: 'Team to Delete',
description: '',
pattern: 'sequential',
memberAgents: [{ agentId: 'agent-1', role: 'orchestrator' }],
});
const teamId = useTeamStore.getState().teams[0].id;
const team = useTeamStore.getState().teams[0];
setActiveTeam(team);
await deleteTeam(teamId);
const state = useTeamStore.getState();
expect(state.activeTeam).toBeNull();
});
});
});