feat(frontend): Implement project dashboard, issues, and project wizard (#40, #42, #48, #50)

Merge feature/40-project-dashboard branch into dev.

This comprehensive merge includes:

## Project Dashboard (#40)
- ProjectDashboard component with stats and activity
- ProjectHeader, SprintProgress, BurndownChart components
- AgentPanel for viewing project agents
- StatusBadge, ProgressBar, IssueSummary components
- Real-time activity integration

## Issue Management (#42)
- Issue list and detail pages
- IssueFilters, IssueTable, IssueDetailPanel components
- StatusWorkflow, PriorityBadge, SyncStatusIndicator
- ActivityTimeline, BulkActions components
- useIssues hook with TanStack Query

## Main Dashboard (#48)
- Main dashboard page implementation
- Projects list with grid/list view toggle

## Project Creation Wizard (#50)
- Multi-step wizard (6 steps)
- SelectableCard, StepIndicator components
- Wizard steps: BasicInfo, Complexity, ClientMode, Autonomy, AgentChat, Review
- Form validation with useWizardState hook

Includes comprehensive unit tests and E2E tests.

Closes #40, #42, #48, #50

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2025-12-31 11:19:07 +01:00
68 changed files with 8896 additions and 0 deletions

View File

@@ -0,0 +1,242 @@
/**
* Agent Panel Component
*
* Displays a list of active agents on the project with their status and current task.
*/
'use client';
import { Bot, MoreVertical } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Skeleton } from '@/components/ui/skeleton';
import { AgentStatusIndicator } from './AgentStatusIndicator';
import type { AgentInstance } from './types';
// ============================================================================
// Types
// ============================================================================
interface AgentPanelProps {
/** List of agent instances */
agents: AgentInstance[];
/** Whether data is loading */
isLoading?: boolean;
/** Callback when "Manage Agents" is clicked */
onManageAgents?: () => void;
/** Callback when an agent action is triggered */
onAgentAction?: (agentId: string, action: 'view' | 'pause' | 'restart' | 'terminate') => void;
/** Additional CSS classes */
className?: string;
}
// ============================================================================
// Helper Functions
// ============================================================================
function getAgentAvatarText(agent: AgentInstance): string {
if (agent.avatar) return agent.avatar;
// Generate initials from role
const words = agent.role.split(/[\s_-]+/);
if (words.length >= 2) {
return (words[0][0] + words[1][0]).toUpperCase();
}
return agent.role.substring(0, 2).toUpperCase();
}
function formatLastActivity(lastActivity?: string): string {
if (!lastActivity) return 'No activity';
try {
return formatDistanceToNow(new Date(lastActivity), { addSuffix: true });
} catch {
return 'Unknown';
}
}
// ============================================================================
// Subcomponents
// ============================================================================
function AgentListItem({
agent,
onAction,
}: {
agent: AgentInstance;
onAction?: (agentId: string, action: 'view' | 'pause' | 'restart' | 'terminate') => void;
}) {
const avatarText = getAgentAvatarText(agent);
const lastActivity = formatLastActivity(agent.last_activity_at);
return (
<div
className="flex items-center justify-between rounded-lg border p-3 transition-colors hover:bg-muted/50"
data-testid={`agent-item-${agent.id}`}
>
<div className="flex items-center gap-3">
{/* Avatar */}
<div
className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-sm font-medium text-primary"
aria-hidden="true"
>
{avatarText}
</div>
{/* Info */}
<div>
<div className="flex items-center gap-2">
<span className="font-medium">{agent.name}</span>
<AgentStatusIndicator status={agent.status} />
</div>
<p className="text-sm text-muted-foreground line-clamp-1">
{agent.current_task || 'No active task'}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">{lastActivity}</span>
{onAction && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
aria-label={`Actions for ${agent.name}`}
>
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => onAction(agent.id, 'view')}>
View Details
</DropdownMenuItem>
{agent.status === 'active' || agent.status === 'working' ? (
<DropdownMenuItem onClick={() => onAction(agent.id, 'pause')}>
Pause Agent
</DropdownMenuItem>
) : (
<DropdownMenuItem onClick={() => onAction(agent.id, 'restart')}>
Restart Agent
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => onAction(agent.id, 'terminate')}
className="text-destructive focus:text-destructive"
>
Terminate Agent
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</div>
);
}
function AgentPanelSkeleton() {
return (
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="space-y-2">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-4 w-48" />
</div>
<Skeleton className="h-9 w-28" />
</div>
</CardHeader>
<CardContent>
<div className="space-y-3">
{[1, 2, 3].map((i) => (
<div key={i} className="flex items-center gap-3 rounded-lg border p-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-3 w-48" />
</div>
<Skeleton className="h-8 w-8" />
</div>
))}
</div>
</CardContent>
</Card>
);
}
// ============================================================================
// Main Component
// ============================================================================
export function AgentPanel({
agents,
isLoading = false,
onManageAgents,
onAgentAction,
className,
}: AgentPanelProps) {
if (isLoading) {
return <AgentPanelSkeleton />;
}
const activeAgentCount = agents.filter(
(a) => a.status === 'active' || a.status === 'working'
).length;
return (
<Card className={className} data-testid="agent-panel">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div>
<CardTitle className="flex items-center gap-2">
<Bot className="h-5 w-5" aria-hidden="true" />
Active Agents
</CardTitle>
<CardDescription>
{activeAgentCount} of {agents.length} agents working
</CardDescription>
</div>
{onManageAgents && (
<Button variant="outline" size="sm" onClick={onManageAgents}>
Manage Agents
</Button>
)}
</div>
</CardHeader>
<CardContent>
{agents.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-center text-muted-foreground">
<Bot className="mb-2 h-8 w-8" aria-hidden="true" />
<p className="text-sm">No agents assigned to this project</p>
</div>
) : (
<div className="space-y-3">
{agents.map((agent) => (
<AgentListItem
key={agent.id}
agent={agent}
onAction={onAgentAction}
/>
))}
</div>
)}
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,79 @@
/**
* Agent Status Indicator
*
* Visual indicator for agent status (idle, working, error, etc.)
*/
'use client';
import { cn } from '@/lib/utils';
import type { AgentStatus } from './types';
const statusConfig: Record<AgentStatus, { color: string; label: string }> = {
idle: {
color: 'bg-yellow-500',
label: 'Idle',
},
active: {
color: 'bg-green-500',
label: 'Active',
},
working: {
color: 'bg-green-500 animate-pulse',
label: 'Working',
},
pending: {
color: 'bg-gray-400',
label: 'Pending',
},
error: {
color: 'bg-red-500',
label: 'Error',
},
terminated: {
color: 'bg-gray-600',
label: 'Terminated',
},
};
interface AgentStatusIndicatorProps {
status: AgentStatus;
size?: 'sm' | 'md' | 'lg';
showLabel?: boolean;
className?: string;
}
export function AgentStatusIndicator({
status,
size = 'sm',
showLabel = false,
className,
}: AgentStatusIndicatorProps) {
const config = statusConfig[status] || statusConfig.pending;
const sizeClasses = {
sm: 'h-2 w-2',
md: 'h-3 w-3',
lg: 'h-4 w-4',
};
return (
<span
className={cn('inline-flex items-center gap-1.5', className)}
role="status"
aria-label={`Status: ${config.label}`}
>
<span
className={cn(
'inline-block rounded-full',
sizeClasses[size],
config.color
)}
aria-hidden="true"
/>
{showLabel && (
<span className="text-xs text-muted-foreground">{config.label}</span>
)}
</span>
);
}

View File

@@ -0,0 +1,146 @@
/**
* Burndown Chart Component
*
* Simple SVG-based burndown chart showing actual vs ideal progress.
* This is a placeholder that will be enhanced when a charting library is integrated.
*/
'use client';
import { cn } from '@/lib/utils';
import type { BurndownDataPoint } from './types';
interface BurndownChartProps {
/** Burndown data points */
data: BurndownDataPoint[];
/** Chart height */
height?: number;
/** Additional CSS classes */
className?: string;
/** Show legend */
showLegend?: boolean;
}
export function BurndownChart({
data,
height = 120,
className,
showLegend = true,
}: BurndownChartProps) {
if (data.length === 0) {
return (
<div
className={cn(
'flex items-center justify-center rounded-md border border-dashed p-4 text-sm text-muted-foreground',
className
)}
style={{ height }}
>
No burndown data available
</div>
);
}
const chartWidth = 100;
const chartHeight = height;
const padding = { top: 10, right: 10, bottom: 20, left: 10 };
const innerWidth = chartWidth - padding.left - padding.right;
const innerHeight = chartHeight - padding.top - padding.bottom;
const maxPoints = Math.max(...data.map((d) => Math.max(d.remaining, d.ideal)));
// Generate points for polylines
const getPoints = (key: 'remaining' | 'ideal') => {
return data
.map((d, i) => {
const x = padding.left + (i / (data.length - 1)) * innerWidth;
const y = padding.top + innerHeight - (d[key] / maxPoints) * innerHeight;
return `${x},${y}`;
})
.join(' ');
};
return (
<div className={cn('w-full', className)}>
<div className="relative" style={{ height }}>
<svg
viewBox={`0 0 ${chartWidth} ${chartHeight}`}
className="h-full w-full"
preserveAspectRatio="none"
role="img"
aria-label="Sprint burndown chart showing actual progress versus ideal progress"
>
{/* Grid lines */}
<g className="text-muted stroke-current opacity-20">
{[0, 0.25, 0.5, 0.75, 1].map((ratio) => (
<line
key={ratio}
x1={padding.left}
y1={padding.top + innerHeight * ratio}
x2={padding.left + innerWidth}
y2={padding.top + innerHeight * ratio}
strokeWidth="0.5"
/>
))}
</g>
{/* Ideal line (dashed) */}
<polyline
fill="none"
stroke="currentColor"
strokeOpacity="0.3"
strokeWidth="1"
strokeDasharray="4,2"
points={getPoints('ideal')}
/>
{/* Actual line */}
<polyline
fill="none"
stroke="currentColor"
className="text-primary"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
points={getPoints('remaining')}
/>
{/* Data points on actual line */}
{data.map((d, i) => {
const x = padding.left + (i / (data.length - 1)) * innerWidth;
const y = padding.top + innerHeight - (d.remaining / maxPoints) * innerHeight;
return (
<circle
key={i}
cx={x}
cy={y}
r="2"
className="fill-primary"
/>
);
})}
</svg>
{/* X-axis labels */}
<div className="absolute bottom-0 left-0 right-0 flex justify-between text-xs text-muted-foreground">
<span>Day 1</span>
<span>Day {data.length}</span>
</div>
</div>
{/* Legend */}
{showLegend && (
<div className="mt-2 flex items-center justify-center gap-6 text-xs text-muted-foreground">
<span className="flex items-center gap-1">
<span className="h-0.5 w-4 bg-primary" />
Actual
</span>
<span className="flex items-center gap-1">
<span className="h-0.5 w-4 border-t border-dashed border-muted-foreground" />
Ideal
</span>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,194 @@
/**
* Issue Summary Component
*
* Sidebar component showing issue counts by status.
*/
'use client';
import {
GitBranch,
CircleDot,
PlayCircle,
Clock,
AlertCircle,
CheckCircle2,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import type { IssueSummary as IssueSummaryType } from './types';
// ============================================================================
// Types
// ============================================================================
interface IssueSummaryProps {
/** Issue summary data */
summary: IssueSummaryType | null;
/** Whether data is loading */
isLoading?: boolean;
/** Callback when "View All Issues" is clicked */
onViewAllIssues?: () => void;
/** Additional CSS classes */
className?: string;
}
interface StatusRowProps {
icon: React.ElementType;
iconColor: string;
label: string;
count: number;
}
// ============================================================================
// Subcomponents
// ============================================================================
function StatusRow({ icon: Icon, iconColor, label, count }: StatusRowProps) {
return (
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Icon className={cn('h-4 w-4', iconColor)} aria-hidden="true" />
<span className="text-sm">{label}</span>
</div>
<span className="font-medium">{count}</span>
</div>
);
}
function IssueSummarySkeleton() {
return (
<Card>
<CardHeader className="pb-3">
<Skeleton className="h-5 w-32" />
</CardHeader>
<CardContent>
<div className="space-y-3">
{[1, 2, 3, 4].map((i) => (
<div key={i} className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4" />
<Skeleton className="h-4 w-20" />
</div>
<Skeleton className="h-4 w-8" />
</div>
))}
<Skeleton className="h-px w-full" />
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4" />
<Skeleton className="h-4 w-20" />
</div>
<Skeleton className="h-4 w-8" />
</div>
<div className="pt-2">
<Skeleton className="h-9 w-full" />
</div>
</div>
</CardContent>
</Card>
);
}
// ============================================================================
// Main Component
// ============================================================================
export function IssueSummary({
summary,
isLoading = false,
onViewAllIssues,
className,
}: IssueSummaryProps) {
if (isLoading) {
return <IssueSummarySkeleton />;
}
if (!summary) {
return (
<Card className={className} data-testid="issue-summary">
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-lg">
<GitBranch className="h-5 w-5" aria-hidden="true" />
Issue Summary
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col items-center justify-center py-4 text-center text-muted-foreground">
<CircleDot className="mb-2 h-6 w-6" aria-hidden="true" />
<p className="text-sm">No issues found</p>
</div>
</CardContent>
</Card>
);
}
return (
<Card className={className} data-testid="issue-summary">
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-lg">
<GitBranch className="h-5 w-5" aria-hidden="true" />
Issue Summary
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3" role="list" aria-label="Issue counts by status">
<StatusRow
icon={CircleDot}
iconColor="text-blue-500"
label="Open"
count={summary.open}
/>
<StatusRow
icon={PlayCircle}
iconColor="text-yellow-500"
label="In Progress"
count={summary.in_progress}
/>
<StatusRow
icon={Clock}
iconColor="text-purple-500"
label="In Review"
count={summary.in_review}
/>
<StatusRow
icon={AlertCircle}
iconColor="text-red-500"
label="Blocked"
count={summary.blocked}
/>
<Separator />
<StatusRow
icon={CheckCircle2}
iconColor="text-green-500"
label="Completed"
count={summary.done}
/>
{onViewAllIssues && (
<div className="pt-2">
<Button
variant="outline"
className="w-full"
size="sm"
onClick={onViewAllIssues}
>
View All Issues ({summary.total})
</Button>
</div>
)}
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,75 @@
/**
* Progress Bar Component
*
* Simple progress bar with customizable appearance.
*/
'use client';
import { cn } from '@/lib/utils';
interface ProgressBarProps {
/** Progress value (0-100) */
value: number;
/** Color variant */
variant?: 'default' | 'success' | 'warning' | 'error';
/** Height size */
size?: 'sm' | 'md' | 'lg';
/** Show percentage label */
showLabel?: boolean;
/** Additional CSS classes for the container */
className?: string;
/** Aria label for accessibility */
'aria-label'?: string;
}
const variantClasses = {
default: 'bg-primary',
success: 'bg-green-500',
warning: 'bg-yellow-500',
error: 'bg-red-500',
};
const sizeClasses = {
sm: 'h-1',
md: 'h-2',
lg: 'h-3',
};
export function ProgressBar({
value,
variant = 'default',
size = 'md',
showLabel = false,
className,
'aria-label': ariaLabel,
}: ProgressBarProps) {
const clampedValue = Math.min(100, Math.max(0, value));
return (
<div className={cn('w-full', className)}>
{showLabel && (
<div className="mb-1 flex justify-between text-sm">
<span className="text-muted-foreground">Progress</span>
<span className="font-medium">{Math.round(clampedValue)}%</span>
</div>
)}
<div
className={cn('w-full rounded-full bg-muted', sizeClasses[size])}
role="progressbar"
aria-valuenow={clampedValue}
aria-valuemin={0}
aria-valuemax={100}
aria-label={ariaLabel || `Progress: ${Math.round(clampedValue)}%`}
>
<div
className={cn(
'h-full rounded-full transition-all duration-300 ease-in-out',
variantClasses[variant]
)}
style={{ width: `${clampedValue}%` }}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,451 @@
/**
* Project Dashboard Component
*
* Main dashboard view for a project showing agents, sprints, issues, and activity.
* Integrates real-time updates via SSE.
*
* @see Issue #40
*/
'use client';
import { useCallback, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { AlertCircle, RefreshCw } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { ConnectionStatus } from '@/components/events/ConnectionStatus';
import { useProjectEvents } from '@/lib/hooks/useProjectEvents';
import { EventType, type ProjectEvent } from '@/lib/types/events';
import { ProjectHeader } from './ProjectHeader';
import { AgentPanel } from './AgentPanel';
import { SprintProgress } from './SprintProgress';
import { IssueSummary } from './IssueSummary';
import { RecentActivity } from './RecentActivity';
import type {
Project,
AgentInstance,
Sprint,
BurndownDataPoint,
IssueSummary as IssueSummaryType,
ActivityItem,
} from './types';
// ============================================================================
// Types
// ============================================================================
interface ProjectDashboardProps {
/** Project ID */
projectId: string;
/** Additional CSS classes */
className?: string;
}
// ============================================================================
// Mock Data (to be replaced with API calls)
// ============================================================================
// Mock data for development - will be replaced with TanStack Query hooks
const mockProject: Project = {
id: 'proj-001',
name: 'E-Commerce Platform Redesign',
description: 'Complete redesign of the e-commerce platform with modern UI/UX',
status: 'in_progress',
autonomy_level: 'milestone',
current_sprint_id: 'sprint-003',
created_at: '2025-01-15T00:00:00Z',
owner_id: 'user-001',
};
const mockAgents: AgentInstance[] = [
{
id: 'agent-001',
agent_type_id: 'type-po',
project_id: 'proj-001',
name: 'Product Owner',
role: 'product_owner',
status: 'active',
current_task: 'Reviewing user story acceptance criteria',
last_activity_at: new Date(Date.now() - 2 * 60 * 1000).toISOString(),
spawned_at: '2025-01-15T00:00:00Z',
avatar: 'PO',
},
{
id: 'agent-002',
agent_type_id: 'type-arch',
project_id: 'proj-001',
name: 'Architect',
role: 'architect',
status: 'working',
current_task: 'Designing API contract for checkout flow',
last_activity_at: new Date(Date.now() - 5 * 60 * 1000).toISOString(),
spawned_at: '2025-01-15T00:00:00Z',
avatar: 'AR',
},
{
id: 'agent-003',
agent_type_id: 'type-be',
project_id: 'proj-001',
name: 'Backend Engineer',
role: 'backend_engineer',
status: 'idle',
current_task: 'Waiting for architecture review',
last_activity_at: new Date(Date.now() - 15 * 60 * 1000).toISOString(),
spawned_at: '2025-01-15T00:00:00Z',
avatar: 'BE',
},
{
id: 'agent-004',
agent_type_id: 'type-fe',
project_id: 'proj-001',
name: 'Frontend Engineer',
role: 'frontend_engineer',
status: 'active',
current_task: 'Implementing product catalog component',
last_activity_at: new Date(Date.now() - 1 * 60 * 1000).toISOString(),
spawned_at: '2025-01-15T00:00:00Z',
avatar: 'FE',
},
{
id: 'agent-005',
agent_type_id: 'type-qa',
project_id: 'proj-001',
name: 'QA Engineer',
role: 'qa_engineer',
status: 'pending',
current_task: 'Preparing test cases for Sprint 3',
last_activity_at: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
spawned_at: '2025-01-15T00:00:00Z',
avatar: 'QA',
},
];
const mockSprint: Sprint = {
id: 'sprint-003',
project_id: 'proj-001',
name: 'Sprint 3',
goal: 'Complete checkout flow',
status: 'active',
start_date: '2025-01-27',
end_date: '2025-02-10',
total_issues: 15,
completed_issues: 8,
in_progress_issues: 4,
blocked_issues: 1,
todo_issues: 2,
};
const mockBurndownData: BurndownDataPoint[] = [
{ day: 1, remaining: 45, ideal: 45 },
{ day: 2, remaining: 42, ideal: 42 },
{ day: 3, remaining: 38, ideal: 39 },
{ day: 4, remaining: 35, ideal: 36 },
{ day: 5, remaining: 30, ideal: 33 },
{ day: 6, remaining: 28, ideal: 30 },
{ day: 7, remaining: 25, ideal: 27 },
{ day: 8, remaining: 20, ideal: 24 },
];
const mockIssueSummary: IssueSummaryType = {
open: 12,
in_progress: 8,
in_review: 3,
blocked: 2,
done: 45,
total: 70,
};
const mockActivity: ActivityItem[] = [
{
id: 'act-001',
type: 'agent_message',
agent: 'Product Owner',
message: 'Approved user story #42: Cart checkout flow',
timestamp: new Date(Date.now() - 2 * 60 * 1000).toISOString(),
},
{
id: 'act-002',
type: 'issue_update',
agent: 'Backend Engineer',
message: 'Moved issue #38 to "In Review"',
timestamp: new Date(Date.now() - 8 * 60 * 1000).toISOString(),
},
{
id: 'act-003',
type: 'agent_status',
agent: 'Frontend Engineer',
message: 'Started working on issue #45',
timestamp: new Date(Date.now() - 15 * 60 * 1000).toISOString(),
},
{
id: 'act-004',
type: 'approval_request',
agent: 'Architect',
message: 'Requesting approval for API design document',
timestamp: new Date(Date.now() - 25 * 60 * 1000).toISOString(),
requires_action: true,
},
{
id: 'act-005',
type: 'sprint_event',
agent: 'System',
message: 'Sprint 3 daily standup completed',
timestamp: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
},
];
// ============================================================================
// Helper Functions
// ============================================================================
/**
* Convert SSE events to activity items
*/
function eventToActivity(event: ProjectEvent): ActivityItem {
const getAgentName = (event: ProjectEvent): string | undefined => {
if (event.actor_type === 'agent') {
const payload = event.payload as Record<string, unknown>;
return (payload.agent_name as string) || 'Agent';
}
if (event.actor_type === 'system') {
return 'System';
}
return undefined;
};
const getMessage = (event: ProjectEvent): string => {
const payload = event.payload as Record<string, unknown>;
switch (event.type) {
case EventType.AGENT_SPAWNED:
return `spawned as ${payload.role || 'agent'}`;
case EventType.AGENT_MESSAGE:
return String(payload.message || 'sent a message');
case EventType.AGENT_STATUS_CHANGED:
return `status changed to ${payload.new_status}`;
case EventType.ISSUE_CREATED:
return `created issue: ${payload.title}`;
case EventType.ISSUE_UPDATED:
return `updated issue #${payload.issue_id}`;
case EventType.APPROVAL_REQUESTED:
return String(payload.description || 'requested approval');
case EventType.SPRINT_STARTED:
return `started sprint: ${payload.sprint_name}`;
default:
return event.type.replace(/_/g, ' ');
}
};
const getType = (event: ProjectEvent): ActivityItem['type'] => {
if (event.type.startsWith('agent.message')) return 'agent_message';
if (event.type.startsWith('agent.')) return 'agent_status';
if (event.type.startsWith('issue.')) return 'issue_update';
if (event.type.startsWith('approval.')) return 'approval_request';
if (event.type.startsWith('sprint.')) return 'sprint_event';
return 'system';
};
return {
id: event.id,
type: getType(event),
agent: getAgentName(event),
message: getMessage(event),
timestamp: event.timestamp,
requires_action: event.type === EventType.APPROVAL_REQUESTED,
};
}
// ============================================================================
// Main Component
// ============================================================================
export function ProjectDashboard({ projectId, className }: ProjectDashboardProps) {
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// SSE connection for real-time updates
const {
events: sseEvents,
connectionState,
error: sseError,
retryCount,
reconnect,
} = useProjectEvents(projectId, {
autoConnect: true,
onEvent: (event) => {
// Handle specific event types for state updates
console.log('[Dashboard] Received event:', event.type);
},
});
// Convert SSE events to activity items
const sseActivities = useMemo(() => {
return sseEvents.slice(-10).map(eventToActivity);
}, [sseEvents]);
// Merge mock activities with SSE activities (SSE takes priority)
const allActivities = useMemo(() => {
const merged = [...sseActivities, ...mockActivity];
// Sort by timestamp, newest first
merged.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
return merged.slice(0, 10);
}, [sseActivities]);
// Use mock data for now (will be replaced with TanStack Query)
const project = mockProject;
const agents = mockAgents;
const sprint = mockSprint;
const burndownData = mockBurndownData;
const issueSummary = mockIssueSummary;
// Event handlers
const handleStartSprint = useCallback(() => {
console.log('Start sprint clicked');
// TODO: Implement start sprint action
}, []);
const handlePauseProject = useCallback(() => {
console.log('Pause project clicked');
// TODO: Implement pause project action
}, []);
const handleCreateSprint = useCallback(() => {
console.log('Create sprint clicked');
// TODO: Navigate to create sprint page
}, []);
const handleSettings = useCallback(() => {
router.push(`/projects/${projectId}/settings`);
}, [router, projectId]);
const handleManageAgents = useCallback(() => {
router.push(`/projects/${projectId}/agents`);
}, [router, projectId]);
const handleAgentAction = useCallback(
(agentId: string, action: 'view' | 'pause' | 'restart' | 'terminate') => {
console.log(`Agent action: ${action} on ${agentId}`);
// TODO: Implement agent actions
},
[]
);
const handleViewAllIssues = useCallback(() => {
router.push(`/projects/${projectId}/issues`);
}, [router, projectId]);
const handleViewAllActivity = useCallback(() => {
router.push(`/projects/${projectId}/activity`);
}, [router, projectId]);
const handleActionClick = useCallback((activityId: string) => {
console.log(`Action clicked for activity: ${activityId}`);
// TODO: Navigate to approval page
}, []);
// Error state
if (error) {
return (
<div className={cn('container mx-auto px-4 py-6', className)}>
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Error loading project</AlertTitle>
<AlertDescription className="flex items-center gap-2">
{error}
<Button
variant="outline"
size="sm"
onClick={() => {
setError(null);
setIsLoading(true);
// TODO: Refetch data
}}
>
<RefreshCw className="mr-2 h-4 w-4" />
Retry
</Button>
</AlertDescription>
</Alert>
</div>
);
}
return (
<div className={cn('min-h-screen bg-background', className)} data-testid="project-dashboard">
<div className="container mx-auto px-4 py-6">
<div className="space-y-6">
{/* SSE Connection Status - only show if not connected */}
{connectionState !== 'connected' && (
<ConnectionStatus
state={connectionState}
error={sseError}
retryCount={retryCount}
onReconnect={reconnect}
compact
className="mb-4"
/>
)}
{/* Header Section */}
<ProjectHeader
project={project}
isLoading={isLoading}
canPause={project.status === 'in_progress'}
canStart={true}
onStartSprint={handleStartSprint}
onPauseProject={handlePauseProject}
onCreateSprint={handleCreateSprint}
onSettings={handleSettings}
/>
{/* Main Content Grid */}
<div className="grid gap-6 lg:grid-cols-3">
{/* Left Column - Agent Panel & Sprint Overview */}
<div className="space-y-6 lg:col-span-2">
{/* Agent Panel */}
<AgentPanel
agents={agents}
isLoading={isLoading}
onManageAgents={handleManageAgents}
onAgentAction={handleAgentAction}
/>
{/* Sprint Overview */}
<SprintProgress
sprint={sprint}
burndownData={burndownData}
availableSprints={[
{ id: 'sprint-003', name: 'Sprint 3' },
{ id: 'sprint-002', name: 'Sprint 2' },
{ id: 'sprint-001', name: 'Sprint 1' },
]}
selectedSprintId={sprint.id}
isLoading={isLoading}
/>
</div>
{/* Right Column - Activity & Issue Summary */}
<div className="space-y-6">
{/* Issue Summary */}
<IssueSummary
summary={issueSummary}
isLoading={isLoading}
onViewAllIssues={handleViewAllIssues}
/>
{/* Recent Activity */}
<RecentActivity
activities={allActivities}
isLoading={isLoading}
onViewAll={handleViewAllActivity}
onActionClick={handleActionClick}
/>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,146 @@
/**
* Project Header Component
*
* Header section for the project dashboard with title, status, and quick actions.
*/
'use client';
import { PlayCircle, PauseCircle, Plus, Settings } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { ProjectStatusBadge, AutonomyBadge } from './StatusBadge';
import type { Project } from './types';
// ============================================================================
// Types
// ============================================================================
interface ProjectHeaderProps {
/** Project data */
project: Project | null;
/** Whether data is loading */
isLoading?: boolean;
/** Whether the project can be paused */
canPause?: boolean;
/** Whether the project can be started */
canStart?: boolean;
/** Callback when "Start/Run Sprint" is clicked */
onStartSprint?: () => void;
/** Callback when "Pause" is clicked */
onPauseProject?: () => void;
/** Callback when "Create Sprint" is clicked */
onCreateSprint?: () => void;
/** Callback when "Settings" is clicked */
onSettings?: () => void;
/** Additional CSS classes */
className?: string;
}
// ============================================================================
// Subcomponents
// ============================================================================
function ProjectHeaderSkeleton() {
return (
<div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-3">
<Skeleton className="h-9 w-64" />
<Skeleton className="h-6 w-24" />
<Skeleton className="h-6 w-28" />
</div>
<Skeleton className="h-5 w-96" />
</div>
<div className="flex gap-2">
<Skeleton className="h-9 w-32" />
<Skeleton className="h-9 w-28" />
</div>
</div>
);
}
// ============================================================================
// Main Component
// ============================================================================
export function ProjectHeader({
project,
isLoading = false,
canPause = false,
canStart = true,
onStartSprint,
onPauseProject,
onCreateSprint,
onSettings,
className,
}: ProjectHeaderProps) {
if (isLoading) {
return <ProjectHeaderSkeleton />;
}
if (!project) {
return null;
}
const showPauseButton = canPause && project.status === 'in_progress';
const showStartButton = canStart && project.status !== 'completed' && project.status !== 'archived';
return (
<div
className={cn(
'flex flex-col gap-4 md:flex-row md:items-start md:justify-between',
className
)}
data-testid="project-header"
>
{/* Project Info */}
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-3">
<h1 className="text-3xl font-bold">{project.name}</h1>
<ProjectStatusBadge status={project.status} />
<AutonomyBadge level={project.autonomy_level} />
</div>
{project.description && (
<p className="text-muted-foreground">{project.description}</p>
)}
</div>
{/* Quick Actions */}
<div className="flex flex-wrap gap-2">
{onSettings && (
<Button
variant="ghost"
size="icon"
onClick={onSettings}
aria-label="Project settings"
>
<Settings className="h-4 w-4" />
</Button>
)}
{showPauseButton && onPauseProject && (
<Button variant="outline" size="sm" onClick={onPauseProject}>
<PauseCircle className="mr-2 h-4 w-4" aria-hidden="true" />
Pause Project
</Button>
)}
{onCreateSprint && (
<Button variant="outline" size="sm" onClick={onCreateSprint}>
<Plus className="mr-2 h-4 w-4" aria-hidden="true" />
New Sprint
</Button>
)}
{showStartButton && onStartSprint && (
<Button size="sm" onClick={onStartSprint}>
<PlayCircle className="mr-2 h-4 w-4" aria-hidden="true" />
Run Sprint
</Button>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,207 @@
/**
* Recent Activity Component
*
* Displays recent project activity feed with action items.
*/
'use client';
import { formatDistanceToNow } from 'date-fns';
import {
Activity,
MessageSquare,
GitPullRequest,
PlayCircle,
AlertCircle,
Users,
Cog,
type LucideIcon,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import type { ActivityItem } from './types';
// ============================================================================
// Types
// ============================================================================
interface RecentActivityProps {
/** Activity items to display */
activities: ActivityItem[];
/** Whether data is loading */
isLoading?: boolean;
/** Maximum items to show */
maxItems?: number;
/** Callback when "View All" is clicked */
onViewAll?: () => void;
/** Callback when an action item is clicked */
onActionClick?: (activityId: string) => void;
/** Additional CSS classes */
className?: string;
}
// ============================================================================
// Helper Functions
// ============================================================================
function getActivityIcon(type: ActivityItem['type']): LucideIcon {
switch (type) {
case 'agent_message':
return MessageSquare;
case 'issue_update':
return GitPullRequest;
case 'agent_status':
return PlayCircle;
case 'approval_request':
return AlertCircle;
case 'sprint_event':
return Users;
case 'system':
default:
return Cog;
}
}
function formatTimestamp(timestamp: string): string {
try {
return formatDistanceToNow(new Date(timestamp), { addSuffix: true });
} catch {
return 'Unknown time';
}
}
// ============================================================================
// Subcomponents
// ============================================================================
interface ActivityItemRowProps {
activity: ActivityItem;
onActionClick?: (activityId: string) => void;
}
function ActivityItemRow({ activity, onActionClick }: ActivityItemRowProps) {
const Icon = getActivityIcon(activity.type);
const timestamp = formatTimestamp(activity.timestamp);
return (
<div className="flex gap-3" data-testid={`activity-item-${activity.id}`}>
<div
className={cn(
'flex h-8 w-8 shrink-0 items-center justify-center rounded-full',
activity.requires_action
? 'bg-yellow-100 text-yellow-600 dark:bg-yellow-900 dark:text-yellow-400'
: 'bg-muted text-muted-foreground'
)}
>
<Icon className="h-4 w-4" aria-hidden="true" />
</div>
<div className="min-w-0 flex-1">
<p className="text-sm">
{activity.agent && (
<span className="font-medium">{activity.agent}</span>
)}{' '}
<span className="text-muted-foreground">{activity.message}</span>
</p>
<p className="text-xs text-muted-foreground">{timestamp}</p>
{activity.requires_action && onActionClick && (
<Button
variant="outline"
size="sm"
className="mt-2 h-7 text-xs"
onClick={() => onActionClick(activity.id)}
>
Review Request
</Button>
)}
</div>
</div>
);
}
function RecentActivitySkeleton({ count = 5 }: { count?: number }) {
return (
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-8 w-16" />
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
{Array.from({ length: count }).map((_, i) => (
<div key={i} className="flex gap-3">
<Skeleton className="h-8 w-8 shrink-0 rounded-full" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-3 w-20" />
</div>
</div>
))}
</div>
</CardContent>
</Card>
);
}
// ============================================================================
// Main Component
// ============================================================================
export function RecentActivity({
activities,
isLoading = false,
maxItems = 5,
onViewAll,
onActionClick,
className,
}: RecentActivityProps) {
if (isLoading) {
return <RecentActivitySkeleton count={maxItems} />;
}
const displayedActivities = activities.slice(0, maxItems);
return (
<Card className={className} data-testid="recent-activity">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="flex items-center gap-2 text-lg">
<Activity className="h-5 w-5" aria-hidden="true" />
Recent Activity
</CardTitle>
{onViewAll && activities.length > maxItems && (
<Button variant="ghost" size="sm" className="text-xs" onClick={onViewAll}>
View All
</Button>
)}
</div>
</CardHeader>
<CardContent>
{displayedActivities.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-center text-muted-foreground">
<Activity className="mb-2 h-8 w-8" aria-hidden="true" />
<p className="text-sm">No recent activity</p>
</div>
) : (
<div className="space-y-4" role="list" aria-label="Recent project activity">
{displayedActivities.map((activity) => (
<ActivityItemRow
key={activity.id}
activity={activity}
onActionClick={onActionClick}
/>
))}
</div>
)}
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,255 @@
/**
* Sprint Progress Component
*
* Displays sprint overview with progress bar, issue stats, and burndown chart.
*/
'use client';
import { TrendingUp, Calendar } from 'lucide-react';
import { format } from 'date-fns';
import { cn } from '@/lib/utils';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { ProgressBar } from './ProgressBar';
import { BurndownChart } from './BurndownChart';
import type { Sprint, BurndownDataPoint } from './types';
// ============================================================================
// Types
// ============================================================================
interface SprintProgressProps {
/** Current sprint data */
sprint: Sprint | null;
/** Burndown chart data */
burndownData?: BurndownDataPoint[];
/** List of available sprints for selector */
availableSprints?: { id: string; name: string }[];
/** Currently selected sprint ID */
selectedSprintId?: string;
/** Callback when sprint selection changes */
onSprintChange?: (sprintId: string) => void;
/** Whether data is loading */
isLoading?: boolean;
/** Additional CSS classes */
className?: string;
}
// ============================================================================
// Helper Functions
// ============================================================================
function formatSprintDates(startDate?: string, endDate?: string): string {
if (!startDate || !endDate) return 'Dates not set';
try {
const start = format(new Date(startDate), 'MMM d');
const end = format(new Date(endDate), 'MMM d, yyyy');
return `${start} - ${end}`;
} catch {
return 'Invalid dates';
}
}
function calculateProgress(sprint: Sprint): number {
if (sprint.total_issues === 0) return 0;
return Math.round((sprint.completed_issues / sprint.total_issues) * 100);
}
// ============================================================================
// Subcomponents
// ============================================================================
interface StatCardProps {
value: number;
label: string;
colorClass: string;
}
function StatCard({ value, label, colorClass }: StatCardProps) {
return (
<div className="rounded-lg border p-3 text-center">
<div className={cn('text-2xl font-bold', colorClass)}>{value}</div>
<div className="text-xs text-muted-foreground">{label}</div>
</div>
);
}
function SprintProgressSkeleton() {
return (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div className="space-y-2">
<Skeleton className="h-5 w-40" />
<Skeleton className="h-4 w-56" />
</div>
<Skeleton className="h-9 w-32" />
</div>
</CardHeader>
<CardContent>
<div className="space-y-6">
{/* Progress bar skeleton */}
<div className="space-y-2">
<div className="flex justify-between">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-12" />
</div>
<Skeleton className="h-2 w-full rounded-full" />
</div>
{/* Stats grid skeleton */}
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
{[1, 2, 3, 4].map((i) => (
<div key={i} className="rounded-lg border p-3 text-center">
<Skeleton className="mx-auto h-8 w-8" />
<Skeleton className="mx-auto mt-1 h-3 w-16" />
</div>
))}
</div>
{/* Burndown skeleton */}
<div className="space-y-2">
<Skeleton className="h-4 w-28" />
<Skeleton className="h-32 w-full" />
</div>
</div>
</CardContent>
</Card>
);
}
// ============================================================================
// Main Component
// ============================================================================
export function SprintProgress({
sprint,
burndownData = [],
availableSprints = [],
selectedSprintId,
onSprintChange,
isLoading = false,
className,
}: SprintProgressProps) {
if (isLoading) {
return <SprintProgressSkeleton />;
}
if (!sprint) {
return (
<Card className={className} data-testid="sprint-progress">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<TrendingUp className="h-5 w-5" aria-hidden="true" />
Sprint Overview
</CardTitle>
<CardDescription>No active sprint</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-col items-center justify-center py-8 text-center text-muted-foreground">
<Calendar className="mb-2 h-8 w-8" aria-hidden="true" />
<p className="text-sm">No sprint is currently active</p>
<p className="mt-1 text-xs">Create a sprint to track progress</p>
</div>
</CardContent>
</Card>
);
}
const progress = calculateProgress(sprint);
const dateRange = formatSprintDates(sprint.start_date, sprint.end_date);
return (
<Card className={className} data-testid="sprint-progress">
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle className="flex items-center gap-2">
<TrendingUp className="h-5 w-5" aria-hidden="true" />
Sprint Overview
</CardTitle>
<CardDescription>
{sprint.name} ({dateRange})
</CardDescription>
</div>
{availableSprints.length > 1 && onSprintChange && (
<Select
value={selectedSprintId || sprint.id}
onValueChange={onSprintChange}
>
<SelectTrigger className="w-32" aria-label="Select sprint">
<SelectValue />
</SelectTrigger>
<SelectContent>
{availableSprints.map((s) => (
<SelectItem key={s.id} value={s.id}>
{s.name}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
</CardHeader>
<CardContent>
<div className="space-y-6">
{/* Sprint Progress */}
<ProgressBar
value={progress}
showLabel
aria-label={`Sprint progress: ${progress}% complete`}
/>
{/* Issue Stats Grid */}
<div
className="grid grid-cols-2 gap-4 sm:grid-cols-4"
role="list"
aria-label="Sprint issue statistics"
>
<StatCard
value={sprint.completed_issues}
label="Completed"
colorClass="text-green-600"
/>
<StatCard
value={sprint.in_progress_issues}
label="In Progress"
colorClass="text-blue-600"
/>
<StatCard
value={sprint.blocked_issues}
label="Blocked"
colorClass="text-red-600"
/>
<StatCard
value={sprint.todo_issues}
label="To Do"
colorClass="text-gray-600"
/>
</div>
{/* Burndown Chart */}
<div>
<h4 className="mb-2 text-sm font-medium">Burndown Chart</h4>
<BurndownChart data={burndownData} height={120} />
</div>
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,97 @@
/**
* Status Badge Components
*
* Reusable badge components for displaying project and autonomy status.
*/
'use client';
import { CircleDot } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import type { ProjectStatus, AutonomyLevel } from './types';
// ============================================================================
// Project Status Badge
// ============================================================================
const projectStatusConfig: Record<ProjectStatus, { label: string; className: string }> = {
draft: {
label: 'Draft',
className: 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200',
},
in_progress: {
label: 'In Progress',
className: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
},
paused: {
label: 'Paused',
className: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
},
completed: {
label: 'Completed',
className: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
},
blocked: {
label: 'Blocked',
className: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200',
},
archived: {
label: 'Archived',
className: 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400',
},
};
interface ProjectStatusBadgeProps {
status: ProjectStatus;
className?: string;
}
export function ProjectStatusBadge({ status, className }: ProjectStatusBadgeProps) {
const config = projectStatusConfig[status] || projectStatusConfig.draft;
return (
<Badge variant="outline" className={cn(config.className, className)}>
{config.label}
</Badge>
);
}
// ============================================================================
// Autonomy Level Badge
// ============================================================================
const autonomyLevelConfig: Record<AutonomyLevel, { label: string; description: string }> = {
full_control: {
label: 'Full Control',
description: 'Approve every action',
},
milestone: {
label: 'Milestone',
description: 'Approve at sprint boundaries',
},
autonomous: {
label: 'Autonomous',
description: 'Only major decisions',
},
};
interface AutonomyBadgeProps {
level: AutonomyLevel;
showDescription?: boolean;
className?: string;
}
export function AutonomyBadge({ level, showDescription = false, className }: AutonomyBadgeProps) {
const config = autonomyLevelConfig[level] || autonomyLevelConfig.milestone;
return (
<Badge variant="secondary" className={cn('gap-1', className)} title={config.description}>
<CircleDot className="h-3 w-3" aria-hidden="true" />
{config.label}
{showDescription && (
<span className="text-muted-foreground"> - {config.description}</span>
)}
</Badge>
);
}

View File

@@ -0,0 +1,19 @@
/**
* Project Components
*
* Export all project-related components for use throughout the application.
*
* @module components/projects
*/
// Wizard Components
export { ProjectWizard, StepIndicator, SelectableCard } from './wizard';
// Re-export wizard types
export type {
WizardState,
WizardStep,
ProjectComplexity,
ClientMode,
AutonomyLevel,
} from './wizard';

View File

@@ -0,0 +1,120 @@
/**
* Project Dashboard Types
*
* Type definitions for project-related components.
* These types will be updated when the API endpoints are implemented.
*
* @module components/projects/types
*/
// ============================================================================
// Project Types
// ============================================================================
export type ProjectStatus = 'draft' | 'in_progress' | 'paused' | 'completed' | 'blocked' | 'archived';
export type AutonomyLevel = 'full_control' | 'milestone' | 'autonomous';
export interface Project {
id: string;
name: string;
description?: string;
status: ProjectStatus;
autonomy_level: AutonomyLevel;
current_sprint_id?: string;
created_at: string;
updated_at?: string;
owner_id: string;
}
// ============================================================================
// Agent Types
// ============================================================================
export type AgentStatus = 'idle' | 'active' | 'working' | 'pending' | 'error' | 'terminated';
export interface AgentInstance {
id: string;
agent_type_id: string;
project_id: string;
name: string;
role: string;
status: AgentStatus;
current_task?: string;
last_activity_at?: string;
spawned_at: string;
avatar?: string;
}
// ============================================================================
// Sprint Types
// ============================================================================
export type SprintStatus = 'planning' | 'active' | 'review' | 'completed';
export interface Sprint {
id: string;
project_id: string;
name: string;
goal?: string;
status: SprintStatus;
start_date?: string;
end_date?: string;
total_issues: number;
completed_issues: number;
in_progress_issues: number;
blocked_issues: number;
todo_issues: number;
}
export interface BurndownDataPoint {
day: number;
date?: string;
remaining: number;
ideal: number;
}
// ============================================================================
// Issue Types
// ============================================================================
export type IssueStatus = 'open' | 'in_progress' | 'in_review' | 'blocked' | 'done' | 'closed';
export type IssuePriority = 'low' | 'medium' | 'high' | 'critical';
export interface Issue {
id: string;
project_id: string;
sprint_id?: string;
title: string;
description?: string;
status: IssueStatus;
priority: IssuePriority;
assignee_id?: string;
created_at: string;
updated_at?: string;
labels?: string[];
}
export interface IssueSummary {
open: number;
in_progress: number;
in_review: number;
blocked: number;
done: number;
total: number;
}
// ============================================================================
// Activity Types
// ============================================================================
export interface ActivityItem {
id: string;
type: 'agent_message' | 'issue_update' | 'agent_status' | 'approval_request' | 'sprint_event' | 'system';
agent?: string;
message: string;
timestamp: string;
requires_action?: boolean;
metadata?: Record<string, unknown>;
}

View File

@@ -0,0 +1,227 @@
'use client';
/**
* Project Creation Wizard
*
* Multi-step wizard for creating new Syndarix projects.
* Adapts based on project complexity - scripts use a simplified 4-step flow.
*/
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, ArrowRight, Check, CheckCircle2, Loader2 } from 'lucide-react';
import { useMutation } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { apiClient } from '@/lib/api/client';
import { StepIndicator } from './StepIndicator';
import { useWizardState, type ProjectCreateData } from './useWizardState';
import { WIZARD_STEPS } from './constants';
import {
BasicInfoStep,
ComplexityStep,
ClientModeStep,
AutonomyStep,
AgentChatStep,
ReviewStep,
} from './steps';
/**
* Project response from API
*/
interface ProjectResponse {
id: string;
name: string;
slug: string;
description: string | null;
autonomy_level: string;
status: string;
settings: Record<string, unknown>;
owner_id: string | null;
created_at: string;
updated_at: string;
agent_count: number;
issue_count: number;
active_sprint_name: string | null;
}
interface ProjectWizardProps {
locale: string;
className?: string;
}
export function ProjectWizard({ locale, className }: ProjectWizardProps) {
const router = useRouter();
const [isCreated, setIsCreated] = useState(false);
const {
state,
updateState,
resetState,
isScriptMode,
canProceed,
goNext,
goBack,
getProjectData,
} = useWizardState();
// Project creation mutation using the configured API client
const createProjectMutation = useMutation({
mutationFn: async (projectData: ProjectCreateData): Promise<ProjectResponse> => {
// Call the projects API endpoint
// Note: The API client already handles authentication via interceptors
const response = await apiClient.instance.post<ProjectResponse>(
'/api/v1/projects',
{
name: projectData.name,
slug: projectData.slug,
description: projectData.description,
autonomy_level: projectData.autonomy_level,
settings: projectData.settings,
}
);
return response.data;
},
onSuccess: () => {
setIsCreated(true);
},
onError: (error) => {
// Error handling - in production, show toast notification
console.error('Failed to create project:', error);
},
});
const handleCreate = () => {
const projectData = getProjectData();
createProjectMutation.mutate(projectData);
};
const handleReset = () => {
resetState();
setIsCreated(false);
createProjectMutation.reset();
};
const handleGoToProject = () => {
// Navigate to project dashboard - using slug from successful creation
if (createProjectMutation.data) {
router.push(`/${locale}/projects/${createProjectMutation.data.slug}`);
} else {
router.push(`/${locale}/projects`);
}
};
// Success screen
if (isCreated && createProjectMutation.data) {
return (
<div className={className}>
<div className="mx-auto max-w-2xl">
<Card className="text-center">
<CardContent className="space-y-6 p-8">
<div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-green-100 dark:bg-green-900">
<CheckCircle2 className="h-8 w-8 text-green-600 dark:text-green-400" aria-hidden="true" />
</div>
<div>
<h2 className="text-2xl font-bold">Project Created Successfully!</h2>
<p className="mt-2 text-muted-foreground">
&quot;{createProjectMutation.data.name}&quot; has been created. The Product Owner
agent will begin the requirements discovery process shortly.
</p>
</div>
<div className="flex flex-col justify-center gap-4 sm:flex-row">
<Button onClick={handleGoToProject}>Go to Project Dashboard</Button>
<Button variant="outline" onClick={handleReset}>
Create Another Project
</Button>
</div>
</CardContent>
</Card>
</div>
</div>
);
}
return (
<div className={className}>
<div className="mx-auto max-w-3xl">
{/* Step Indicator */}
<div className="mb-8">
<StepIndicator currentStep={state.step} isScriptMode={isScriptMode} />
</div>
{/* Step Content */}
<Card>
<CardContent className="p-6 md:p-8">
{state.step === WIZARD_STEPS.BASIC_INFO && (
<BasicInfoStep state={state} updateState={updateState} />
)}
{state.step === WIZARD_STEPS.COMPLEXITY && (
<ComplexityStep state={state} updateState={updateState} />
)}
{state.step === WIZARD_STEPS.CLIENT_MODE && !isScriptMode && (
<ClientModeStep state={state} updateState={updateState} />
)}
{state.step === WIZARD_STEPS.AUTONOMY && !isScriptMode && (
<AutonomyStep state={state} updateState={updateState} />
)}
{state.step === WIZARD_STEPS.AGENT_CHAT && <AgentChatStep />}
{state.step === WIZARD_STEPS.REVIEW && <ReviewStep state={state} />}
</CardContent>
{/* Navigation Footer */}
<Separator />
<div className="flex items-center justify-between p-6">
<Button
variant="ghost"
onClick={goBack}
disabled={state.step === WIZARD_STEPS.BASIC_INFO}
className={state.step === WIZARD_STEPS.BASIC_INFO ? 'invisible' : ''}
>
<ArrowLeft className="mr-2 h-4 w-4" aria-hidden="true" />
Back
</Button>
<div className="flex gap-2">
{state.step < WIZARD_STEPS.REVIEW ? (
<Button onClick={goNext} disabled={!canProceed}>
Next
<ArrowRight className="ml-2 h-4 w-4" aria-hidden="true" />
</Button>
) : (
<Button
onClick={handleCreate}
disabled={createProjectMutation.isPending}
>
{createProjectMutation.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />
Creating...
</>
) : (
<>
<Check className="mr-2 h-4 w-4" aria-hidden="true" />
Create Project
</>
)}
</Button>
)}
</div>
</div>
{/* Error display */}
{createProjectMutation.isError && (
<div className="border-t bg-destructive/10 p-4">
<p className="text-sm text-destructive">
Failed to create project. Please try again.
</p>
</div>
)}
</Card>
</div>
</div>
);
}

View File

@@ -0,0 +1,44 @@
'use client';
/**
* Selectable Card Component
*
* A button-based card that can be selected/deselected.
* Used for complexity, client mode, and autonomy selection.
*/
import type { ReactNode } from 'react';
import { cn } from '@/lib/utils';
interface SelectableCardProps {
selected: boolean;
onClick: () => void;
children: ReactNode;
className?: string;
'aria-label'?: string;
}
export function SelectableCard({
selected,
onClick,
children,
className,
'aria-label': ariaLabel,
}: SelectableCardProps) {
return (
<button
type="button"
onClick={onClick}
aria-pressed={selected}
aria-label={ariaLabel}
className={cn(
'w-full rounded-lg border-2 p-4 text-left transition-all',
'hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
selected ? 'border-primary bg-primary/5' : 'border-border',
className
)}
>
{children}
</button>
);
}

View File

@@ -0,0 +1,50 @@
'use client';
/**
* Step Indicator Component
*
* Shows progress through the wizard steps with visual feedback.
* Dynamically adjusts based on whether script mode is active.
*/
import { cn } from '@/lib/utils';
import { getStepLabels, getDisplayStep, getTotalSteps } from './constants';
interface StepIndicatorProps {
currentStep: number;
isScriptMode: boolean;
className?: string;
}
export function StepIndicator({ currentStep, isScriptMode, className }: StepIndicatorProps) {
const steps = getStepLabels(isScriptMode);
const totalSteps = getTotalSteps(isScriptMode);
const displayStep = getDisplayStep(currentStep, isScriptMode);
return (
<div className={cn('w-full', className)}>
<div className="mb-2 flex items-center justify-between text-sm text-muted-foreground">
<span>
Step {displayStep} of {totalSteps}
</span>
<span>{steps[displayStep - 1]}</span>
</div>
<div className="flex gap-1" role="progressbar" aria-valuenow={displayStep} aria-valuemax={totalSteps}>
{Array.from({ length: totalSteps }, (_, i) => (
<div
key={i}
className={cn(
'h-2 flex-1 rounded-full transition-colors',
i + 1 < displayStep
? 'bg-primary'
: i + 1 === displayStep
? 'bg-primary/70'
: 'bg-muted'
)}
aria-hidden="true"
/>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,188 @@
/**
* Constants for the Project Creation Wizard
*/
import {
FileCode,
Folder,
Layers,
Building2,
Zap,
HelpCircle,
Shield,
Milestone,
Bot,
} from 'lucide-react';
import type { ComplexityOption, ClientModeOption, AutonomyOption } from './types';
/**
* Complexity options with descriptions
* Note: Timelines match the exact requirements from Issue #50
*/
export const complexityOptions: ComplexityOption[] = [
{
id: 'script',
label: 'Script',
icon: FileCode,
description: 'Single-file utilities, automation scripts, CLI tools',
scope: 'Minutes to 1-2 hours, single file or small module',
examples: 'Data migration script, API integration helper, Build tool plugin',
skipConfig: true,
},
{
id: 'simple',
label: 'Simple',
icon: Folder,
description: 'Small applications with clear requirements',
scope: '2-3 days, handful of files/components',
examples: 'Landing page, REST API endpoint, Browser extension',
skipConfig: false,
},
{
id: 'medium',
label: 'Medium',
icon: Layers,
description: 'Full applications with multiple features',
scope: '2-3 weeks, multiple modules/services',
examples: 'Admin dashboard, E-commerce store, Mobile app',
skipConfig: false,
},
{
id: 'complex',
label: 'Complex',
icon: Building2,
description: 'Enterprise systems with many moving parts',
scope: '2-3 months, distributed architecture',
examples: 'SaaS platform, Microservices ecosystem, Data pipeline',
skipConfig: false,
},
];
/**
* Client mode options
*/
export const clientModeOptions: ClientModeOption[] = [
{
id: 'technical',
label: 'Technical Mode',
icon: Zap,
description: "I'll provide detailed technical specifications",
details: [
'Upload existing specs or PRDs',
'Define API contracts and schemas',
'Specify architecture patterns',
'Direct sprint planning input',
],
},
{
id: 'auto',
label: 'Auto Mode',
icon: HelpCircle,
description: 'Help me figure out what I need',
details: [
'Guided requirements discovery',
'AI suggests best practices',
'Interactive brainstorming sessions',
'Progressive refinement of scope',
],
},
];
/**
* Autonomy level options with approval matrix
*/
export const autonomyOptions: AutonomyOption[] = [
{
id: 'full_control',
label: 'Full Control',
icon: Shield,
description: 'Review every action before it happens',
approvals: {
codeChanges: true,
issueUpdates: true,
architectureDecisions: true,
sprintPlanning: true,
deployments: true,
},
recommended: 'New users or critical projects',
},
{
id: 'milestone',
label: 'Milestone',
icon: Milestone,
description: 'Review at sprint boundaries',
approvals: {
codeChanges: false,
issueUpdates: false,
architectureDecisions: true,
sprintPlanning: true,
deployments: true,
},
recommended: 'Balanced control (recommended)',
},
{
id: 'autonomous',
label: 'Autonomous',
icon: Bot,
description: 'Only major decisions require approval',
approvals: {
codeChanges: false,
issueUpdates: false,
architectureDecisions: true,
sprintPlanning: false,
deployments: true,
},
recommended: 'Experienced users or low-risk projects',
},
];
/**
* Step configuration for wizard navigation
*/
export const WIZARD_STEPS = {
BASIC_INFO: 1,
COMPLEXITY: 2,
CLIENT_MODE: 3,
AUTONOMY: 4,
AGENT_CHAT: 5,
REVIEW: 6,
} as const;
/**
* Total steps based on complexity mode
*/
export const getTotalSteps = (isScriptMode: boolean): number => {
return isScriptMode ? 4 : 6;
};
/**
* Get step labels based on complexity mode
*/
export const getStepLabels = (isScriptMode: boolean): string[] => {
if (isScriptMode) {
return ['Basic Info', 'Complexity', 'Agent Chat', 'Review'];
}
return ['Basic Info', 'Complexity', 'Client Mode', 'Autonomy', 'Agent Chat', 'Review'];
};
/**
* Map actual step to display step for scripts
*/
export const getDisplayStep = (actualStep: number, isScriptMode: boolean): number => {
if (!isScriptMode) return actualStep;
// For scripts: 1->1, 2->2, 5->3, 6->4
switch (actualStep) {
case 1:
return 1;
case 2:
return 2;
case 5:
return 3;
case 6:
return 4;
default:
return actualStep;
}
};

View File

@@ -0,0 +1,26 @@
/**
* Project Creation Wizard
*
* Multi-step wizard for creating new Syndarix projects.
*/
export { ProjectWizard } from './ProjectWizard';
export { StepIndicator } from './StepIndicator';
export { SelectableCard } from './SelectableCard';
// Re-export types
export type {
WizardState,
WizardStep,
ProjectComplexity,
ClientMode,
AutonomyLevel,
} from './types';
// Re-export constants
export {
complexityOptions,
clientModeOptions,
autonomyOptions,
WIZARD_STEPS,
} from './constants';

View File

@@ -0,0 +1,171 @@
'use client';
/**
* Step 5: Agent Chat Placeholder
*
* Preview of the requirements discovery chat interface.
* This will be fully implemented in Phase 4.
*/
import { Bot, User, MessageSquare, Sparkles } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
interface MockMessage {
id: number;
role: 'agent' | 'user';
name: string;
message: string;
timestamp: string;
}
const mockMessages: MockMessage[] = [
{
id: 1,
role: 'agent',
name: 'Product Owner Agent',
message:
"Hello! I'm your Product Owner agent. I'll help you define what we're building. Can you tell me more about your project goals?",
timestamp: '10:00 AM',
},
{
id: 2,
role: 'user',
name: 'You',
message:
'I want to build an e-commerce platform for selling handmade crafts. It should have user accounts, a product catalog, and checkout.',
timestamp: '10:02 AM',
},
{
id: 3,
role: 'agent',
name: 'Product Owner Agent',
message:
"Great! Let me break this down into user stories. For the MVP, I'd suggest focusing on: user registration/login, product browsing with categories, and a simple cart checkout. Should we also include seller accounts or just a single store?",
timestamp: '10:03 AM',
},
];
export function AgentChatStep() {
return (
<div className="space-y-6">
<div>
<div className="flex items-center gap-2">
<h2 className="text-2xl font-bold">Requirements Discovery</h2>
<Badge variant="secondary">Coming in Phase 4</Badge>
</div>
<p className="mt-1 text-muted-foreground">
In the full version, you&apos;ll chat with our Product Owner agent here to define
requirements.
</p>
</div>
<Card>
<CardHeader className="border-b pb-4">
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
<Bot className="h-5 w-5 text-primary" aria-hidden="true" />
</div>
<div>
<CardTitle className="text-base">Product Owner Agent</CardTitle>
<CardDescription>Requirements discovery and sprint planning</CardDescription>
</div>
<Badge variant="outline" className="ml-auto">
Preview Only
</Badge>
</div>
</CardHeader>
<CardContent className="p-0">
{/* Chat Messages Area */}
<div
className="max-h-80 space-y-4 overflow-y-auto p-4"
role="log"
aria-label="Chat preview messages"
>
{mockMessages.map((msg) => (
<div
key={msg.id}
className={cn('flex gap-3', msg.role === 'user' ? 'flex-row-reverse' : '')}
>
<div
className={cn(
'flex h-8 w-8 shrink-0 items-center justify-center rounded-full',
msg.role === 'agent' ? 'bg-primary/10' : 'bg-muted'
)}
aria-hidden="true"
>
{msg.role === 'agent' ? (
<Bot className="h-4 w-4 text-primary" />
) : (
<User className="h-4 w-4 text-muted-foreground" />
)}
</div>
<div
className={cn(
'max-w-[80%] rounded-lg px-4 py-2',
msg.role === 'agent' ? 'bg-muted' : 'bg-primary text-primary-foreground'
)}
>
<p className="text-sm">{msg.message}</p>
<p
className={cn(
'mt-1 text-xs',
msg.role === 'agent' ? 'text-muted-foreground' : 'text-primary-foreground/70'
)}
>
{msg.timestamp}
</p>
</div>
</div>
))}
</div>
{/* Chat Input Area (disabled preview) */}
<div className="border-t p-4">
<div className="flex gap-2">
<Input
placeholder="Type your message... (disabled in preview)"
disabled
className="flex-1"
aria-label="Chat input (disabled in preview)"
/>
<Button disabled aria-label="Send message (disabled in preview)">
<MessageSquare className="h-4 w-4" aria-hidden="true" />
</Button>
</div>
<p className="mt-2 text-center text-xs text-muted-foreground">
This chat interface is a preview. Full agent interaction will be available in Phase 4.
</p>
</div>
</CardContent>
</Card>
<Card className="border-dashed bg-muted/30">
<CardContent className="flex items-center gap-4 p-6">
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
<Sparkles className="h-6 w-6 text-primary" aria-hidden="true" />
</div>
<div>
<h4 className="font-medium">What to Expect in the Full Version</h4>
<ul className="mt-2 space-y-1 text-sm text-muted-foreground">
<li>- Interactive requirements gathering with AI Product Owner</li>
<li>- Architecture spike with BA and Architect agents</li>
<li>- Collaborative backlog creation and prioritization</li>
<li>- Real-time refinement of user stories</li>
</ul>
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,153 @@
'use client';
/**
* Step 4: Autonomy Level Selection
*
* Allows users to choose how much control they want over agent actions.
* Includes a detailed approval matrix comparison.
* Skipped for script complexity projects.
*/
import { Check, AlertCircle } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { cn } from '@/lib/utils';
import { SelectableCard } from '../SelectableCard';
import { autonomyOptions } from '../constants';
import type { WizardState, AutonomyLevel, ApprovalMatrix } from '../types';
import { approvalLabels } from '../types';
interface AutonomyStepProps {
state: WizardState;
updateState: (updates: Partial<WizardState>) => void;
}
export function AutonomyStep({ state, updateState }: AutonomyStepProps) {
const handleSelect = (autonomyLevel: AutonomyLevel) => {
updateState({ autonomyLevel });
};
return (
<div className="space-y-6">
<div>
<h2 className="text-2xl font-bold">Autonomy Level</h2>
<p className="mt-1 text-muted-foreground">
How much control do you want over the AI agents&apos; actions?
</p>
</div>
<div className="grid gap-4" role="radiogroup" aria-label="Autonomy level options">
{autonomyOptions.map((option) => {
const Icon = option.icon;
const isSelected = state.autonomyLevel === option.id;
return (
<SelectableCard
key={option.id}
selected={isSelected}
onClick={() => handleSelect(option.id)}
aria-label={`${option.label}: ${option.description}`}
>
<div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
<div className="flex items-start gap-4">
<div
className={cn(
'flex h-10 w-10 shrink-0 items-center justify-center rounded-lg',
isSelected ? 'bg-primary text-primary-foreground' : 'bg-muted'
)}
>
<Icon className="h-5 w-5" aria-hidden="true" />
</div>
<div>
<div className="flex items-center gap-2">
<h3 className="font-semibold">{option.label}</h3>
{isSelected && (
<div className="flex h-5 w-5 items-center justify-center rounded-full bg-primary text-primary-foreground">
<Check className="h-3 w-3" aria-hidden="true" />
</div>
)}
</div>
<p className="text-sm text-muted-foreground">{option.description}</p>
<p className="mt-1 text-xs text-muted-foreground">
<span className="font-medium">Best for:</span> {option.recommended}
</p>
</div>
</div>
<div className="flex flex-wrap gap-2 md:justify-end">
{Object.entries(option.approvals).map(([key, requiresApproval]) => (
<Badge
key={key}
variant={requiresApproval ? 'default' : 'secondary'}
className="text-xs"
>
{requiresApproval ? 'Approve' : 'Auto'}:{' '}
{approvalLabels[key as keyof ApprovalMatrix]}
</Badge>
))}
</div>
</div>
</SelectableCard>
);
})}
</div>
<Card className="bg-muted/50">
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<AlertCircle className="h-4 w-4" aria-hidden="true" />
Approval Matrix
</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<table className="w-full text-sm" aria-label="Approval requirements by autonomy level">
<thead>
<tr className="border-b">
<th scope="col" className="pb-2 text-left font-medium">
Action Type
</th>
<th scope="col" className="pb-2 text-center font-medium">
Full Control
</th>
<th scope="col" className="pb-2 text-center font-medium">
Milestone
</th>
<th scope="col" className="pb-2 text-center font-medium">
Autonomous
</th>
</tr>
</thead>
<tbody className="divide-y">
{Object.keys(autonomyOptions[0].approvals).map((key) => (
<tr key={key}>
<td className="py-2 text-muted-foreground">
{approvalLabels[key as keyof ApprovalMatrix]}
</td>
{autonomyOptions.map((option) => (
<td key={option.id} className="py-2 text-center">
{option.approvals[key as keyof ApprovalMatrix] ? (
<Badge variant="outline" className="text-xs">
Required
</Badge>
) : (
<span className="text-xs text-muted-foreground">Automatic</span>
)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,142 @@
'use client';
/**
* Step 1: Basic Information
*
* Collects project name, description, and optional repository URL.
*/
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { GitBranch } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import type { WizardState } from '../types';
const basicInfoSchema = z.object({
projectName: z
.string()
.min(3, 'Project name must be at least 3 characters')
.max(255, 'Project name must be less than 255 characters'),
description: z.string().max(2000, 'Description must be less than 2000 characters').optional(),
repoUrl: z.string().url('Please enter a valid URL').or(z.literal('')).optional(),
});
type BasicInfoFormData = z.infer<typeof basicInfoSchema>;
interface BasicInfoStepProps {
state: WizardState;
updateState: (updates: Partial<WizardState>) => void;
}
export function BasicInfoStep({ state, updateState }: BasicInfoStepProps) {
const {
register,
formState: { errors },
trigger,
} = useForm<BasicInfoFormData>({
resolver: zodResolver(basicInfoSchema),
defaultValues: {
projectName: state.projectName,
description: state.description,
repoUrl: state.repoUrl,
},
mode: 'onBlur',
});
const handleChange = (field: keyof BasicInfoFormData, value: string) => {
updateState({ [field]: value });
};
return (
<div className="space-y-6">
<div>
<h2 className="text-2xl font-bold">Create New Project</h2>
<p className="mt-1 text-muted-foreground">
Let&apos;s start with the basics. Give your project a name and description.
</p>
</div>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="project-name">
Project Name <span className="text-destructive">*</span>
</Label>
<Input
id="project-name"
placeholder="e.g., E-Commerce Platform Redesign"
{...register('projectName')}
value={state.projectName}
onChange={(e) => {
handleChange('projectName', e.target.value);
if (errors.projectName) {
trigger('projectName');
}
}}
onBlur={() => trigger('projectName')}
aria-invalid={!!errors.projectName}
aria-describedby={errors.projectName ? 'project-name-error' : undefined}
/>
{errors.projectName && (
<p id="project-name-error" className="text-sm text-destructive">
{errors.projectName.message}
</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="description">Description (Optional)</Label>
<Textarea
id="description"
placeholder="Briefly describe what this project is about..."
{...register('description')}
value={state.description}
onChange={(e) => handleChange('description', e.target.value)}
rows={3}
aria-describedby="description-hint"
/>
<p id="description-hint" className="text-xs text-muted-foreground">
A clear description helps the AI agents understand your project better.
</p>
</div>
<div className="space-y-2">
<Label htmlFor="repo-url">Repository URL (Optional)</Label>
<div className="flex gap-2">
<div className="flex h-9 w-9 items-center justify-center rounded-md border bg-muted">
<GitBranch className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
</div>
<Input
id="repo-url"
placeholder="https://github.com/your-org/your-repo"
{...register('repoUrl')}
value={state.repoUrl}
onChange={(e) => {
handleChange('repoUrl', e.target.value);
if (errors.repoUrl) {
trigger('repoUrl');
}
}}
onBlur={() => trigger('repoUrl')}
className="flex-1"
aria-invalid={!!errors.repoUrl}
aria-describedby={errors.repoUrl ? 'repo-url-error' : 'repo-url-hint'}
/>
</div>
{errors.repoUrl ? (
<p id="repo-url-error" className="text-sm text-destructive">
{errors.repoUrl.message}
</p>
) : (
<p id="repo-url-hint" className="text-xs text-muted-foreground">
Connect an existing repository or leave blank to create a new one.
</p>
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,95 @@
'use client';
/**
* Step 3: Client Mode Selection
*
* Allows users to choose how they want to interact with Syndarix agents.
* Skipped for script complexity projects.
*/
import { Check, CheckCircle2 } from 'lucide-react';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import { SelectableCard } from '../SelectableCard';
import { clientModeOptions } from '../constants';
import type { WizardState, ClientMode } from '../types';
interface ClientModeStepProps {
state: WizardState;
updateState: (updates: Partial<WizardState>) => void;
}
export function ClientModeStep({ state, updateState }: ClientModeStepProps) {
const handleSelect = (clientMode: ClientMode) => {
updateState({ clientMode });
};
return (
<div className="space-y-6">
<div>
<h2 className="text-2xl font-bold">How Would You Like to Work?</h2>
<p className="mt-1 text-muted-foreground">
Choose how you want to interact with Syndarix agents.
</p>
</div>
<div className="grid gap-6 md:grid-cols-2" role="radiogroup" aria-label="Client interaction mode options">
{clientModeOptions.map((option) => {
const Icon = option.icon;
const isSelected = state.clientMode === option.id;
return (
<SelectableCard
key={option.id}
selected={isSelected}
onClick={() => handleSelect(option.id)}
className="h-full"
aria-label={`${option.label}: ${option.description}`}
>
<div className="flex h-full flex-col space-y-4">
<div className="flex items-start justify-between">
<div
className={cn(
'flex h-12 w-12 items-center justify-center rounded-lg',
isSelected ? 'bg-primary text-primary-foreground' : 'bg-muted'
)}
>
<Icon className="h-6 w-6" aria-hidden="true" />
</div>
{isSelected && (
<div className="flex h-6 w-6 items-center justify-center rounded-full bg-primary text-primary-foreground">
<Check className="h-4 w-4" aria-hidden="true" />
</div>
)}
</div>
<div>
<h3 className="text-lg font-semibold">{option.label}</h3>
<p className="mt-1 text-muted-foreground">{option.description}</p>
</div>
<Separator />
<ul className="flex-1 space-y-2">
{option.details.map((detail) => (
<li key={detail} className="flex items-start gap-2 text-sm">
<CheckCircle2
className={cn(
'mt-0.5 h-4 w-4 shrink-0',
isSelected ? 'text-primary' : 'text-muted-foreground'
)}
aria-hidden="true"
/>
<span className="text-muted-foreground">{detail}</span>
</li>
))}
</ul>
</div>
</SelectableCard>
);
})}
</div>
</div>
);
}

View File

@@ -0,0 +1,90 @@
'use client';
/**
* Step 2: Complexity Assessment
*
* Allows users to select the project complexity level.
* Script complexity triggers simplified flow (skips steps 3-4).
*/
import { Check } from 'lucide-react';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import { SelectableCard } from '../SelectableCard';
import { complexityOptions } from '../constants';
import type { WizardState, ProjectComplexity } from '../types';
interface ComplexityStepProps {
state: WizardState;
updateState: (updates: Partial<WizardState>) => void;
}
export function ComplexityStep({ state, updateState }: ComplexityStepProps) {
const handleSelect = (complexity: ProjectComplexity) => {
updateState({ complexity });
};
return (
<div className="space-y-6">
<div>
<h2 className="text-2xl font-bold">Project Complexity</h2>
<p className="mt-1 text-muted-foreground">
How complex is your project? This helps us assign the right resources.
</p>
{state.complexity === 'script' && (
<p className="mt-2 text-sm text-primary">
Scripts use a simplified flow - you&apos;ll skip to agent chat directly.
</p>
)}
</div>
<div className="grid gap-4 md:grid-cols-2" role="radiogroup" aria-label="Project complexity options">
{complexityOptions.map((option) => {
const Icon = option.icon;
const isSelected = state.complexity === option.id;
return (
<SelectableCard
key={option.id}
selected={isSelected}
onClick={() => handleSelect(option.id)}
aria-label={`${option.label}: ${option.description}`}
>
<div className="space-y-3">
<div className="flex items-start justify-between">
<div
className={cn(
'flex h-10 w-10 items-center justify-center rounded-lg',
isSelected ? 'bg-primary text-primary-foreground' : 'bg-muted'
)}
>
<Icon className="h-5 w-5" aria-hidden="true" />
</div>
{isSelected && (
<div className="flex h-6 w-6 items-center justify-center rounded-full bg-primary text-primary-foreground">
<Check className="h-4 w-4" aria-hidden="true" />
</div>
)}
</div>
<div>
<h3 className="font-semibold">{option.label}</h3>
<p className="mt-1 text-sm text-muted-foreground">{option.description}</p>
</div>
<Separator />
<div className="space-y-1 text-sm">
<p className="text-muted-foreground">
<span className="font-medium text-foreground">Scope:</span> {option.scope}
</p>
<p className="text-muted-foreground">
<span className="font-medium text-foreground">Examples:</span> {option.examples}
</p>
</div>
</div>
</SelectableCard>
);
})}
</div>
</div>
);
}

View File

@@ -0,0 +1,158 @@
'use client';
/**
* Step 6: Review & Confirmation
*
* Shows a summary of all selections before creating the project.
*/
import { CheckCircle2 } from 'lucide-react';
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { complexityOptions, clientModeOptions, autonomyOptions } from '../constants';
import type { WizardState } from '../types';
interface ReviewStepProps {
state: WizardState;
}
export function ReviewStep({ state }: ReviewStepProps) {
const complexity = complexityOptions.find((o) => o.id === state.complexity);
const clientMode = clientModeOptions.find((o) => o.id === state.clientMode);
const autonomy = autonomyOptions.find((o) => o.id === state.autonomyLevel);
const isScriptMode = state.complexity === 'script';
return (
<div className="space-y-6">
<div>
<h2 className="text-2xl font-bold">Review Your Project</h2>
<p className="mt-1 text-muted-foreground">
Please review your selections before creating the project.
</p>
</div>
<div className="grid gap-6 md:grid-cols-2">
{/* Basic Info Card */}
<Card>
<CardHeader>
<CardTitle className="text-base">Basic Information</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div>
<p className="text-sm font-medium">Project Name</p>
<p className="text-sm text-muted-foreground">
{state.projectName || 'Not specified'}
</p>
</div>
<div>
<p className="text-sm font-medium">Description</p>
<p className="text-sm text-muted-foreground">
{state.description || 'No description provided'}
</p>
</div>
<div>
<p className="text-sm font-medium">Repository</p>
<p className="text-sm text-muted-foreground">
{state.repoUrl || 'New repository will be created'}
</p>
</div>
</CardContent>
</Card>
{/* Complexity Card */}
<Card>
<CardHeader>
<CardTitle className="text-base">Project Complexity</CardTitle>
</CardHeader>
<CardContent>
{complexity ? (
<div className="flex items-start gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
<complexity.icon className="h-5 w-5 text-primary" aria-hidden="true" />
</div>
<div>
<p className="font-medium">{complexity.label}</p>
<p className="text-sm text-muted-foreground">{complexity.description}</p>
</div>
</div>
) : (
<p className="text-sm text-muted-foreground">Not selected</p>
)}
</CardContent>
</Card>
{/* Client Mode Card - show for non-scripts or show auto-selected for scripts */}
<Card>
<CardHeader>
<CardTitle className="text-base">Interaction Mode</CardTitle>
</CardHeader>
<CardContent>
{isScriptMode ? (
<p className="text-sm text-muted-foreground">
Auto Mode (automatically set for script projects)
</p>
) : clientMode ? (
<div className="flex items-start gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
<clientMode.icon className="h-5 w-5 text-primary" aria-hidden="true" />
</div>
<div>
<p className="font-medium">{clientMode.label}</p>
<p className="text-sm text-muted-foreground">{clientMode.description}</p>
</div>
</div>
) : (
<p className="text-sm text-muted-foreground">Not selected</p>
)}
</CardContent>
</Card>
{/* Autonomy Card - show for non-scripts or show auto-selected for scripts */}
<Card>
<CardHeader>
<CardTitle className="text-base">Autonomy Level</CardTitle>
</CardHeader>
<CardContent>
{isScriptMode ? (
<p className="text-sm text-muted-foreground">
Autonomous (automatically set for script projects)
</p>
) : autonomy ? (
<div className="flex items-start gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
<autonomy.icon className="h-5 w-5 text-primary" aria-hidden="true" />
</div>
<div>
<p className="font-medium">{autonomy.label}</p>
<p className="text-sm text-muted-foreground">{autonomy.description}</p>
</div>
</div>
) : (
<p className="text-sm text-muted-foreground">Not selected</p>
)}
</CardContent>
</Card>
</div>
{/* Summary Alert */}
<Card className="border-primary/50 bg-primary/5">
<CardContent className="flex items-start gap-4 p-6">
<CheckCircle2 className="mt-0.5 h-5 w-5 shrink-0 text-primary" aria-hidden="true" />
<div>
<h4 className="font-medium">Ready to Create</h4>
<p className="mt-1 text-sm text-muted-foreground">
Once you create this project, Syndarix will set up your environment and begin the
requirements discovery phase with the Product Owner agent.
</p>
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,10 @@
/**
* Export all wizard step components
*/
export { BasicInfoStep } from './BasicInfoStep';
export { ComplexityStep } from './ComplexityStep';
export { ClientModeStep } from './ClientModeStep';
export { AutonomyStep } from './AutonomyStep';
export { AgentChatStep } from './AgentChatStep';
export { ReviewStep } from './ReviewStep';

View File

@@ -0,0 +1,109 @@
/**
* Types and constants for the Project Creation Wizard
*/
import type { LucideIcon } from 'lucide-react';
/**
* Project complexity levels matching backend enum
*/
export type ProjectComplexity = 'script' | 'simple' | 'medium' | 'complex';
/**
* Client interaction mode matching backend enum
*/
export type ClientMode = 'technical' | 'auto';
/**
* Autonomy level matching backend enum
*/
export type AutonomyLevel = 'full_control' | 'milestone' | 'autonomous';
/**
* Wizard step numbers
*/
export type WizardStep = 1 | 2 | 3 | 4 | 5 | 6;
/**
* Full wizard state
*/
export interface WizardState {
step: WizardStep;
projectName: string;
description: string;
repoUrl: string;
complexity: ProjectComplexity | null;
clientMode: ClientMode | null;
autonomyLevel: AutonomyLevel | null;
}
/**
* Complexity option configuration
*/
export interface ComplexityOption {
id: ProjectComplexity;
label: string;
icon: LucideIcon;
description: string;
scope: string;
examples: string;
skipConfig: boolean;
}
/**
* Client mode option configuration
*/
export interface ClientModeOption {
id: ClientMode;
label: string;
icon: LucideIcon;
description: string;
details: string[];
}
/**
* Approval types for autonomy matrix
*/
export interface ApprovalMatrix {
codeChanges: boolean;
issueUpdates: boolean;
architectureDecisions: boolean;
sprintPlanning: boolean;
deployments: boolean;
}
/**
* Autonomy option configuration
*/
export interface AutonomyOption {
id: AutonomyLevel;
label: string;
icon: LucideIcon;
description: string;
approvals: ApprovalMatrix;
recommended: string;
}
/**
* Initial wizard state
*/
export const initialWizardState: WizardState = {
step: 1,
projectName: '',
description: '',
repoUrl: '',
complexity: null,
clientMode: null,
autonomyLevel: null,
};
/**
* Human-readable labels for approval matrix keys
*/
export const approvalLabels: Record<keyof ApprovalMatrix, string> = {
codeChanges: 'Code Changes',
issueUpdates: 'Issue Updates',
architectureDecisions: 'Architecture Decisions',
sprintPlanning: 'Sprint Planning',
deployments: 'Deployments',
};

View File

@@ -0,0 +1,164 @@
/**
* Custom hook for managing wizard state
*
* Handles step navigation logic including script mode shortcuts.
*/
import { useState, useCallback } from 'react';
import type { WizardState, WizardStep } from './types';
import { initialWizardState } from './types';
import { WIZARD_STEPS } from './constants';
interface UseWizardStateReturn {
state: WizardState;
updateState: (updates: Partial<WizardState>) => void;
resetState: () => void;
isScriptMode: boolean;
canProceed: boolean;
goNext: () => void;
goBack: () => void;
getProjectData: () => ProjectCreateData;
}
/**
* Data structure for project creation API call
*/
export interface ProjectCreateData {
name: string;
slug: string;
description: string | undefined;
autonomy_level: 'full_control' | 'milestone' | 'autonomous';
settings: {
complexity: string;
client_mode: string;
repo_url?: string;
};
}
/**
* Generate a URL-safe slug from a project name
*/
function generateSlug(name: string): string {
return name
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '') // Remove special characters
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-') // Replace multiple hyphens with single
.replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
}
export function useWizardState(): UseWizardStateReturn {
const [state, setState] = useState<WizardState>(initialWizardState);
const isScriptMode = state.complexity === 'script';
const updateState = useCallback((updates: Partial<WizardState>) => {
setState((prev) => ({ ...prev, ...updates }));
}, []);
const resetState = useCallback(() => {
setState(initialWizardState);
}, []);
/**
* Check if user can proceed to next step
*/
const canProceed = (() => {
switch (state.step) {
case WIZARD_STEPS.BASIC_INFO:
return state.projectName.trim().length >= 3;
case WIZARD_STEPS.COMPLEXITY:
return state.complexity !== null;
case WIZARD_STEPS.CLIENT_MODE:
return isScriptMode || state.clientMode !== null;
case WIZARD_STEPS.AUTONOMY:
return isScriptMode || state.autonomyLevel !== null;
case WIZARD_STEPS.AGENT_CHAT:
return true; // Agent chat is preview only
case WIZARD_STEPS.REVIEW:
return true;
default:
return false;
}
})();
/**
* Navigate to next step, handling script mode skip logic
*/
const goNext = useCallback(() => {
if (!canProceed) return;
setState((prev) => {
let nextStep = (prev.step + 1) as WizardStep;
const currentIsScriptMode = prev.complexity === 'script';
// For scripts, skip from step 2 directly to step 5 (agent chat)
if (currentIsScriptMode && prev.step === WIZARD_STEPS.COMPLEXITY) {
return {
...prev,
step: WIZARD_STEPS.AGENT_CHAT as WizardStep,
clientMode: 'auto',
autonomyLevel: 'autonomous',
};
}
// Don't go past review step
if (nextStep > WIZARD_STEPS.REVIEW) {
nextStep = WIZARD_STEPS.REVIEW as WizardStep;
}
return { ...prev, step: nextStep };
});
}, [canProceed]);
/**
* Navigate to previous step, handling script mode skip logic
*/
const goBack = useCallback(() => {
setState((prev) => {
if (prev.step <= 1) return prev;
let prevStep = (prev.step - 1) as WizardStep;
const currentIsScriptMode = prev.complexity === 'script';
// For scripts, go from step 5 back to step 2
if (currentIsScriptMode && prev.step === WIZARD_STEPS.AGENT_CHAT) {
prevStep = WIZARD_STEPS.COMPLEXITY as WizardStep;
}
return { ...prev, step: prevStep };
});
}, []);
/**
* Get data formatted for the project creation API
*/
const getProjectData = useCallback((): ProjectCreateData => {
const slug = generateSlug(state.projectName);
return {
name: state.projectName.trim(),
slug,
description: state.description.trim() || undefined,
autonomy_level: state.autonomyLevel || 'milestone',
settings: {
complexity: state.complexity || 'medium',
client_mode: state.clientMode || 'auto',
...(state.repoUrl && { repo_url: state.repoUrl }),
},
};
}, [state]);
return {
state,
updateState,
resetState,
isScriptMode,
canProceed,
goNext,
goBack,
getProjectData,
};
}