Debugging Guide

This guide helps you diagnose and fix common issues in Weldr.dev development.

Debug Tools & Techniques

1. Browser Developer Tools

#### Console Debugging

Check for client-side errors:

// Add debug logging in your code
console.log('DSL State:', dslContext);
console.error('Failed to load:', error);

// Check feature flags
console.log('Annotations enabled?', process.env.NEXT_PUBLIC_USE_ANNOTATIONS);

#### Network Tab

Monitor API calls:

  • Open DevTools → Network tab
  • Filter by "Fetch/XHR"
  • Check for:
  • - Failed requests (red status codes) - Slow responses (>3s) - Payload/response data

    #### React DevTools

    Install React DevTools extension to inspect:

  • • Component props and state
  • • React Query cache
  • • Zustand stores
  • 2. Server-Side Debugging

    #### Terminal Logs

    # Start with verbose logging
    DEBUG=* pnpm dev
    
    # Or specific namespaces
    DEBUG=app:*,db:* pnpm dev

    #### Custom Debug Logging

    Add debug points in server code:

    // In API routes
    console.log('[API] Chat request:', {
      userId: session?.user?.id,
      messageCount: messages.length
    });
    
    // In database queries
    console.log('[DB] Query:', query.toSQL());

    3. Database Debugging

    #### Drizzle Studio

    Inspect your database visually:

    pnpm db:studio
    # Opens at http://localhost:4983

    #### Direct SQL Queries

    Test queries directly:

    # Connect to your database
    psql $POSTGRES_URL
    
    # Check recent messages
    SELECT * FROM "Message" ORDER BY "createdAt" DESC LIMIT 10;
    
    # Check chat sessions
    SELECT id, title, "userId" FROM "Chat" WHERE "userId" = 'your-id';

    4. Authentication Debugging

    #### Check Session State

    // Add to any page component
    import { getSession } from '@/lib/auth/supabase-auth';
    
    export default async function DebugPage() {
      const session = await getSession();
      return <pre>{JSON.stringify(session, null, 2)}</pre>;
    }

    #### Test Authentication Flow

    # Run auth test script
    node test-auth-flow.mjs
    
    # Or manual test
    curl -X POST http://localhost:3000/api/auth/callback/credentials \
      -H "Content-Type: application/json" \
      -d '{"email":"test@example.com"}'

    Common Issues & Solutions

    1. "Module not found: Can't resolve 'fs'"

    Cause: Client component importing server-only code Debug Steps:
  • Check the error stack trace for the importing file
  • Look for 'use client' directive
  • Trace imports back to server modules
  • Solution:
    // ❌ BAD - client component
    'use client';
    import { db } from '@/lib/db'; // Server only!
    
    // ✅ GOOD - use API route
    'use client';
    const data = await fetch('/api/data').then(r => r.json());

    2. "Database query error"

    Debug Steps:
    # 1. Test connection
    node -e "console.log(process.env.POSTGRES_URL)"
    
    # 2. Check migration status
    pnpm db:migrate
    
    # 3. Inspect with studio
    pnpm db:studio

    Common Fixes:
  • • Wrong connection string format
  • • Missing migrations
  • • Connection pool exhausted (restart server)
  • 3. Streaming Not Working

    Debug the streaming pipeline:

    // Add logging to route.ts
    export async function POST(request: Request) {
      console.log('[Stream] Starting...');
    
      const stream = createUIMessageStream({
        execute: ({ writer: dataStream }) => {
          console.log('[Stream] Execute called');
          // ...
        }
      });
    
      stream.pipeThrough(new TransformStream({
        transform(chunk, controller) {
          console.log('[Stream] Chunk:', chunk);
          controller.enqueue(chunk);
        }
      }));
    }

    Check in browser:
    // Monitor SSE in console
    const eventSource = new EventSource('/api/chat');
    eventSource.onmessage = (e) => console.log('SSE:', e.data);

    4. DSL Not Extracting

    Debug DSL extraction:

    // In orchestrator.ts
    console.log('[DSL] Input messages:', messages);
    console.log('[DSL] Extraction result:', extractedDSL);
    console.log('[DSL] Current context:', updatedContext);

    Check feature flags:
    # In .env.local
    ENABLE_DSL_EXTRACTION=true
    NEXT_PUBLIC_USE_ANNOTATIONS=true

    5. Authentication Issues

    Debug auth flow:

    # 1. Clear all cookies
    # 2. Go to root URL (not /chat/new)
    # 3. Check network tab for /api/auth calls
    # 4. Verify session creation

    Add debug middleware:
    // In middleware.ts
    export function middleware(request: NextRequest) {
      console.log('[Auth] Path:', request.nextUrl.pathname);
      console.log('[Auth] Cookies:', request.cookies.getAll());
      // ...
    }

    Advanced Debugging

    Performance Profiling

    // Measure API response times
    console.time('api-call');
    const result = await fetch('/api/chat');
    console.timeEnd('api-call');
    
    // React component rendering
    import { Profiler } from 'react';
    
    <Profiler id="Chat" onRender={(id, phase, duration) => {
      console.log(`${id} (${phase}) took ${duration}ms`);
    }}>
      <Chat />
    </Profiler>

    Memory Leaks

    // Monitor memory usage
    if (typeof window !== 'undefined') {
      setInterval(() => {
        if (performance.memory) {
          console.log('Memory:', {
            used: Math.round(performance.memory.usedJSHeapSize / 1048576) + 'MB',
            total: Math.round(performance.memory.totalJSHeapSize / 1048576) + 'MB'
          });
        }
      }, 5000);
    }

    Zustand Store Debugging

    // Access store from console
    window.__ZUSTAND_DEVTOOLS__ = true;
    
    // In your store
    import { devtools } from 'zustand/middleware';
    
    const useStore = create(devtools((set) => ({
      // your store
    })));

    Debug Scripts

    Quick Health Check

    # Check all systems
    npm run quick:test
    
    # Detailed status
    npm run server:status

    Test Core Flow

    # Test complete chat → DSL → generation flow
    node test-core-flow-v2.mjs
    
    # Test with verbose output
    DEBUG=* node test-integration.mjs

    Logging Best Practices

  • Use consistent prefixes: [API], [DB], [Auth], [DSL]
  • Include context: User ID, request ID, timestamp
  • Avoid logging sensitive data: Passwords, API keys, PII
  • Clean up debug logs before committing
  • Getting Help

    When reporting issues, include:

  • Error message (full stack trace)
  • Steps to reproduce
  • Environment details:
  •    node --version
       pnpm --version
       git rev-parse HEAD

  • Relevant logs (sanitized)
  • Network HAR file if applicable
  • Related Guides

  • Common Issues
  • Performance Optimization
  • Development Setup