Generate a fully functional, multi-page Next.js MVP application for 'AgentFlow', a cloud-based platform designed to simplify the creation, orchestration, testing, and deployment of AI agents. Inspired by Google's Scion project, AgentFlow aims to provide developers and data scientists with an intuitive interface for building complex agent systems.
PROJECT OVERVIEW:
AgentFlow addresses the growing complexity of developing and managing multi-agent AI systems. It solves the problem of inefficient agent design, difficult orchestration, and cumbersome testing by providing a unified, visual, and automated platform. The core value proposition is to significantly reduce the time and effort required to build, deploy, and scale sophisticated AI agent networks, enabling users to leverage the power of AI more effectively.
TECH STACK:
- Framework: Next.js (App Router)
- Language: TypeScript
- Styling: Tailwind CSS
- UI Components: shadcn/ui
- ORM: Drizzle ORM (PostgreSQL compatible)
- Database: PostgreSQL (or a compatible provider like Neon, Supabase)
- Authentication: NextAuth.js (e.g., with Google, GitHub providers)
- State Management: React Context API / Zustand (for global state if needed)
- Form Handling: React Hook Form + Zod for validation
- API Layer: Server Actions and Route Handlers
- Other Libraries: `clsx` for conditional classes, `tailwind-merge` for Tailwind classes, `react-table` (or similar for data grid), charting library (e.g., Recharts or Chart.js).
DATABASE SCHEMA:
We'll use Drizzle ORM with PostgreSQL. The schema will be defined in `src/db/schema.ts`.
1. `users` table:
- `id`: UUID (Primary Key, default: uuid_generate_v4())
- `name`: VARCHAR(255)
- `email`: VARCHAR(255) UNIQUE
- `emailVerified`: TIMESTAMP WITH TIME ZONE
- `image`: TEXT
- `createdAt`: TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- `updatedAt`: TIMESTAMP WITH TIME ZONE DEFAULT NOW()
2. `accounts` table (for NextAuth.js):
- `id`: BIGSERIAL PRIMARY KEY
- `userId`: UUID REFERENCES `users`(`id`) ON DELETE CASCADE
- `type`: TEXT
- `provider`: TEXT
- `providerAccountId`: TEXT
- `refresh_token`: TEXT
- `access_token`: TEXT
- `expires_at`: BIGINT
- `token_type`: TEXT
- `scope`: TEXT
- `id_token`: TEXT
- `session_state`: TEXT
3. `sessions` table (for NextAuth.js):
- `sessionToken`: VARCHAR(255) PRIMARY KEY
- `userId`: UUID REFERENCES `users`(`id`) ON DELETE CASCADE
- `expires`: TIMESTAMP WITH TIME ZONE
4. `verificationTokens` table (for NextAuth.js):
- `identifier`: VARCHAR(255)
- `token`: VARCHAR(255)
- `expires`: TIMESTAMP WITH TIME ZONE
- PRIMARY KEY (`identifier`, `token`)
5. `agents` table:
- `id`: UUID PRIMARY KEY DEFAULT uuid_generate_v4()
- `userId`: UUID REFERENCES `users`(`id`) ON DELETE CASCADE
- `name`: VARCHAR(255) NOT NULL
- `description`: TEXT
- `config`: JSONB (e.g., agent type, LLM model, parameters)
- `createdAt`: TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- `updatedAt`: TIMESTAMP WITH TIME ZONE DEFAULT NOW()
6. `workflows` table:
- `id`: UUID PRIMARY KEY DEFAULT uuid_generate_v4()
- `userId`: UUID REFERENCES `users`(`id`) ON DELETE CASCADE
- `name`: VARCHAR(255) NOT NULL
- `description`: TEXT
- `flowData`: JSONB (Defines the connections between agents, triggers, logic - visual representation data)
- `createdAt`: TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- `updatedAt`: TIMESTAMP WITH TIME ZONE DEFAULT NOW()
7. `simulations` table:
- `id`: UUID PRIMARY KEY DEFAULT uuid_generate_v4()
- `workflowId`: UUID REFERENCES `workflows`(`id`) ON DELETE CASCADE
- `userId`: UUID REFERENCES `users`(`id`) ON DELETE CASCADE
- `status`: VARCHAR(50) DEFAULT 'pending' -- pending, running, completed, failed
- `results`: JSONB (Output logs, performance metrics)
- `startTime`: TIMESTAMP WITH TIME ZONE
- `endTime`: TIMESTAMP WITH TIME ZONE
- `createdAt`: TIMESTAMP WITH TIME ZONE DEFAULT NOW()
CORE FEATURES & USER FLOW:
1. **Authentication Flow:**
* User visits the landing page (`/`).
* Clicks 'Sign In' or 'Get Started'.
* Redirected to the NextAuth.js sign-in page.
* User chooses a provider (e.g., Google, GitHub).
* After successful OAuth, user is redirected to the dashboard (`/dashboard`).
* If the user is new, create an entry in the `users` table.
* Subsequent visits redirect directly to the dashboard.
* Sign out functionality available in dropdown menu.
2. **Agent Design & Management:**
* **User Flow:** Dashboard -> 'Agents' tab -> 'Create New Agent' button.
* User navigates to `/dashboard/agents`.
* Sees a list of existing agents (empty state if none).
* Clicks 'Create New Agent'.
* Navigates to `/dashboard/agents/new`.
* Fills out the agent form: Name, Description, Configuration (using a modal/drawer for complex config like LLM selection, parameters, tools).
* Form uses React Hook Form and Zod for validation (required fields: Name).
* Upon submission, a POST request is made via Server Action to `/api/agents`.
* Backend creates a new record in the `agents` table.
* User is redirected back to `/dashboard/agents` with the new agent listed.
* **Edit Agent:** User clicks 'Edit' on an agent row -> navigates to `/dashboard/agents/[id]` -> fills form -> Server Action updates the agent record.
* **Delete Agent:** User clicks 'Delete' -> Confirmation modal -> Server Action deletes the agent record.
3. **Workflow Creation & Orchestration:**
* **User Flow:** Dashboard -> 'Workflows' tab -> 'Create New Workflow'.
* User navigates to `/dashboard/workflows`.
* Sees a list of existing workflows.
* Clicks 'Create New Workflow'.
* Navigates to a visual canvas interface (e.g., using a library like React Flow) at `/dashboard/workflows/new`.
* User drags and drops available agents onto the canvas.
* Connects agents with nodes representing steps, triggers, and conditions.
* Saves the workflow configuration (`flowData` JSONB). The `flowData` will represent the nodes, edges, and their properties.
* Upon saving, a POST request is made via Server Action to `/api/workflows`.
* **Edit Workflow:** User clicks 'Edit' on a workflow -> navigates to `/dashboard/workflows/[id]` -> modifies canvas -> Server Action updates `flowData`.
4. **Simulation & Testing:**
* **User Flow:** Workflow List -> Select Workflow -> 'Run Simulation'.
* User navigates to `/dashboard/workflows/[id]`.
* Clicks 'Run Simulation'.
* A POST request is sent to `/api/simulations` with the `workflowId`.
* Backend creates a new record in the `simulations` table with `status: 'pending'`. The orchestration engine (simulated for MVP) picks up the job.
* The simulation runs, updating the `status` to `running`, then `completed` or `failed`, and populating `results` (logs, metrics).
* User can view simulation status and results on the workflow details page or a dedicated `/dashboard/simulations` page.
* The `results` JSONB will contain structured logs and key performance indicators (KPIs) like execution time, success rate of agent interactions, etc.
API & DATA FETCHING:
- Use Next.js Server Actions for mutations (create, update, delete) on agents, workflows, and simulations. This avoids separate API route handlers for simple CRUD.
- Use Server Components where possible for initial data fetching (e.g., listing agents/workflows on dashboard pages).
- For dynamic data or real-time updates (like simulation status), consider Route Handlers (`app/api/.../route.ts`) or client-side fetching with libraries like SWR or React Query if needed, though Server Actions cover most MVP needs.
- **Example Server Action (Create Agent):**
```typescript
// src/actions/agentActions.ts
'use server';
import { db } from '@/db'; // Your Drizzle DB instance
import { agents } from '@/db/schema';
import { auth } from '@/auth';
import { eq } from 'drizzle-orm';
export async function createAgent(formData: FormData) {
const session = await auth();
if (!session?.user?.id) {
throw new Error('Unauthorized');
}
const name = formData.get('name') as string;
const description = formData.get('description') as string;
const config = JSON.parse(formData.get('config') as string || '{}'); // Handle config parsing
await db.insert(agents).values({
userId: session.user.id,
name,
description,
config,
});
// Revalidate path to refetch data
// revalidatePath('/dashboard/agents'); // Consider using revalidatePath or tag-based revalidation
redirect('/dashboard/agents'); // Or redirect
}
```
- **Data Fetching in Server Components:**
```typescript
// src/app/dashboard/agents/page.tsx
import { db } from '@/db';
import { agents } from '@/db/schema';
import { auth } from '@/auth';
import { eq } from 'drizzle-orm';
import AgentList from '@/components/AgentList'; // Your component
async function AgentsPage() {
const session = await auth();
if (!session?.user?.id) {
// Handle unauthorized access, maybe redirect to login
return <div>Not Authorized</div>;
}
const userAgents = await db.query.agents.findMany({
where: eq(agents.userId, session.user.id),
orderBy: (agents.createdAt, 'desc'),
});
return <AgentList initialAgents={userAgents} />;
}
```
COMPONENT BREAKDOWN (Next.js App Router Structure):
- **`app/`**
* `layout.tsx`: Root layout (includes providers, global styles, auth context).
* `page.tsx`: Landing Page (marketing content, call to action).
* `auth/`
* `signin/page.tsx`: Sign-in page managed by NextAuth.js.
* `dashboard/`
* `layout.tsx`: Dashboard layout (sidebar, header, main content area).
* `page.tsx`: Dashboard overview (summary stats, recent activity).
* `agents/`
* `page.tsx`: List all agents, 'Create New Agent' button. Fetches agents for the logged-in user.
* `[id]/page.tsx`: View/Edit agent details. Fetches a specific agent. Contains form.
* `new/page.tsx`: Form for creating a new agent. (Can be combined with `[id]/page.tsx` using conditional rendering).
* `workflows/`
* `page.tsx`: List all workflows. Button to create new.
* `[id]/page.tsx`: View/Edit workflow details. Includes the visual canvas editor. Fetch workflow data. Contains simulation trigger.
* `new/page.tsx`: Interface for creating a new workflow (visual canvas).
* `simulations/`
* `page.tsx`: List all simulations across workflows. Filterable by status, date.
* `settings/page.tsx`: User settings page.
* `api/`
* `auth/[...nextauth]/route.ts`: NextAuth.js route handler.
* `(Optional) agents/route.ts`: If not using Server Actions for all CRUD.
* `(Optional) workflows/route.ts`: If not using Server Actions.
* `(Optional) simulations/route.ts`: For triggering simulations if not using Server Actions.
- **`components/`**
* `ui/`: Wrapper components from shadcn/ui (e.g., `Button`, `Card`, `Input`, `Dialog`, `Sheet`, `Form`, `FormField`, `Label`, `Select`, `Table`, `Tabs`, `AlertDialog`).
* `layout/`: Dashboard-specific layout components (e.g., `Sidebar`, `Header`, `DashboardLayout`).
* `auth/`: Auth-related components (e.g., `SignInButton`, `SignOutButton`, `UserAvatarDropdown`).
* `agents/`: Agent-specific components (e.g., `AgentList`, `AgentForm`, `AgentCard`, `AgentConfigModal`).
* `workflows/`: Workflow-specific components (e.g., `WorkflowList`, `WorkflowCanvas` (using React Flow), `SimulationTriggerButton`).
* `simulations/`: Simulation-specific components (e.g., `SimulationList`, `SimulationStatusBadge`, `SimulationResultsViewer`).
* `common/`: Reusable components (e.g., `DataTable`, `LoadingSpinner`, `ErrorMessage`).
- **`lib/`**: Utility functions, DB connection, Drizzle schema definitions.
- **`hooks/`**: Custom React hooks.
- **`actions/`**: Server Actions for data mutations.
UI/UX DESIGN & VISUAL IDENTITY:
- **Style:** Modern, clean, and professional with a focus on clarity and usability for technical users. Think minimalist with subtle gradient accents.
- **Color Palette:**
* Primary (Dark Mode): `#1E1E1E` (Background), `#2A2A2A` (Card/Section Background), `#FFFFFF` (Primary Text)
* Primary (Light Mode): `#F5F5F5` (Background), `#FFFFFF` (Card/Section Background), `#1A1A1A` (Primary Text)
* Accent/Brand: A vibrant gradient from `#6366F1` (Indigo) to `#8B5CF6` (Violet) for buttons, active states, and key UI elements.
* Secondary Accent: `#3B82F6` (Blue) for info elements.
* Success: `#22C55E` (Green)
* Warning: `#F59E0B` (Amber)
* Danger: `#EF4444` (Red)
- **Typography:**
* Headings: Inter (or similar sans-serif like Geist Sans), Semi-bold or Bold.
* Body Text: Inter (or similar), Regular.
* Code/Monospace: JetBrains Mono or Fira Code.
- **Layout:** Use a consistent padding and margin system (e.g., multiples of 4px or 8px). Sidebar navigation for the dashboard. Main content area with clear card-based sections for different modules (Agents, Workflows, etc.). Responsive design is crucial, ensuring usability on various screen sizes.
- **Interactions:** Subtle hover effects on buttons and interactive elements. Smooth transitions for modals, drawers, and route changes.
ANIMATIONS:
- **Page Transitions:** Use `AnimatePresence` (if using `framer-motion` or similar) or CSS transitions for smooth loading and unloading of pages/components.
- **Hover Effects:** Slight scale-up or background color change on interactive elements like buttons and cards.
- **Loading States:** Implement spinners or skeleton loaders for data fetching and form submissions. Use Tailwind CSS animations (`animate-spin`, etc.) or a dedicated library.
- **Canvas Animations:** Smooth zooming, panning, and node/edge animations within the workflow editor.
EDGE CASES:
- **Authentication:** Handle unauthorized access gracefully (redirect to sign-in, display messages).
- **Empty States:** Design informative empty states for agent lists, workflow lists, simulation history, providing clear calls to action.
- **Form Validation:** Implement real-time client-side and server-side validation for all forms (e.g., required fields, valid JSON for config, etc.) using Zod and React Hook Form.
- **Error Handling:** Display user-friendly error messages for API failures, validation errors, or simulation failures. Use `try...catch` blocks in Server Actions and Route Handlers. Potentially use a global error boundary component.
- **Data Loading:** Show loading indicators during data fetching. Handle cases where data might be `null` or `undefined` from the backend.
- **Concurrency:** Consider potential race conditions if multiple users/actions modify the same resource (less critical for MVP but good to keep in mind).
- **Configuration Parsing:** Robustly handle `JSON.parse` for agent configurations, showing errors if the JSON is invalid.
SAMPLE DATA:
1. **Agent List (Empty State):**
* Message: "Henüz ajan oluşturmadınız. Ajanlar, otomasyonunuzun yapı taşlarıdır. Hemen yeni bir ajan oluşturun!"
* Button: "Yeni Ajan Oluştur"
2. **Workflow List (Empty State):**
* Message: "İş akışı oluşturmadınız. Farklı ajanları birleştirerek karmaşık görevleri otomatikleştirin."
* Button: "Yeni İş Akışı Oluştur"
3. **Mock Agent Data (for `AgentList` component):**
* `{ id: 'uuid-1', name: 'Email Responder Bot', description: 'Automatically responds to common customer inquiries.', config: { model: 'gpt-4o', temperature: 0.7, prompt: '...' }, createdAt: '2024-05-15T10:00:00Z' }`
* `{ id: 'uuid-2', name: 'Data Scraper', description: 'Scrapes product prices from e-commerce sites.', config: { targetUrl: '...', selectors: ['price'] }, createdAt: '2024-05-16T11:30:00Z' }`
* `{ id: 'uuid-3', name: 'Report Generator', description: 'Generates weekly sales reports from fetched data.', config: { format: 'pdf', data_source_id: 'ds-xyz' }, createdAt: '2024-05-17T09:15:00Z' }`
4. **Mock Workflow Data (for `WorkflowList` component):**
* `{ id: 'wf-uuid-1', name: 'Customer Support Automation', description: 'Handles initial customer support tickets.', createdAt: '2024-05-16T14:00:00Z', status: 'active' }`
* `{ id: 'wf-uuid-2', name: 'Price Monitoring Service', description: 'Monitors e-commerce prices and alerts.', createdAt: '2024-05-17T10:00:00Z', status: 'inactive' }`
5. **Mock Simulation Data (for `SimulationList` component):**
* `{ id: 'sim-uuid-1', workflowId: 'wf-uuid-1', status: 'completed', startTime: '2024-05-18T08:00:00Z', endTime: '2024-05-18T08:05:15Z', results: { 'execution_time_ms': 315000, 'tasks_completed': 15, 'errors': 1 } }`
* `{ id: 'sim-uuid-2', workflowId: 'wf-uuid-2', status: 'running', startTime: '2024-05-18T09:00:00Z', endTime: null, results: null }`
* `{ id: 'sim-uuid-3', workflowId: 'wf-uuid-1', status: 'failed', startTime: '2024-05-17T11:00:00Z', endTime: '2024-05-17T11:02:30Z', results: { 'error_message': 'Agent X failed due to API timeout', 'execution_time_ms': 150000 } }`
**Turkish Translations for UI Elements:**
- Sign In: Giriş Yap
- Sign Out: Çıkış Yap
- Dashboard: Kontrol Paneli
- Agents: Ajanlar
- Workflows: İş Akışları
- Simulations: Simülasyonlar
- Settings: Ayarlar
- Create New Agent: Yeni Ajan Oluştur
- Create New Workflow: Yeni İş Akışı Oluştur
- Run Simulation: Simülasyonu Başlat
- Save: Kaydet
- Cancel: İptal
- Edit: Düzenle
- Delete: Sil
- Name: Ad
- Description: Açıklama
- Configuration: Yapılandırma
- Status: Durum
- Created At: Oluşturulma Tarihi
- Actions: Eylemler
- Active: Aktif
- Inactive: Pasif
- Pending: Bekliyor
- Running: Çalışıyor
- Completed: Tamamlandı
- Failed: Başarısız
- No agents found: Hiç ajan bulunamadı
- No workflows found: Hiç iş akışı bulunamadı
- No simulations found: Hiç simülasyon bulunamadı
- Start Date: Başlangıç Tarihi
- End Date: Bitiş Tarihi
- Execution Time: Çalışma Süresi
- Error Message: Hata Mesajı
This detailed prompt provides all necessary information for an AI to generate the AgentFlow MVP application, including database structure, API logic, component breakdown, UI design guidelines, and essential Turkish translations for key UI elements.