diff --git a/.env b/.env index c77a791..a181243 100644 --- a/.env +++ b/.env @@ -3,3 +3,23 @@ LOG_LEVEL=debug APP_NAME=Nexus APP_PORT=3000 +# Database PostgreSQL with pgvector +DATABASE_URL="postgres://postgres:72ff3d8d80c352f89d99@192.168.1.20:5433/nexus?sslmode=disable" + +# Server +PORT=3000 +CLIENT_URL=http://localhost:3001 + +# JWT +JWT_SECRET=your-super-secret-jwt-key-change-in-production-nexus-2026 + +# File Upload +MAX_FILE_SIZE=10485760 +UPLOAD_DIR=./uploads + +# AI Providers (optional - users configure in UI) +OPENAI_API_KEY= +ANTHROPIC_API_KEY= +GOOGLE_API_KEY= +MISTRAL_API_KEY= +COHERE_API_KEY= diff --git a/.gitignore b/.gitignore index b12c4ac..adb3c29 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,5 @@ logs/ coverage/ .nyc_output/ + +/src/generated/prisma diff --git a/DATABASE-SETUP.md b/DATABASE-SETUP.md new file mode 100644 index 0000000..bb728ee --- /dev/null +++ b/DATABASE-SETUP.md @@ -0,0 +1,652 @@ +# ๐๏ธ Sistema de Persistencia con PostgreSQL + Prisma + +## Base de Datos Completa con RAG Vector Support + +He implementado un sistema completo de persistencia usando PostgreSQL con soporte para vectores (pgvector) para RAG, utilizando Prisma ORM para un manejo escalable. + +--- + +## ๐ Arquitectura de Base de Datos + +### Conexiรณn PostgreSQL +``` +Host: 192.168.1.20:5433 +Database: nexus +User: postgres +Password: 72ff3d8d80c352f89d99 +Extension: pgvector (para RAG) +``` + +### Variables de Entorno (.env) +```env +# Database +DATABASE_URL="postgres://postgres:72ff3d8d80c352f89d99@192.168.1.20:5433/nexus?sslmode=disable" + +# Server +PORT=3000 +NODE_ENV=development +CLIENT_URL=http://localhost:3001 + +# JWT +JWT_SECRET=your-super-secret-jwt-key-change-in-production-nexus-2026 + +# File Upload +MAX_FILE_SIZE=10485760 +UPLOAD_DIR=./uploads + +# AI Providers (optional - users configure in UI) +OPENAI_API_KEY= +ANTHROPIC_API_KEY= +GOOGLE_API_KEY= +MISTRAL_API_KEY= +COHERE_API_KEY= +``` + +--- + +## ๐๏ธ Modelos de Base de Datos + +### 1. User +```prisma +model User { + id String @id @default(cuid()) + email String @unique + name String? + password String + avatar String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + conversations Conversation[] + aiProviders AIProvider[] + knowledgeBases KnowledgeBase[] + agents Agent[] + settings AppSettings? +} +``` + +**Propรณsito**: Gestiรณn de usuarios y autenticaciรณn + +--- + +### 2. AppSettings (Branding + Config) +```prisma +model AppSettings { + id String @id @default(cuid()) + userId String @unique + + // Branding + appName String @default("NexusChat") + appLogo String? // URL or base64 + appIcon String? // URL or base64 for avatar/favicon + + // Theme + theme String @default("dark") + primaryColor String @default("#667eea") + + // General Settings + autoSave Boolean @default(true) + soundEnabled Boolean @default(false) + language String @default("en") +} +``` + +**Propรณsito**: +- โ Personalizaciรณn de marca (logo, icono, nombre) +- โ Configuraciรณn de tema +- โ Preferencias generales + +--- + +### 3. AIProvider +```prisma +model AIProvider { + id String @id @default(cuid()) + userId String + + providerId String // openai, anthropic, google, mistral, cohere + name String + enabled Boolean @default(false) + apiKey String? @db.Text // Encrypted +} +``` + +**Propรณsito**: Almacenar configuraciรณn de AI Providers por usuario + +--- + +### 4. Conversation +```prisma +model Conversation { + id String @id @default(cuid()) + userId String + + title String + agentId String? + + modelId String? // gpt-4o, claude-3-opus, etc + providerId String? // openai, anthropic, etc + + messages Message[] + topics Topic[] +} +``` + +**Propรณsito**: Gestiรณn de conversaciones de chat + +--- + +### 5. Message +```prisma +model Message { + id String @id @default(cuid()) + conversationId String + + role String // user, assistant, system + content String @db.Text + + // Metadata + tokensUsed Int? + model String? +} +``` + +**Propรณsito**: Almacenar mensajes de las conversaciones + +--- + +### 6. Topic +```prisma +model Topic { + id String @id @default(cuid()) + conversationId String + + title String + order Int @default(0) +} +``` + +**Propรณsito**: Topics del panel derecho del chat + +--- + +### 7. KnowledgeBase +```prisma +model KnowledgeBase { + id String @id @default(cuid()) + userId String + + name String + description String? @db.Text + + documents Document[] + agents Agent[] +} +``` + +**Propรณsito**: Contenedor de documentos para RAG + +--- + +### 8. Document +```prisma +model Document { + id String @id @default(cuid()) + knowledgeBaseId String + + fileName String + fileType String + fileSize Int + filePath String + + status String @default("processing") // processing, ready, error + chunksCount Int @default(0) + + chunks DocumentChunk[] +} +``` + +**Propรณsito**: Archivos subidos para RAG + +--- + +### 9. DocumentChunk (RAG con Vectores) +```prisma +model DocumentChunk { + id String @id @default(cuid()) + documentId String + + content String @db.Text + chunkIndex Int + + // Vector embedding for semantic search (using pgvector) + // TODO: Enable after pgvector extension is installed + // embedding Unsupported("vector(1536)")? + + metadata Json? // Additional metadata +} +``` + +**Propรณsito**: +- โ Chunks de documentos procesados +- โ Vector embeddings para bรบsqueda semรกntica +- โ Metadata adicional + +**Nota**: El campo `embedding` estรก comentado temporalmente. Se habilitarรก despuรฉs de instalar la extensiรณn pgvector en PostgreSQL. + +--- + +### 10. Agent +```prisma +model Agent { + id String @id @default(cuid()) + userId String + + name String + emoji String @default("๐ค") + role String + description String @db.Text + + status String @default("active") // active, inactive + + // Capabilities + mcpEnabled Boolean @default(false) + mcpTools Json? // Array of MCP tools + + // RAG Configuration + ragEnabled Boolean @default(false) + + // Stats + interactions Int @default(0) + lastUsedAt DateTime? + + conversations Conversation[] + knowledgeBases KnowledgeBase[] +} +``` + +**Propรณsito**: Agentes IA configurables con MCP y RAG + +--- + +## ๐จ Nueva Feature: Branding Settings + +### Componente SettingsBranding + +Permite personalizar: +1. **Nombre de la aplicaciรณn** +2. **Logo (texto)** - Imagen para el header +3. **Icono (avatar)** - Imagen para el chat avatar + +### Visual +``` +โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ +โ โจ Branding โ +โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค +โ โ +โ Nombre de la Aplicaciรณn โ +โ [NexusChat ] โ +โ โ +โ โโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโ โ +โ โ Logo โ Icono โ โ +โ โ โ โ โ +โ โ โฌ๏ธ Upload โ โฌ๏ธ Upload โ โ +โ โ Click para โ Click para subir โ โ +โ โ subir logo โ icono โ โ +โ โ โ โ โ +โ โโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโ โ +โ โ +โ [Guardar Cambios] โ +โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ +``` + +### Funcionalidades +- โ Upload de imagen para logo +- โ Upload de imagen para icono +- โ Cambiar nombre de la app +- โ Preview de imรกgenes +- โ Botรณn para remover imรกgenes +- โ Guardar en localStorage (temporal) +- โ TODO: Guardar en base de datos + +--- + +## ๐ Estructura de Archivos + +### Backend +``` +/ +โโโ .env (configuraciรณn) +โโโ prisma/ +โ โโโ schema.prisma (modelos) +โ โโโ migrations/ (migraciones) +โ +โโโ src/ + โโโ config/ + โโโ prisma.ts (cliente singleton) +``` + +### Frontend +``` +client/src/components/ +โโโ SettingsBranding.tsx (nuevo componente) +``` + +--- + +## ๐ Uso del Sistema + +### 1. Iniciar Base de Datos +La base de datos ya estรก configurada en `192.168.1.20:5433` + +### 2. Aplicar Migraciones +```bash +cd /Users/cesarmendivil/WebstormProjects/Nexus +npx prisma migrate dev +``` + +### 3. Generar Cliente +```bash +npx prisma generate +``` + +### 4. Usar Prisma en Backend +```typescript +import prisma from './config/prisma'; + +// Crear usuario +const user = await prisma.user.create({ + data: { + email: 'user@example.com', + password: 'hashed_password', + name: 'John Doe', + }, +}); + +// Guardar configuraciรณn de AI Provider +await prisma.aIProvider.create({ + data: { + userId: user.id, + providerId: 'openai', + name: 'OpenAI', + enabled: true, + apiKey: 'encrypted_key', + }, +}); + +// Crear conversaciรณn +const conversation = await prisma.conversation.create({ + data: { + userId: user.id, + title: 'Nueva conversaciรณn', + modelId: 'gpt-4o', + providerId: 'openai', + }, +}); + +// Guardar mensaje +await prisma.message.create({ + data: { + conversationId: conversation.id, + role: 'user', + content: 'Hola!', + }, +}); +``` + +--- + +## ๐ Flujo de Datos + +### Configuraciรณn de AI Providers +``` +UI (SettingsModal) + โ localStorage (temporal) + โ Backend API (TODO) + โ Prisma + โ PostgreSQL +``` + +### Branding +``` +UI (SettingsBranding) + โ Upload imagen + โ Base64 / File + โ localStorage (temporal) + โ Backend API (TODO) + โ Prisma (AppSettings) + โ PostgreSQL +``` + +### RAG Pipeline +``` +1. Usuario sube archivo + โ KnowledgeBase + +2. Backend procesa archivo + โ Divide en chunks + โ DocumentChunk + +3. Genera embeddings + โ OpenAI embeddings API + โ Guarda en vector field + +4. Bรบsqueda semรกntica + โ Query โ embedding + โ pgvector similarity search + โ Retorna chunks relevantes +``` + +--- + +## ๐ Diagrama de Relaciones + +``` +User + โโโ Conversation + โ โโโ Message + โ โโโ Topic + โ + โโโ AIProvider + โ + โโโ KnowledgeBase + โ โโโ Document + โ โโโ DocumentChunk (with vector) + โ + โโโ Agent + โ โโโ KnowledgeBase (many-to-many) + โ + โโโ AppSettings +``` + +--- + +## ๐ Seguridad + +### API Keys +- โ Almacenadas en campo `@db.Text` +- โ ๏ธ TODO: Implementar encriptaciรณn +- โ No expuestas en el cliente + +### Passwords +- โ ๏ธ TODO: Implementar hashing (bcrypt) +- โ Campo password en User model + +### JWT +- โ Secret configurado en .env +- โ ๏ธ TODO: Implementar autenticaciรณn + +--- + +## ๐ Prรณximos Pasos + +### Backend APIs a Implementar + +#### 1. Auth +```typescript +POST /api/auth/register +POST /api/auth/login +POST /api/auth/logout +GET /api/auth/me +``` + +#### 2. AI Providers +```typescript +GET /api/providers +POST /api/providers +PUT /api/providers/:id +DELETE /api/providers/:id +``` + +#### 3. Conversations +```typescript +GET /api/conversations +POST /api/conversations +GET /api/conversations/:id +DELETE /api/conversations/:id +POST /api/conversations/:id/messages +``` + +#### 4. Knowledge Base +```typescript +GET /api/knowledge +POST /api/knowledge +POST /api/knowledge/:id/documents +GET /api/knowledge/:id/documents +DELETE /api/documents/:id +``` + +#### 5. Agents +```typescript +GET /api/agents +POST /api/agents +PUT /api/agents/:id +DELETE /api/agents/:id +``` + +#### 6. Settings +```typescript +GET /api/settings +PUT /api/settings +POST /api/settings/branding/upload +``` + +--- + +## ๐ฏ Integraciรณn con Frontend + +### useChat Hook (Actualizar) +```typescript +// En lugar de localStorage +const messages = await fetch('/api/conversations/${id}/messages'); + +// Guardar mensaje +await fetch('/api/conversations/${id}/messages', { + method: 'POST', + body: JSON.stringify({ content, role: 'user' }), +}); +``` + +### SettingsAIProviders (Actualizar) +```typescript +// En lugar de localStorage +const providers = await fetch('/api/providers'); + +// Guardar provider +await fetch('/api/providers', { + method: 'POST', + body: JSON.stringify(providerData), +}); +``` + +### SettingsBranding (Actualizar) +```typescript +// Upload logo +const formData = new FormData(); +formData.append('logo', file); + +await fetch('/api/settings/branding/upload', { + method: 'POST', + body: formData, +}); +``` + +--- + +## ๐๏ธ Comandos รtiles de Prisma + +### Ver Base de Datos +```bash +npx prisma studio +``` +Abre interfaz web en `http://localhost:5555` + +### Crear Migraciรณn +```bash +npx prisma migrate dev --name migration_name +``` + +### Reset Database +```bash +npx prisma migrate reset +``` + +### Pull Schema from DB +```bash +npx prisma db pull +``` + +### Push Schema to DB (sin migraciรณn) +```bash +npx prisma db push +``` + +--- + +## โ Estado Actual + +``` +โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ +โ โ BASE DE DATOS CONFIGURADA โ +โ โ +โ PostgreSQL: 192.168.1.20:5433 โ +โ Database: nexus โ +โ ORM: Prisma โ +โ Extension: pgvector (preparado) โ +โ โ +โ Modelos: 10 โ +โ - User โ +โ - AppSettings (Branding) โ +โ - AIProvider โ +โ - Conversation โ +โ - Message โ +โ - Topic โ +โ - KnowledgeBase โ +โ - Document โ +โ - DocumentChunk (RAG) โ +โ - Agent โ +โ โ +โ Features Frontend: โ +โ โ Branding Settings UI โ +โ โ Upload logo/icono โ +โ โ Cambiar nombre app โ +โ โ +โ TODO: โ +โ โณ Backend APIs โ +โ โณ Autenticaciรณn โ +โ โณ Encriptaciรณn API Keys โ +โ โณ Integraciรณn RAG pipeline โ +โ โ +โ Estado: ESTRUCTURA COMPLETA โ โ +โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ +``` + +--- + +**Implementado**: 14 de Febrero, 2026 +**Base de Datos**: PostgreSQL con pgvector +**ORM**: Prisma +**Modelos**: 10 completos +**Features**: Branding Settings UI +**Estado**: โ **ESTRUCTURA LISTA - APIs PENDIENTES** + diff --git a/WELCOME-SCREEN.md b/WELCOME-SCREEN.md new file mode 100644 index 0000000..866b4a4 --- /dev/null +++ b/WELCOME-SCREEN.md @@ -0,0 +1,312 @@ +# โ WELCOME SCREEN "GOOD EVENING" IMPLEMENTADO + +## Pantalla de Bienvenida para Nuevo Chat + +He implementado la pantalla de bienvenida que se mostrarรก por defecto cuando el usuario entre a un nuevo chat en el Content Area. + +--- + +## ๐จ Diseรฑo Visual + +``` +โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ +โ โ +โ ๐ โ +โ Good Evening โ +โ โ +โ I am your personal intelligent assistant LobeChat โ +โ If you need a more professional assistant, click + โ +โ โ +โ New Assistant Recommendations: ๐ โ +โ โ +โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ โ +โ โ ๐ต โ ๐ โ โ +โ โ Internationalโ Backtracking โ โ +โ โ Lyricist โ Question... โ โ +โ โ โ โ โ +โ โโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโ โ +โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ โ +โ โ ๐ฎ โ ๐ป โ โ +โ โ Unreal Engineโ TypeScript โ โ +โ โ Master โ Solution... โ โ +โ โ โ โ โ +โ โโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโ โ +โ โ +โ Frequently Asked Questions: โฐ Back to bottom โ +โ โ +โ [Does LobeChat support...] [What is LobeChat?] โ +โ [Is there a marketplace...] โ +โ โ +โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ +``` + +--- + +## ๐ฆ Componente: WelcomeScreen.tsx + +### Features Implementadas + +#### 1. **Saludo Principal** ๐ +```typescript +- Emoji animado: ๐ (48px) +- Tรญtulo: "Good Evening" (28px, bold) +- Subtรญtulo informativo +- Highlight para el botรณn "+" +``` + +#### 2. **Asistentes Recomendados** +```typescript +- Grid 2x2 responsive +- Cards con hover effect +- 4 asistentes predefinidos: + โข ๐ต International Lyricist + โข ๐ Backtracking Question Expert + โข ๐ฎ Unreal Engine Master + โข ๐ป TypeScript Solution Architect +- Botรณn refresh para actualizar +``` + +#### 3. **Preguntas Frecuentes** +```typescript +- Chips interactivos +- 3 preguntas por defecto +- Click para enviar pregunta +- Botรณn "Back to bottom" +``` + +--- + +## ๐ฏ Props del Componente + +```typescript +interface WelcomeScreenProps { + onAssistantSelect?: (assistant: Assistant) => void; + onQuestionSelect?: (question: string) => void; +} + +interface Assistant { + id: string; + icon: string; + name: string; + description: string; +} +``` + +--- + +## ๐ Integraciรณn con LobeChatArea + +### Antes (Empty State Simple) +```typescript +{messages.length === 0 ? ( +
,
- title: 'Escribir cรณdigo',
- description: 'Ayรบdame a programar algo',
+ id: 'backtracking',
+ icon: '๐',
+ name: 'Backtracking Question Expert',
+ description: 'Hello! I am an expert in world knowledge, skilled in using backtracking questioning strategies to...',
},
{
- icon: + I am your personal intelligent assistant LobeChat, how can I help you now? +
+
+ If you need a more professional or customized assistant, you can click on{' '}
+
+