All files / src/components TeamCollaborationView.tsx

0% Statements 0/300
0% Branches 0/1
0% Functions 0/1
0% Lines 0/300

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * 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;