---
name: sse-stream-debugger
description: "Diagnose and fix SSE stream interruptions in chat UI. Invoke when user reports 'Answers have stopped', chat freezing, or unexpected stream disconnections. | 诊断和修复聊天UI中的SSE流中断。当用户报告'回答停止'、聊天冻结或意外流断开时触发。"
metadata:
  {
    "builtin_skill_version": "1.0",
    "xingzierai":
      {
        "emoji": "📡",
        "requires": {}
      }
  }
---
# SSE Stream Debugger

Diagnose and fix SSE stream interruptions in the chat UI.

## When to Use

- User reports "Answers have stopped" or "Chat is frozen"
- SSE stream disconnects unexpectedly
- Chat output is incomplete or truncated
- Tool execution results not appearing
- Streaming works in curl but not in browser

## Diagnostic Procedure

### Phase 1: Backend SSE Verification

1. Check backend health:
```bash
curl -s http://localhost:8565/health | head -5
```

2. Test SSE stream directly:
```bash
curl -N http://localhost:8565/api/chat -H "Content-Type: application/json" -d '{"message":"hello"}'
```

3. Check for backend errors:
```bash
grep -i "error\|exception\|traceback" logs/*.log | tail -20
```

### Phase 2: Frontend Processing Analysis

1. Check browser console for errors
2. Verify EventSource/fetch connection state
3. Check if messages are received but not rendered
4. Look for React state update issues

### Phase 3: Root Cause Classification

| Symptom | Likely Root Cause | Fix |
|---------|------------------|-----|
| Stream starts but stops mid-way | LLM timeout or token limit | Increase timeout or reduce max_tokens |
| Stream never starts | Backend crash or auth failure | Check backend logs |
| Stream starts but UI doesn't update | React state not updating | Check rAF throttling |
| Stream works but content is blank | Empty LLM response | Check context compression |
| Stream disconnects after tool call | Tool execution timeout | Increase tool timeout |
| Stream works in curl but not browser | CORS or proxy issue | Check CORS headers |

### Phase 4: Fix Implementation

Apply the appropriate fix based on root cause classification.

### Phase 5: Verification

1. Send 5 test messages to confirm stream stability
2. Test with long responses (>2000 chars)
3. Test with tool execution
4. Test with concurrent sessions

## Common Error Patterns

| Pattern | Error | Fix |
|---------|-------|-----|
| ReadableStream reader leak | "reader is already released" | Ensure reader.releaseLock() in finally block |
| Buffer overflow | Memory grows during streaming | Implement buffer size limit with backpressure |
| Completed premature | Stream ends before full response | Check for early "completed" event |
| Free model DOWN | 503 from LLM provider | Implement fallback to alternative model |

## Prevention

- Always use rAF throttling for SSE updates
- Always release ReadableStream readers in finally blocks
- Always implement buffer size limits
- Always handle "completed" event correctly
- Always implement model fallback
