Common Issues & Solutions

DeprecatedHiddenIntroduced in legacy

Owner

@engineering

Last verified

2024-05-01

Sources of truth

  • doc: docs/getting-started/installation.md

> ⚠️ This troubleshooting guide references the legacy Prisma-based stack and will be replaced. Prefer the tips embedded in docs/getting-started/installation.md until the updated diagnostics guide ships.

Installation Issues

Cannot Install Dependencies

Error:
ERR_PNPM_PEER_DEP_ISSUES Unmet peer dependencies

Solution:
# Force install with legacy peer deps
pnpm install --legacy-peer-deps

# Or clean install
rm -rf node_modules pnpm-lock.yaml
pnpm install

Node Version Mismatch

Error:
Error: The engine "node" is incompatible with this module

Solution:
# Check current version
node --version

# Install correct version with nvm
nvm install 20
nvm use 20

# Or update package.json engines

Database Issues

Cannot Connect to Database

Error:
Error: P1001: Can't reach database server at localhost:5432

Solutions:
  • Check PostgreSQL is running:
  • # macOS
    brew services list | grep postgresql
    
    # Linux
    systemctl status postgresql
    
    # Docker
    docker ps | grep postgres

  • Verify connection string:
  • # Test connection
    psql $DATABASE_URL -c "SELECT 1"
    
    # Check format
    # Should be: postgresql://user:pass@host:port/db

  • Check firewall/network:
  • # Allow PostgreSQL port
    sudo ufw allow 5432

    Migration Failures

    Error:
    Error: P3005: The database schema for `postgres` is not empty

    Solution:
    # Reset database (CAUTION: Deletes all data)
    pnpm prisma migrate reset
    
    # Or manually
    pnpm prisma db push --force-reset

    Prisma Client Issues

    Error:
    Error: @prisma/client did not initialize yet

    Solution:
    # Generate Prisma Client
    pnpm prisma generate
    
    # Ensure postinstall script runs
    pnpm install

    OpenRouter API Issues

    Invalid API Key

    Error:
    Error: Invalid API key provided

    Solutions:
  • Verify API key:
  • # Check environment variable
    echo $OPENROUTER_API_KEY
    
    # Should start with sk-or-v1-

  • Check .env.local file:
  • # Ensure no quotes or spaces
    OPENROUTER_API_KEY=sk-or-v1-xxxxx

  • Regenerate key:
  • • Go to OpenRouter Settings
  • • Create new API key
  • • Update .env.local
  • Rate Limiting

    Error:
    Error: Rate limit exceeded. Please try again later.

    Solutions:
  • Add credits to account
  • Implement retry logic:
  • async function retryWithBackoff(fn, retries = 3) {
      for (let i = 0; i < retries; i++) {
        try {
          return await fn()
        } catch (error) {
          if (i === retries - 1) throw error
          await new Promise(r => setTimeout(r, 2 ** i * 1000))
        }
      }
    }

  • Use different model:
  • // Fallback to cheaper model
    const model = rateLimited ? 'openai/gpt-3.5-turbo' : 'anthropic/claude-3.5-sonnet'

    Chat Interface Issues

    Messages Not Streaming

    Problem: Chat responses appear all at once instead of streaming Solutions:
  • Check SSE support:
  • // Ensure using streaming endpoint
    fetch('/api/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ message })
    })

  • Verify response headers:
  • // API route should return:
    return new Response(stream, {
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
      }
    })

  • Check proxy/CDN settings:
  • • Disable buffering for streaming endpoints
  • • Configure Vercel/Cloudflare for SSE
  • Chat History Not Persisting

    Problem: Messages disappear on refresh Solutions:
  • Check authentication:
  • // Ensure user is logged in
    const session = await auth()
    if (!session) {
      // Guest mode - use localStorage
    }

  • Verify database writes:
  • -- Check messages are saved
    SELECT * FROM "Message" WHERE "chatId" = 'xxx';

  • Check React Query cache:
  • // Force refetch
    queryClient.invalidateQueries(['chat', chatId])

    DSL Extraction Issues

    DSL Not Updating

    Problem: DSL panel doesn't reflect conversation Solutions:
  • Check WebSocket/SSE connection:
  • // Browser console
    console.log(eventSource.readyState)
    // Should be 1 (OPEN)

  • Verify DSL extraction in response:
  • // Check API response includes DSL
    const response = await fetch('/api/chat')
    const data = await response.json()
    console.log(data.dsl) // Should have DSL data

  • Check DSL Manager:
  • // Ensure DSL events are stored
    const events = await db.query.dslEvent.findMany({
      where: eq(dslEvent.chatId, chatId)
    })

    Low Confidence Scores

    Problem: AI shows low confidence in extraction Solutions:
  • Provide more specific information:
  • ❌ "I need a system"
    ✅ "I need a task management system with projects, tasks, and users"

  • Clarify relationships:
  • ❌ "Users and tasks are related"
    ✅ "Each user can have many tasks, tasks belong to one user"

  • Include field details:
  • ❌ "Tasks have some fields"
    ✅ "Tasks have title (required), description, status (todo/done), and due date"

    Code Generation Issues

    Generation Button Not Appearing

    Problem: Can't see generate button at 75%+ readiness Solutions:
  • Check readiness calculation:
  • console.log('DSL Readiness:', dsl.readiness)
    // Should be >= 75

  • Verify phase:
  • // Should be 'confirming' or 'building'
    console.log('Current phase:', dsl.phase)

  • Check UI conditions:
  • // components/code-generation-panel.tsx
    const canGenerate = readiness >= 75 && entityCount > 0

    Generated Code Has Errors

    Problem: Generated code doesn't compile Solutions:
  • Check dependencies:
  • # Ensure all required packages installed
    pnpm install

  • Verify TypeScript config:
  • // tsconfig.json
    {
      "compilerOptions": {
        "strict": true,
        "skipLibCheck": true
      }
    }

  • Fix import paths:
  • // Use @ alias consistently
    import { prisma } from '@/lib/prisma'
    // Not: import { prisma } from '../../lib/prisma'

    Performance Issues

    Slow Response Times

    Solutions:
  • Optimize database queries:
  • // Use select to limit fields
    const posts = await prisma.post.findMany({
      select: {
        id: true,
        title: true,
        // Don't fetch content if not needed
      }
    })

  • Implement caching:
  • // Cache frequently accessed data
    const cached = await redis.get(key)
    if (cached) return JSON.parse(cached)

  • Use pagination:
  • // Limit results
    const posts = await prisma.post.findMany({
      take: 20,
      skip: page * 20
    })

    High Memory Usage

    Solutions:
  • Stream large responses:
  • // Use streaming for large data
    const stream = new ReadableStream({
      async start(controller) {
        for (const chunk of data) {
          controller.enqueue(chunk)
        }
        controller.close()
      }
    })

  • Optimize bundle size:
  • # Analyze bundle
    ANALYZE=true pnpm build
    
    # Remove unused dependencies
    pnpm prune --production

    Authentication Issues

    Cannot Login

    Solutions:
  • Check AUTH_SECRET:
  • # Generate new secret
    openssl rand -base64 32
    
    # Update .env.local
    AUTH_SECRET=new_secret_here

  • Clear cookies:
  • // Browser console
    document.cookie.split(";").forEach(c => {
      document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/")
    })

  • Check database user:
  • -- Verify user exists
    SELECT * FROM "User" WHERE email = 'user@example.com';

    Session Expires Too Quickly

    Solutions:
  • Adjust session settings:
  • // auth.config.ts
    export const authConfig = {
      session: {
        strategy: 'jwt',
        maxAge: 30 * 24 * 60 * 60, // 30 days
      }
    }

  • Implement refresh tokens:
  • // Refresh session before expiry
    if (session.expires - Date.now() < 3600000) {
      await refreshSession()
    }

    Deployment Issues

    Vercel Build Failures

    Solutions:
  • Check build logs:
  • vercel logs [deployment-url]

  • Test locally:
  • # Simulate production build
    pnpm build
    pnpm start

  • Clear cache:
  • vercel --force

    Environment Variable Issues

    Solutions:
  • Verify in Vercel dashboard:
  • • Settings → Environment Variables
  • • Check all required vars present
  • Pull to local:
  • vercel env pull .env.local

  • Check variable names:
  • // Common mistake: NEXT_PUBLIC_ prefix
    // Client-side needs: NEXT_PUBLIC_APP_URL
    // Server-side needs: APP_URL

    Browser Issues

    Works in Chrome but not Safari

    Solutions:
  • Check for Safari-specific issues:
  • // Polyfill for Safari
    if (!window.TextEncoder) {
      window.TextEncoder = TextEncoder
    }

  • Test WebSocket/SSE support:
  • // Fallback for older browsers
    if (!window.EventSource) {
      // Use polling instead
    }

    CORS Errors

    Solutions:
  • Configure CORS headers:
  • // middleware.ts
    export function middleware(request: NextRequest) {
      const response = NextResponse.next()
      
      response.headers.set('Access-Control-Allow-Origin', '*')
      response.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
      
      return response
    }

  • Check API routes:
  • // Ensure OPTIONS handled
    export async function OPTIONS() {
      return new Response(null, { status: 200 })
    }

    Getting Help

    Debug Mode

    # Enable debug logging
    DEBUG=* pnpm dev
    
    # Specific module
    DEBUG=prisma:query pnpm dev

    Support Channels

  • • 📖 Documentation
  • • 💬 Discord Community
  • • 🐛 GitHub Issues
  • • 📧 Email Support
  • Provide Information

    When reporting issues, include:
  • Error message/screenshot
  • Steps to reproduce
  • Environment (OS, Node version, browser)
  • Relevant logs
  • DSL context if applicable