YourBench.ai is a multi-persona AI chat application built as a monorepo using Next.js 15, TypeScript, and PostgreSQL with pgvector for embeddings. Provides a chat interface for AI interactions within organization-scoped workspaces.
Current Status: MVP Phase - Core features implemented, test suite at 100% pass rate (305+ tests passing)
- Frontend: Next.js 15, React 19, TypeScript, Tailwind CSS, shadcn/ui
- Backend: Next.js API Routes, Supabase (PostgreSQL + Auth)
- Database: PostgreSQL 16 with pgvector extension
- Authentication: Supabase Auth with Row Level Security (RLS)
- AI Providers: OpenAI, Google Gemini, Anthropic Claude (Provider Registry System - TT004 ✅ COMPLETED)
- Deployment: Vercel (FREE tier) with native Supabase integration
- Testing: Vitest, Testing Library, MSW for API mocking
- Monorepo: Turborepo for workspace management
yourbench/
├── apps/web/ # Next.js 15 web application
│ ├── lib/providers/ # AI Provider Registry System (TT004)
│ ├── lib/database/ # Database Access Layer (TT002)
│ ├── lib/auth/ # Authentication System
│ ├── app/api/ # API Routes
│ └── components/ # React Components
├── packages/ui/ # Shared UI components
├── supabase/migrations/ # Database schema and migrations
├── docs/ # Technical documentation
├── tasks/ # Task management and completed tasks
└── .cursor/rules/ # AI development standards
id(UUID) - Primary Keyname(VARCHAR(100)) - Organization name (e.g., "John Doe's Workspace")description(TEXT) - Organization description (max 500 characters)created_at,updated_at,deleted_at(TIMESTAMP)
id(UUID, references auth.users) - Primary Keyorganization_id(UUID) - References organizations.idemail(VARCHAR(255)) - User email addressfull_name(VARCHAR(255)) - User's full nameavatar_url(TEXT) - Profile picture URLrole(VARCHAR(20)) - User role: 'user', 'admin', 'super_admin'created_at,updated_at(TIMESTAMP)
id(UUID) - Primary Keyorganization_id(UUID) - References organizations.id (NULL for global personas)user_id(UUID) - Owner (NULL for global personas)name(VARCHAR(255)) - Display namedescription(TEXT) - Persona descriptionavatar(VARCHAR(10)) - Emoji avatarprovider(VARCHAR(50)) - AI provider: 'openai', 'gemini', 'anthropic'model_id(VARCHAR(100)) - Specific model identifiersystem_prompt(TEXT) - AI behavior instructionsis_custom(BOOLEAN) - Whether user-created or globalcreated_at,updated_at(TIMESTAMP)
id(UUID) - Primary Keyorganization_id(UUID) - References organizations.iduser_id(UUID) - Project ownername(VARCHAR(255)) - Project namedescription(TEXT) - Project descriptioncreated_at,updated_at(TIMESTAMP)
id(UUID) - Primary Keyorganization_id(UUID) - References organizations.iduser_id(UUID) - Room ownerproject_id(UUID) - Associated project (NULL for DMs)name(VARCHAR(255)) - Room nameroom_type(VARCHAR(20)) - 'group' or 'dm'created_at,updated_at(TIMESTAMP)
id(UUID) - Primary Keyorganization_id(UUID) - References organizations.idroom_id(UUID) - Associated chat roompersona_id(UUID) - AI persona that respondedrole(VARCHAR(20)) - 'user' or 'assistant'content(TEXT) - Message contenttokens_used(INTEGER) - Token consumptionprovider(VARCHAR(50)) - AI provider usedembedding(vector(1536)) - Message embedding for RAGcreated_at(TIMESTAMP)
id(UUID) - Primary Keyorganization_id(UUID) - References organizations.idroom_id(UUID) - Associated chat roomsummary(TEXT) - Conversation summaryembedding(vector(1536)) - Summary embeddingcreated_at(TIMESTAMP)
id(UUID) - Primary Keyorganization_id(UUID) - References organizations.iduser_id(UUID) - User being trackeddate(DATE) - Usage dateprovider(VARCHAR(50)) - AI providermodel_id(VARCHAR(100)) - Model usedtokens_used(INTEGER) - Daily token usageestimated_cost_usd(DECIMAL(10,4)) - Cost estimatecreated_at,updated_at(TIMESTAMP)
- Organization → Users: One organization can have multiple users (future business accounts)
- Organization → Projects: One organization can have multiple projects
- Organization → Chat Rooms: One organization can have multiple rooms
- Organization → Messages: One organization can have multiple messages
- Organization → Personas: One organization can have multiple custom personas
- Organization → Usage Stats: One organization can have multiple usage records
- User → DMs: One user can have multiple DMs
- Project → Chat Rooms: One project can have multiple rooms
- Chat Room → Messages: One room can have multiple messages
- Chat Room → Summaries: One room can have multiple summaries
- Global Personas: Available to all organizations (organization_id = NULL)
- Organizations: Users can only view their own organization (admin can view all)
- Users: Users can only view users in their organization (admin can view all)
- Personas: Users see their organization's custom personas + global personas (admin sees all)
- Projects: Users see projects in their organization (admin sees all)
- Chat Rooms: Users see rooms in their organization (admin sees all)
- Messages: Users see messages in their organization (admin sees all)
- Usage Stats: Admin only access
create_organization_for_user(user_uuid, user_name)- Create implicit organization for new userget_user_organization(user_uuid)- Get user's organizationupdate_organization_name(org_uuid, new_name)- Update organization nameupdate_organization_description(org_uuid, new_description)- Update organization descriptionreset_organization_name(org_uuid)- Reset organization name to defaultis_admin(user_uuid)- Check if user has admin/super_admin roleis_super_admin(user_uuid)- Check if user has super_admin roletrack_usage(...)- Track daily usage statistics
- Vector Indexes: pgvector indexes on message and summary embeddings
- Foreign Key Indexes: Optimized for join performance
- Composite Indexes: Organization + date combinations for usage tracking
- Text Search: Full-text search capabilities on message content
- Organization Indexes: Optimized for organization-scoped queries
/api/auth/*- Supabase Auth integration- Middleware:
middleware.ts- Route protection and user session management
/api/organizations- Organization management- GET: Get current user's organization
- PUT: Update organization name and description
- POST: Create organization (for future business accounts)
/api/chat- Main chat endpoint for AI interactions- POST: Process user messages and return AI responses
- Features: Multi-provider support, @ mentions, conversation history
- Providers: OpenAI, Gemini, Anthropic with fallback logic
- Organization Context: Automatically scoped to user's organization
/api/projects- Project CRUD operations- GET: List user's projects (organization-scoped)
- POST: Create new project (organization-scoped)
- PUT: Update project details
- DELETE: Delete project
/api/rooms- Chat room operations- GET: List rooms for project or user (organization-scoped)
- POST: Create new room (organization-scoped)
- PUT: Update room details
- DELETE: Delete room
/api/personas- Persona CRUD operations- GET: List available personas (global + organization's custom)
- POST: Create custom persona (organization-scoped)
- PUT: Update persona details
- DELETE: Delete custom persona
/api/admin/*- Administrative functions- User Management: View all users, update roles
- Organization Management: View all organizations, usage analytics
- Usage Analytics: Cost tracking and usage statistics
- System Monitoring: Health checks and performance metrics
/api/webhooks/*- External service integrations- Supabase Webhooks: Real-time database changes
- Vercel Webhooks: Deployment notifications
interface APIResponse<T> {
data?: T;
error?: string;
message?: string;
status: number;
}interface OrganizationUpdateRequest {
name?: string; // Max 100 characters
description?: string; // Max 500 characters
}interface OrganizationResponse {
id: string;
name: string;
description?: string;
created_at: string;
updated_at: string;
}- Complete Organization Isolation: No data sharing between organizations
- Row Level Security (RLS): Database-level access control
- Organization Context: All API routes automatically scope to user's organization
- Admin Access: Admins can view all organizations but cannot edit organization data
- JWT Authentication: Secure token-based authentication via Supabase Auth
- Input Validation: Request sanitization and validation
- Rate Limiting: API endpoint protection
YourBench implements a five-tier context hierarchy enabling AI personas to access relevant information while maintaining proper data isolation.
- Organization Level - Root isolation boundary for multi-tenancy
- User Level - Individual user data and preferences within organization
- Direct Messages - Private 1:1 conversations with AI personas
- Project Level - High-level context for related work
- Room Level - Multi-user conversations with personas
- Organization Isolation: Complete data separation between organizations
- DM Privacy: Direct messages never accessible in rooms
- Room Cross-Reference: Personas can access summaries of rooms they participate in
- Project Inheritance: Project context flows to all child rooms
- Hard Boundaries: Organization and DM levels have strict isolation
- Soft Boundaries: Room and project levels allow controlled sharing
- Persona Access: Manual participation control for room access
- Summary Access: Cross-room information through controlled summaries
- Vector Search: Optimized pgvector indexes for semantic search
- Organization Scoping: All queries automatically filtered by organization
- Connection Pooling: Efficient database connection management
- Caching: Redis for session and frequently accessed data
- CDN: Static asset delivery via Vercel Edge Network
- Serverless Functions: Scalable API endpoint execution
- TT001: Context Hierarchy Data Model ✅ - Organization-scoped data isolation with multi-level context management
- TT002: Database Access Layer Abstraction ✅ - Repository pattern with environment-agnostic data access
- TT003: Authentication Service Centralization 🔄 - Client-side Supabase Auth implemented (ready for centralization)
- TT004: Provider Registry System ✅ - Dynamic provider management with resilient initialization
- TT005: Component State Management Refactoring ✅ - React Context for global state management
- Location:
apps/web/lib/providers/ - Features: Dynamic provider management, configuration-driven selection, resilient initialization
- Resilience: Gracefully handles API connectivity issues, no more HTTP 500 errors
- Fallback: Automatic provider fallback with circuit breaker pattern
- Location:
apps/web/lib/database/ - Pattern: Repository pattern with database factory
- Environment: Environment-agnostic data access
- Features: Transaction management, connection pooling, type-safe queries
- Location:
apps/web/lib/auth/ - Architecture: Client-side Supabase Auth with React Context
- Security: Row Level Security (RLS) with organization-level isolation
- Features: Email/password, OAuth, session management
apps/web/
├── lib/
│ ├── providers/ # AI Provider Registry System (TT004)
│ │ ├── registry.ts # Provider registration and management
│ │ ├── factory.ts # Provider instantiation
│ │ ├── config.ts # Configuration management
│ │ └── implementations/ # Provider implementations
│ ├── database/ # Database Access Layer (TT002)
│ │ ├── factory.ts # Database factory
│ │ ├── repositories/ # Repository implementations
│ │ └── connections/ # Database connections
│ └── auth/ # Authentication System
│ ├── context.tsx # React Context for auth state
│ └── service.ts # Authentication service
├── app/api/ # API Routes
│ ├── chat/ # Main chat endpoint
│ ├── projects/ # Project management
│ ├── rooms/ # Room management
│ └── personas/ # Persona management
└── components/ # React Components
- Application Performance: Vercel Analytics and Real User Monitoring
- Database Performance: Supabase dashboard and query analysis
- Error Tracking: Sentry integration for error monitoring
- Usage Analytics: Custom dashboard for token usage and cost tracking
- Health Checks: Automated monitoring of critical system components
- Provider Health: Real-time monitoring of AI provider availability and performance