# Troubleshooting Guide

Common errors and their fixes for the CoreDeskAI project.

---

## React Hydration Mismatch Error

### Symptoms
```
Error: A tree hydrated but some attributes of the server rendered HTML 
didn't match the client properties.
```

You see attributes like `bis_skin_checked="1"` in the error trace.

### Cause
Browser extensions (Bitdefender, Kaspersky, ad blockers, etc.) modify the DOM by adding attributes before React hydrates, causing a mismatch between server-rendered HTML and client-side React.

### Fix Applied
Added a MutationObserver script in `apps/web/app/layout.tsx` that removes extension-added attributes:

```typescript
<script
  dangerouslySetInnerHTML={{
    __html: `
      (function() {
        if (typeof window !== 'undefined') {
          const observer = new MutationObserver(() => {
            document.querySelectorAll('[bis_skin_checked]').forEach(el => {
              el.removeAttribute('bis_skin_checked');
            });
          });
          observer.observe(document.documentElement, {
            attributes: true,
            subtree: true,
            attributeFilter: ['bis_skin_checked']
          });
        }
      })();
    `,
  }}
/>
```

### If Error Reappears

1. **Check for new extension attributes**: Look at the error trace for new attribute names (e.g., `data-extension-id`, `data-adblock`, etc.)

2. **Update the script** in `apps/web/app/layout.tsx`:
   ```typescript
   // Add new attribute names to the array
   attributeFilter: ['bis_skin_checked', 'new_attribute_name']
   
   // Add removal for new attributes
   document.querySelectorAll('[new_attribute_name]').forEach(el => {
     el.removeAttribute('new_attribute_name');
   });
   ```

3. **Alternative: Disable extensions during development**
   - Open browser in incognito/private mode
   - Or disable extensions temporarily

4. **Last resort: Suppress the warning globally**
   - Add to `next.config.mjs`:
   ```javascript
   const nextConfig = {
     reactStrictMode: false, // Disables strict hydration checks
     // ... other config
   }
   ```

---

## Clerk Authentication: "Identity not found"

### Symptoms
```
ConvexError: {"code":"UNAUTHORIZED","message":"Identity not found"}
```

### Cause
Convex can't verify the user's JWT from Clerk because:
1. JWT doesn't have the required `"aud": "convex"` claim
2. Convex auth config doesn't match Clerk's issuer domain
3. ConvexProvider isn't using Clerk's `useAuth` hook

### Fix

#### 1. Add Convex Audience Claim in Clerk
1. Go to https://dashboard.clerk.com
2. Navigate to **Sessions** → **Customize session token**
3. Add this to the claims editor:
   ```json
   {
     "aud": "convex"
   }
   ```
4. Click **Save**

#### 2. Verify Convex Auth Config
Check `packages/backend/convex/auth.config.ts`:
```typescript
export default {
  providers: [
    {
      domain: "https://your-app.clerk.accounts.dev", // Must match Clerk's issuer
      applicationID: "convex",
    },
  ]
};
```

#### 3. Verify ConvexProvider Setup
Check `apps/web/components/providers.tsx`:
```typescript
import { ConvexProviderWithClerk } from "convex/react-clerk";
import { useAuth } from "@clerk/nextjs";

<ConvexProviderWithClerk client={convex} useAuth={useAuth}>
  {children}
</ConvexProviderWithClerk>
```

#### 4. Restart Servers
```bash
# Terminal 1: Restart Convex
cd packages/backend
pnpm dev

# Terminal 2: Restart Next.js
cd apps/web
pnpm dev
```

---

## Organization Not Found Error

### Symptoms
```
ConvexError: {"code":"UNAUTHORIZED","message":"Organization not found"}
```

### Cause
Code is looking for `identity.orgId` but:
1. Clerk Organizations feature is disabled
2. Organization ID isn't included in JWT claims
3. User hasn't created/joined an organization

### Fix

#### Option 1: Enable Clerk Organizations (Recommended)
1. Go to https://dashboard.clerk.com
2. Navigate to **Organizations** → **Enable Organizations**
3. Choose "Membership required" or "Membership optional"
4. Add org ID to session token claims:
   ```json
   {
     "aud": "convex",
     "orgId": "{{org.id}}"
   }
   ```

#### Option 2: Use User ID Instead
If you don't need multi-tenant organizations, use user ID:

```typescript
// In Convex functions
const identity = await ctx.auth.getUserIdentity();
const userId = identity.tokenIdentifier; // Use this instead of orgId
```

---

## Hardcoded Organization ID Fallbacks

### Symptoms
- Multiple users seeing the same data
- Authentication seems to be bypassed
- Seeing test data in production

### Cause
Code has hardcoded organization IDs as fallbacks:
```typescript
const orgId = organization?.id ?? "org_HARDCODED_FALLBACK"; // BAD
```

### Fix
Use the `"skip"` pattern to require authentication:

```typescript
// BEFORE (INSECURE)
const orgId = organization?.id ?? "org_fallback";
const tools = useQuery(api.tools.list, { organizationId: orgId });

// AFTER (SECURE)
const orgId = organization?.id;
const tools = useQuery(
  api.tools.list, 
  orgId ? { organizationId: orgId } : "skip"
);
```

This ensures:
- Queries don't run until user is authenticated
- No data leakage between users
- Clear loading/auth states

---

## Port Already in Use

### Symptoms
```
Error: listen EADDRINUSE: address already in use :::3000
```

### Fix

#### Windows (PowerShell)
```powershell
# Find and kill process on port 3000
Get-NetTCPConnection -LocalPort 3000 | Select-Object -ExpandProperty OwningProcess | ForEach-Object { Stop-Process -Id $_ -Force }
```

#### macOS/Linux
```bash
# Find process
lsof -ti:3000

# Kill process
kill -9 $(lsof -ti:3000)
```

---

## Convex Functions Not Updating

### Symptoms
- Code changes in Convex functions don't take effect
- Old function behavior persists

### Fix

#### 1. Full Restart
```bash
# Stop Convex (Ctrl+C)
cd packages/backend

# Push once
npx convex dev --once

# Restart
pnpm dev
```

#### 2. Clear Convex Cache
```bash
# Delete .convex folder
rm -rf .convex

# Restart
pnpm dev
```

#### 3. Check for TypeScript Errors
```bash
# Run with typecheck enabled
npx convex dev
```

---

## TypeScript Errors in Convex

### Symptoms
```
├ù TypeScript typecheck via `tsc` failed.
```

### Fix

#### 1. Disable Typecheck (Quick Fix)
```bash
# In packages/backend/package.json
"dev": "convex dev --typecheck=disable"
```

#### 2. Fix TypeScript Errors
Check the error output and fix type issues in your Convex functions.

#### 3. Update Dependencies
```bash
cd packages/backend
pnpm update convex
```

---

## Browser Extension Conflicts

### Symptoms
- Hydration errors
- Unexpected attributes in DOM (`bis_skin_checked`, `data-extension-id`, etc.)
- UI behaving strangely

### Fix

#### 1. Identify Conflicting Extension
Look at the error trace for attribute names that indicate which extension is causing issues.

#### 2. Disable Extension
- Temporarily disable the extension
- Or use incognito/private mode

#### 3. Add to Removal Script
Update `apps/web/app/layout.tsx` to remove the extension's attributes.

---

## Environment Variables Not Loading

### Symptoms
- `process.env.NEXT_PUBLIC_CONVEX_URL` is undefined
- Clerk keys not working

### Fix

#### 1. Check File Location
Ensure `.env.local` is in the correct directory:
- `apps/web/.env.local` for Next.js variables
- `packages/backend/.env.local` for Convex variables

#### 2. Restart Dev Server
Environment variables are only loaded on server start:
```bash
# Stop server (Ctrl+C)
# Restart
pnpm dev
```

#### 3. Verify Variable Names
Next.js public variables must start with `NEXT_PUBLIC_`:
```env
NEXT_PUBLIC_CONVEX_URL=https://...  # ✓ Accessible in browser
CONVEX_URL=https://...              # ✗ Only on server
```

---

## Need More Help?

1. **Check Convex Logs**: Look at the terminal running `pnpm dev` in `packages/backend`
2. **Check Browser Console**: Press F12 and look for errors
3. **Check Network Tab**: See if API calls are failing
4. **Clear Cache**: Hard refresh (Ctrl+Shift+R or Cmd+Shift+R)
5. **Restart Everything**: Stop all servers and restart

---

## Quick Diagnostic Checklist

When something isn't working:

- [ ] Are both servers running? (Convex + Next.js)
- [ ] Did you restart after changing `.env.local`?
- [ ] Are you signed in with Clerk?
- [ ] Do you have an organization (if required)?
- [ ] Did you clear browser cache?
- [ ] Are there errors in browser console?
- [ ] Are there errors in Convex terminal?
- [ ] Did you run `pnpm install` after pulling changes?
