# Bug Analysis - Chat Message Flow ## Bug 1: Auth fails on /api/chat/stream (FIXED) - `getAuthUser()` in chat-endpoint.ts used SDK auth which requires JWT cookie - In dev mode, no cookie is set → returns null → 401 Unauthorized - Fix: Added dev-mode bypass matching tRPC context.ts ## Bug 2: Race condition in Home.tsx session creation - When user sends first message with no session: 1. `handleSend()` calls `createSession.mutate()` with inline `onSuccess` that calls `sendMessage(content, session.id)` 2. But `createSession` also has a global `onSuccess` that calls `clearMessages()` 3. Race: `sendMessage` adds user msg + assistant placeholder → `clearMessages()` wipes them - Fix: Remove `clearMessages()` from global createSession.onSuccess when it's triggered by handleSend ## Bug 3: sessionMessages useEffect overwrites optimistic state - When `currentSessionId` changes, `trpc.messages.list.useQuery` fires - The useEffect unconditionally calls `setMessages(mapped)` - This can overwrite the optimistic user message added by useChat before the DB message is visible - Fix: Don't overwrite messages during streaming ## Bug 4: "done" SSE event with empty data gets skipped - Line 123 in useChat.ts: `if (!dataStr || dataStr === "{}") continue;` - The "done" event sends `data: {}` which gets skipped - this is fine - But the "done" event should trigger cleanup ## Action items: 1. ✅ Fix auth bypass in chat-endpoint.ts 2. Fix race condition in Home.tsx 3. Guard sessionMessages effect during streaming 4. Test end-to-end