[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6C5M5298SZJYTPB07YRWWQT":3,"skill-same:01M6C5M5298SZJYTPB07YRWWQT":75},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":48,"commitSha":49,"skillDirectory":50,"forksCount":14,"repositoryHtmlUrl":51,"repositoryHomepageUrl":6,"ownerHtmlUrl":52,"ownerBlogUrl":53,"ownerDescription":6,"updatedAt":54,"install":55,"resources":68},"01M6C5M5298SZJYTPB07YRWWQT","sse-streaming",null,"Implement Server-Sent Events (SSE) for real-time updates with automatic reconnection and heartbeats. Use when building live dashboards, notifications, progress indicators, or any feature needing server-to-client push.","CoralShades\u002Facm-ai","CoralShades","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F220297585?v=4","01M6C5211QSJHZ8HXSDDWCR507","Coral Shades AI Agency","01M6C52161FNQDRQ0FRR8DAA9D",0,"MIT","https:\u002F\u002Fgithub.com\u002FCoralShades\u002Facm-ai\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsse-streaming\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"streaming","sse","sse streaming","typescript","python","implement","javascript","realtime","push","notifications","server","real-time","indicators","dashboards","use","2026-11-10 10:12:30",false,"---\nname: sse-streaming\ndescription: Implement Server-Sent Events (SSE) for real-time updates with automatic reconnection and heartbeats. Use when building live dashboards, notifications, progress indicators, or any feature needing server-to-client push.\nlicense: MIT\ncompatibility: TypeScript\u002FJavaScript, Python\nmetadata:\n  category: realtime\n  time: 3h\n  source: drift-masterguide\n---\n\n# Server-Sent Events (SSE)\n\nReal-time server-to-client streaming with automatic reconnection.\n\n## When to Use This Skill\n\n- Live dashboards and monitoring\n- Real-time notifications\n- Progress indicators for long operations\n- Live feeds (activity, chat, updates)\n- AI streaming responses\n\n## SSE vs WebSockets\n\n| Feature | SSE | WebSocket |\n|---------|-----|-----------|\n| Direction | Server → Client | Bidirectional |\n| Protocol | HTTP | WS |\n| Reconnection | Automatic | Manual |\n| Complexity | Simple | Complex |\n| Browser Support | Native | Native |\n| Through Proxies | Easy | Can be tricky |\n\n**Use SSE when**: You only need server-to-client push\n**Use WebSocket when**: You need bidirectional communication\n\n## TypeScript Implementation\n\n### SSE Server\n\n```typescript\n\u002F\u002F sse-server.ts\nimport { Request, Response } from 'express';\nimport { EventEmitter } from 'events';\n\ninterface SSEClient {\n  id: string;\n  userId?: string;\n  res: Response;\n  lastEventId: number;\n}\n\nclass SSEServer {\n  private clients = new Map\u003Cstring, SSEClient>();\n  private eventId = 0;\n  private emitter = new EventEmitter();\n  private heartbeatInterval: NodeJS.Timeout;\n\n  constructor(heartbeatMs = 30000) {\n    \u002F\u002F Send heartbeats to keep connections alive\n    this.heartbeatInterval = setInterval(() => {\n      this.broadcast({ type: 'heartbeat', data: { timestamp: Date.now() } });\n    }, heartbeatMs);\n  }\n\n  connect(req: Request, res: Response, userId?: string): string {\n    const clientId = crypto.randomUUID();\n\n    \u002F\u002F Set SSE headers\n    res.setHeader('Content-Type', 'text\u002Fevent-stream');\n    res.setHeader('Cache-Control', 'no-cache');\n    res.setHeader('Connection', 'keep-alive');\n    res.setHeader('X-Accel-Buffering', 'no'); \u002F\u002F Disable nginx buffering\n    res.flushHeaders();\n\n    \u002F\u002F Get last event ID for replay\n    const lastEventId = parseInt(req.headers['last-event-id'] as string) || 0;\n\n    const client: SSEClient = {\n      id: clientId,\n      userId,\n      res,\n      lastEventId,\n    };\n\n    this.clients.set(clientId, client);\n\n    \u002F\u002F Send connection confirmation\n    this.sendToClient(client, {\n      type: 'connected',\n      data: { clientId },\n    });\n\n    \u002F\u002F Handle disconnect\n    req.on('close', () => {\n      this.clients.delete(clientId);\n      this.emitter.emit('disconnect', clientId);\n    });\n\n    this.emitter.emit('connect', clientId, userId);\n\n    return clientId;\n  }\n\n  send(clientId: string, event: SSEEvent): boolean {\n    const client = this.clients.get(clientId);\n    if (!client) return false;\n    return this.sendToClient(client, event);\n  }\n\n  sendToUser(userId: string, event: SSEEvent): number {\n    let sent = 0;\n    for (const client of this.clients.values()) {\n      if (client.userId === userId) {\n        if (this.sendToClient(client, event)) sent++;\n      }\n    }\n    return sent;\n  }\n\n  broadcast(event: SSEEvent): number {\n    let sent = 0;\n    for (const client of this.clients.values()) {\n      if (this.sendToClient(client, event)) sent++;\n    }\n    return sent;\n  }\n\n  private sendToClient(client: SSEClient, event: SSEEvent): boolean {\n    try {\n      const id = ++this.eventId;\n      const data = JSON.stringify(event.data);\n\n      let message = '';\n      if (event.type) message += `event: ${event.type}\\n`;\n      message += `id: ${id}\\n`;\n      message += `data: ${data}\\n\\n`;\n\n      client.res.write(message);\n      return true;\n    } catch {\n      \u002F\u002F Client disconnected\n      this.clients.delete(client.id);\n      return false;\n    }\n  }\n\n  getClientCount(): number {\n    return this.clients.size;\n  }\n\n  getUserClients(userId: string): string[] {\n    return Array.from(this.clients.values())\n      .filter(c => c.userId === userId)\n      .map(c => c.id);\n  }\n\n  onConnect(handler: (clientId: string, userId?: string) => void): void {\n    this.emitter.on('connect', handler);\n  }\n\n  onDisconnect(handler: (clientId: string) => void): void {\n    this.emitter.on('disconnect', handler);\n  }\n\n  close(): void {\n    clearInterval(this.heartbeatInterval);\n    for (const client of this.clients.values()) {\n      client.res.end();\n    }\n    this.clients.clear();\n  }\n}\n\ninterface SSEEvent {\n  type?: string;\n  data: unknown;\n}\n\nexport { SSEServer, SSEEvent, SSEClient };\n```\n\n### Express Routes\n\n```typescript\n\u002F\u002F sse-routes.ts\nimport { Router } from 'express';\nimport { SSEServer } from '.\u002Fsse-server';\n\nconst router = Router();\nconst sse = new SSEServer();\n\n\u002F\u002F SSE endpoint\nrouter.get('\u002Fevents', (req, res) => {\n  const userId = req.user?.id; \u002F\u002F From auth middleware\n  sse.connect(req, res, userId);\n});\n\n\u002F\u002F Send notification to specific user\nrouter.post('\u002Fnotify\u002F:userId', (req, res) => {\n  const { userId } = req.params;\n  const { type, message } = req.body;\n\n  const sent = sse.sendToUser(userId, {\n    type: 'notification',\n    data: { type, message, timestamp: Date.now() },\n  });\n\n  res.json({ sent });\n});\n\n\u002F\u002F Broadcast to all connected clients\nrouter.post('\u002Fbroadcast', (req, res) => {\n  const { type, data } = req.body;\n\n  const sent = sse.broadcast({ type, data });\n  res.json({ sent, total: sse.getClientCount() });\n});\n\nexport { router as sseRouter, sse };\n```\n\n### Progress Streaming\n\n```typescript\n\u002F\u002F progress-stream.ts\nimport { SSEServer } from '.\u002Fsse-server';\n\ninterface ProgressUpdate {\n  taskId: string;\n  progress: number; \u002F\u002F 0-100\n  status: 'pending' | 'running' | 'completed' | 'failed';\n  message?: string;\n}\n\nclass ProgressTracker {\n  constructor(private sse: SSEServer) {}\n\n  async trackTask\u003CT>(\n    taskId: string,\n    userId: string,\n    task: (update: (progress: number, message?: string) => void) => Promise\u003CT>\n  ): Promise\u003CT> {\n    const sendUpdate = (update: ProgressUpdate) => {\n      this.sse.sendToUser(userId, {\n        type: 'progress',\n        data: update,\n      });\n    };\n\n    sendUpdate({ taskId, progress: 0, status: 'running' });\n\n    try {\n      const result = await task((progress, message) => {\n        sendUpdate({ taskId, progress, status: 'running', message });\n      });\n\n      sendUpdate({ taskId, progress: 100, status: 'completed' });\n      return result;\n    } catch (error) {\n      sendUpdate({\n        taskId,\n        progress: 0,\n        status: 'failed',\n        message: error instanceof Error ? error.message : 'Unknown error',\n      });\n      throw error;\n    }\n  }\n}\n\n\u002F\u002F Usage\nconst tracker = new ProgressTracker(sse);\n\napp.post('\u002Fprocess', async (req, res) => {\n  const taskId = crypto.randomUUID();\n  const userId = req.user.id;\n\n  \u002F\u002F Return immediately with task ID\n  res.json({ taskId });\n\n  \u002F\u002F Process in background with progress updates\n  tracker.trackTask(taskId, userId, async (update) => {\n    for (let i = 0; i \u003C= 100; i += 10) {\n      await doSomeWork();\n      update(i, `Processing step ${i \u002F 10}`);\n    }\n  });\n});\n```\n\n## Python Implementation\n\n```python\n# sse_server.py\nimport asyncio\nimport json\nimport uuid\nfrom typing import Dict, Optional, AsyncGenerator, Callable\nfrom dataclasses import dataclass\nfrom fastapi import Request\nfrom fastapi.responses import StreamingResponse\n\n@dataclass\nclass SSEClient:\n    id: str\n    user_id: Optional[str]\n    queue: asyncio.Queue\n\nclass SSEServer:\n    def __init__(self, heartbeat_seconds: int = 30):\n        self.clients: Dict[str, SSEClient] = {}\n        self.event_id = 0\n        self.heartbeat_seconds = heartbeat_seconds\n        self._heartbeat_task: Optional[asyncio.Task] = None\n\n    async def start(self):\n        self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())\n\n    async def stop(self):\n        if self._heartbeat_task:\n            self._heartbeat_task.cancel()\n        for client in self.clients.values():\n            await client.queue.put(None)  # Signal disconnect\n        self.clients.clear()\n\n    async def _heartbeat_loop(self):\n        while True:\n            await asyncio.sleep(self.heartbeat_seconds)\n            await self.broadcast(\"heartbeat\", {\"timestamp\": asyncio.get_event_loop().time()})\n\n    async def connect(self, request: Request, user_id: Optional[str] = None) -> StreamingResponse:\n        client_id = str(uuid.uuid4())\n        queue: asyncio.Queue = asyncio.Queue()\n        \n        client = SSEClient(id=client_id, user_id=user_id, queue=queue)\n        self.clients[client_id] = client\n\n        async def event_generator() -> AsyncGenerator[str, None]:\n            # Send connection event\n            yield self._format_event(\"connected\", {\"clientId\": client_id})\n            \n            try:\n                while True:\n                    event = await queue.get()\n                    if event is None:  # Disconnect signal\n                        break\n                    yield event\n            finally:\n                self.clients.pop(client_id, None)\n\n        return StreamingResponse(\n            event_generator(),\n            media_type=\"text\u002Fevent-stream\",\n            headers={\n                \"Cache-Control\": \"no-cache\",\n                \"Connection\": \"keep-alive\",\n                \"X-Accel-Buffering\": \"no\",\n            },\n        )\n\n    def _format_event(self, event_type: str, data: dict) -> str:\n        self.event_id += 1\n        return f\"event: {event_type}\\nid: {self.event_id}\\ndata: {json.dumps(data)}\\n\\n\"\n\n    async def send(self, client_id: str, event_type: str, data: dict) -> bool:\n        client = self.clients.get(client_id)\n        if not client:\n            return False\n        await client.queue.put(self._format_event(event_type, data))\n        return True\n\n    async def send_to_user(self, user_id: str, event_type: str, data: dict) -> int:\n        sent = 0\n        for client in self.clients.values():\n            if client.user_id == user_id:\n                await client.queue.put(self._format_event(event_type, data))\n                sent += 1\n        return sent\n\n    async def broadcast(self, event_type: str, data: dict) -> int:\n        event = self._format_event(event_type, data)\n        for client in self.clients.values():\n            await client.queue.put(event)\n        return len(self.clients)\n```\n\n### FastAPI Routes\n\n```python\n# sse_routes.py\nfrom fastapi import APIRouter, Request, Depends\nfrom .sse_server import SSEServer\n\nrouter = APIRouter()\nsse = SSEServer()\n\n@router.on_event(\"startup\")\nasync def startup():\n    await sse.start()\n\n@router.on_event(\"shutdown\")\nasync def shutdown():\n    await sse.stop()\n\n@router.get(\"\u002Fevents\")\nasync def events(request: Request, user_id: str = Depends(get_current_user_id)):\n    return await sse.connect(request, user_id)\n\n@router.post(\"\u002Fnotify\u002F{user_id}\")\nasync def notify(user_id: str, event_type: str, message: str):\n    sent = await sse.send_to_user(user_id, \"notification\", {\n        \"type\": event_type,\n        \"message\": message,\n    })\n    return {\"sent\": sent}\n```\n\n## Frontend Client\n\n```typescript\n\u002F\u002F sse-client.ts\ninterface SSEClientOptions {\n  url: string;\n  onMessage?: (event: MessageEvent) => void;\n  onError?: (error: Event) => void;\n  onOpen?: () => void;\n  reconnectDelay?: number;\n  maxRetries?: number;\n}\n\nclass SSEClient {\n  private eventSource: EventSource | null = null;\n  private retries = 0;\n  private handlers = new Map\u003Cstring, Set\u003C(data: unknown) => void>>();\n\n  constructor(private options: SSEClientOptions) {}\n\n  connect(): void {\n    if (this.eventSource) {\n      this.eventSource.close();\n    }\n\n    this.eventSource = new EventSource(this.options.url);\n\n    this.eventSource.onopen = () => {\n      this.retries = 0;\n      this.options.onOpen?.();\n    };\n\n    this.eventSource.onerror = (error) => {\n      this.options.onError?.(error);\n      this.handleReconnect();\n    };\n\n    this.eventSource.onmessage = (event) => {\n      this.options.onMessage?.(event);\n    };\n\n    \u002F\u002F Register typed event handlers\n    for (const [type, handlers] of this.handlers) {\n      this.eventSource.addEventListener(type, (event: MessageEvent) => {\n        const data = JSON.parse(event.data);\n        handlers.forEach(handler => handler(data));\n      });\n    }\n  }\n\n  on\u003CT>(eventType: string, handler: (data: T) => void): () => void {\n    if (!this.handlers.has(eventType)) {\n      this.handlers.set(eventType, new Set());\n      \n      \u002F\u002F Add listener if already connected\n      if (this.eventSource) {\n        this.eventSource.addEventListener(eventType, (event: MessageEvent) => {\n          const data = JSON.parse(event.data);\n          this.handlers.get(eventType)?.forEach(h => h(data));\n        });\n      }\n    }\n\n    this.handlers.get(eventType)!.add(handler);\n\n    \u002F\u002F Return unsubscribe function\n    return () => {\n      this.handlers.get(eventType)?.delete(handler);\n    };\n  }\n\n  private handleReconnect(): void {\n    const maxRetries = this.options.maxRetries ?? 10;\n    const delay = this.options.reconnectDelay ?? 1000;\n\n    if (this.retries >= maxRetries) {\n      console.error('SSE: Max retries reached');\n      return;\n    }\n\n    this.retries++;\n    const backoff = delay * Math.pow(2, this.retries - 1);\n    \n    console.log(`SSE: Reconnecting in ${backoff}ms (attempt ${this.retries})`);\n    setTimeout(() => this.connect(), backoff);\n  }\n\n  disconnect(): void {\n    if (this.eventSource) {\n      this.eventSource.close();\n      this.eventSource = null;\n    }\n  }\n}\n\n\u002F\u002F Usage\nconst sse = new SSEClient({ url: '\u002Fapi\u002Fevents' });\n\nsse.on\u003C{ type: string; message: string }>('notification', (data) => {\n  showNotification(data.type, data.message);\n});\n\nsse.on\u003C{ taskId: string; progress: number }>('progress', (data) => {\n  updateProgressBar(data.taskId, data.progress);\n});\n\nsse.connect();\n```\n\n## React Hook\n\n```typescript\n\u002F\u002F useSSE.ts\nimport { useEffect, useRef, useCallback } from 'react';\n\nfunction useSSE(url: string) {\n  const eventSourceRef = useRef\u003CEventSource | null>(null);\n  const handlersRef = useRef\u003CMap\u003Cstring, (data: unknown) => void>>(new Map());\n\n  useEffect(() => {\n    const eventSource = new EventSource(url);\n    eventSourceRef.current = eventSource;\n\n    eventSource.onerror = () => {\n      \u002F\u002F Browser handles reconnection automatically\n      console.log('SSE connection error, reconnecting...');\n    };\n\n    return () => {\n      eventSource.close();\n    };\n  }, [url]);\n\n  const subscribe = useCallback(\u003CT>(\n    eventType: string,\n    handler: (data: T) => void\n  ) => {\n    const eventSource = eventSourceRef.current;\n    if (!eventSource) return () => {};\n\n    const wrappedHandler = (event: MessageEvent) => {\n      handler(JSON.parse(event.data));\n    };\n\n    eventSource.addEventListener(eventType, wrappedHandler);\n\n    return () => {\n      eventSource.removeEventListener(eventType, wrappedHandler);\n    };\n  }, []);\n\n  return { subscribe };\n}\n\n\u002F\u002F Usage in component\nfunction Dashboard() {\n  const { subscribe } = useSSE('\u002Fapi\u002Fevents');\n  const [notifications, setNotifications] = useState([]);\n\n  useEffect(() => {\n    return subscribe('notification', (data) => {\n      setNotifications(prev => [...prev, data]);\n    });\n  }, [subscribe]);\n\n  return \u003CNotificationList items={notifications} \u002F>;\n}\n```\n\n## Best Practices\n\n1. **Send heartbeats**: Keep connections alive through proxies\n2. **Use event IDs**: Enable automatic replay on reconnect\n3. **Disable buffering**: Set `X-Accel-Buffering: no` for nginx\n4. **Handle reconnection**: Browser does it automatically, but add backoff\n5. **Clean up on disconnect**: Remove clients from memory\n\n## Common Mistakes\n\n- Not disabling proxy buffering (events arrive in batches)\n- Not sending heartbeats (connections timeout)\n- Not handling client disconnects (memory leak)\n- Using SSE for bidirectional communication (use WebSocket)\n- Not using event IDs (lose events on reconnect)\n","# Server-Sent Events (SSE)\n\nReal-time server-to-client streaming with automatic reconnection.\n\n## When to Use This Skill\n\n- Live dashboards and monitoring\n- Real-time notifications\n- Progress indicators for long operations\n- Live feeds (activity, chat, updates)\n- AI streaming responses\n\n## SSE vs WebSockets\n\n| Feature | SSE | WebSocket |\n|---------|-----|-----------|\n| Direction | Server → Client | Bidirectional |\n| Protocol | HTTP | WS |\n| Reconnection | Automatic | Manual |\n| Complexity | Simple | Complex |\n| Browser Support | Native | Native |\n| Through Proxies | Easy | Can be tricky |\n\n**Use SSE when**: You only need server-to-client push\n**Use WebSocket when**: You need bidirectional communication\n\n## TypeScript Implementation\n\n### SSE Server\n\n```typescript\n\u002F\u002F sse-server.ts\nimport { Request, Response } from 'express';\nimport { EventEmitter } from 'events';\n\ninterface SSEClient {\n  id: string;\n  userId?: string;\n  res: Response;\n  lastEventId: number;\n}\n\nclass SSEServer {\n  private clients = new Map\u003Cstring, SSEClient>();\n  private eventId = 0;\n  private emitter = new EventEmitter();\n  private heartbeatInterval: NodeJS.Timeout;\n\n  constructor(heartbeatMs = 30000) {\n    \u002F\u002F Send heartbeats to keep connections alive\n    this.heartbeatInterval = setInterval(() => {\n      this.broadcast({ type: 'heartbeat', data: { timestamp: Date.now() } });\n    }, heartbeatMs);\n  }\n\n  connect(req: Request, res: Response, userId?: string): string {\n    const clientId = crypto.randomUUID();\n\n    \u002F\u002F Set SSE headers\n    res.setHeader('Content-Type', 'text\u002Fevent-stream');\n    res.setHeader('Cache-Control', 'no-cache');\n    res.setHeader('Connection', 'keep-alive');\n    res.setHeader('X-Accel-Buffering', 'no'); \u002F\u002F Disable nginx buffering\n    res.flushHeaders();\n\n    \u002F\u002F Get last event ID for replay\n    const lastEventId = parseInt(req.headers['last-event-id'] as string) || 0;\n\n    const client: SSEClient = {\n      id: clientId,\n      userId,\n      res,\n      lastEventId,\n    };\n\n    this.clients.set(clientId, client);\n\n    \u002F\u002F Send connection confirmation\n    this.sendToClient(client, {\n      type: 'connected',\n      data: { clientId },\n    });\n\n    \u002F\u002F Handle disconnect\n    req.on('close', () => {\n      this.clients.delete(clientId);\n      this.emitter.emit('disconnect', clientId);\n    });\n\n    this.emitter.emit('connect', clientId, userId);\n\n    return clientId;\n  }\n\n  send(clientId: string, event: SSEEvent): boolean {\n    const client = this.clients.get(clientId);\n    if (!client) return false;\n    return this.sendToClient(client, event);\n  }\n\n  sendToUser(userId: string, event: SSEEvent): number {\n    let sent = 0;\n    for (const client of this.clients.values()) {\n      if (client.userId === userId) {\n        if (this.sendToClient(client, event)) sent++;\n      }\n    }\n    return sent;\n  }\n\n  broadcast(event: SSEEvent): number {\n    let sent = 0;\n    for (const client of this.clients.values()) {\n      if (this.sendToClient(client, event)) sent++;\n    }\n    return sent;\n  }\n\n  private sendToClient(client: SSEClient, event: SSEEvent): boolean {\n    try {\n      const id = ++this.eventId;\n      const data = JSON.stringify(event.data);\n\n      let message = '';\n      if (event.type) message += `event: ${event.type}\\n`;\n      message += `id: ${id}\\n`;\n      message += `data: ${data}\\n\\n`;\n\n      client.res.write(message);\n      return true;\n    } catch {\n      \u002F\u002F Client disconnected\n      this.clients.delete(client.id);\n      return false;\n    }\n  }\n\n  getClientCount(): number {\n    return this.clients.size;\n  }\n\n  getUserClients(userId: string): string[] {\n    return Array.from(this.clients.values())\n      .filter(c => c.userId === userId)\n      .map(c => c.id);\n  }\n\n  onConnect(handler: (clientId: string, userId?: string) => void): void {\n    this.emitter.on('connect', handler);\n  }\n\n  onDisconnect(handler: (clientId: string) => void): void {\n    this.emitter.on('disconnect', handler);\n  }\n\n  close(): void {\n    clearInterval(this.heartbeatInterval);\n    for (const client of this.clients.values()) {\n      client.res.end();\n    }\n    this.clients.clear();\n  }\n}\n\ninterface SSEEvent {\n  type?: string;\n  data: unknown;\n}\n\nexport { SSEServer, SSEEvent, SSEClient };\n```\n\n### Express Routes\n\n```typescript\n\u002F\u002F sse-routes.ts\nimport { Router } from 'express';\nimport { SSEServer } from '.\u002Fsse-server';\n\nconst router = Router();\nconst sse = new SSEServer();\n\n\u002F\u002F SSE endpoint\nrouter.get('\u002Fevents', (req, res) => {\n  const userId = req.user?.id; \u002F\u002F From auth middleware\n  sse.connect(req, res, userId);\n});\n\n\u002F\u002F Send notification to specific user\nrouter.post('\u002Fnotify\u002F:userId', (req, res) => {\n  const { userId } = req.params;\n  const { type, message } = req.body;\n\n  const sent = sse.sendToUser(userId, {\n    type: 'notification',\n    data: { type, message, timestamp: Date.now() },\n  });\n\n  res.json({ sent });\n});\n\n\u002F\u002F Broadcast to all connected clients\nrouter.post('\u002Fbroadcast', (req, res) => {\n  const { type, data } = req.body;\n\n  const sent = sse.broadcast({ type, data });\n  res.json({ sent, total: sse.getClientCount() });\n});\n\nexport { router as sseRouter, sse };\n```\n\n### Progress Streaming\n\n```typescript\n\u002F\u002F progress-stream.ts\nimport { SSEServer } from '.\u002Fsse-server';\n\ninterface ProgressUpdate {\n  taskId: string;\n  progress: number; \u002F\u002F 0-100\n  status: 'pending' | 'running' | 'completed' | 'failed';\n  message?: string;\n}\n\nclass ProgressTracker {\n  constructor(private sse: SSEServer) {}\n\n  async trackTask\u003CT>(\n    taskId: string,\n    userId: string,\n    task: (update: (progress: number, message?: string) => void) => Promise\u003CT>\n  ): Promise\u003CT> {\n    const sendUpdate = (update: ProgressUpdate) => {\n      this.sse.sendToUser(userId, {\n        type: 'progress',\n        data: update,\n      });\n    };\n\n    sendUpdate({ taskId, progress: 0, status: 'running' });\n\n    try {\n      const result = await task((progress, message) => {\n        sendUpdate({ taskId, progress, status: 'running', message });\n      });\n\n      sendUpdate({ taskId, progress: 100, status: 'completed' });\n      return result;\n    } catch (error) {\n      sendUpdate({\n        taskId,\n        progress: 0,\n        status: 'failed',\n        message: error instanceof Error ? error.message : 'Unknown error',\n      });\n      throw error;\n    }\n  }\n}\n\n\u002F\u002F Usage\nconst tracker = new ProgressTracker(sse);\n\napp.post('\u002Fprocess', async (req, res) => {\n  const taskId = crypto.randomUUID();\n  const userId = req.user.id;\n\n  \u002F\u002F Return immediately with task ID\n  res.json({ taskId });\n\n  \u002F\u002F Process in background with progress updates\n  tracker.trackTask(taskId, userId, async (update) => {\n    for (let i = 0; i \u003C= 100; i += 10) {\n      await doSomeWork();\n      update(i, `Processing step ${i \u002F 10}`);\n    }\n  });\n});\n```\n\n## Python Implementation\n\n```python\n# sse_server.py\nimport asyncio\nimport json\nimport uuid\nfrom typing import Dict, Optional, AsyncGenerator, Callable\nfrom dataclasses import dataclass\nfrom fastapi import Request\nfrom fastapi.responses import StreamingResponse\n\n@dataclass\nclass SSEClient:\n    id: str\n    user_id: Optional[str]\n    queue: asyncio.Queue\n\nclass SSEServer:\n    def __init__(self, heartbeat_seconds: int = 30):\n        self.clients: Dict[str, SSEClient] = {}\n        self.event_id = 0\n        self.heartbeat_seconds = heartbeat_seconds\n        self._heartbeat_task: Optional[asyncio.Task] = None\n\n    async def start(self):\n        self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())\n\n    async def stop(self):\n        if self._heartbeat_task:\n            self._heartbeat_task.cancel()\n        for client in self.clients.values():\n            await client.queue.put(None)  # Signal disconnect\n        self.clients.clear()\n\n    async def _heartbeat_loop(self):\n        while True:\n            await asyncio.sleep(self.heartbeat_seconds)\n            await self.broadcast(\"heartbeat\", {\"timestamp\": asyncio.get_event_loop().time()})\n\n    async def connect(self, request: Request, user_id: Optional[str] = None) -> StreamingResponse:\n        client_id = str(uuid.uuid4())\n        queue: asyncio.Queue = asyncio.Queue()\n        \n        client = SSEClient(id=client_id, user_id=user_id, queue=queue)\n        self.clients[client_id] = client\n\n        async def event_generator() -> AsyncGenerator[str, None]:\n            # Send connection event\n            yield self._format_event(\"connected\", {\"clientId\": client_id})\n            \n            try:\n                while True:\n                    event = await queue.get()\n                    if event is None:  # Disconnect signal\n                        break\n                    yield event\n            finally:\n                self.clients.pop(client_id, None)\n\n        return StreamingResponse(\n            event_generator(),\n            media_type=\"text\u002Fevent-stream\",\n            headers={\n                \"Cache-Control\": \"no-cache\",\n                \"Connection\": \"keep-alive\",\n                \"X-Accel-Buffering\": \"no\",\n            },\n        )\n\n    def _format_event(self, event_type: str, data: dict) -> str:\n        self.event_id += 1\n        return f\"event: {event_type}\\nid: {self.event_id}\\ndata: {json.dumps(data)}\\n\\n\"\n\n    async def send(self, client_id: str, event_type: str, data: dict) -> bool:\n        client = self.clients.get(client_id)\n        if not client:\n            return False\n        await client.queue.put(self._format_event(event_type, data))\n        return True\n\n    async def send_to_user(self, user_id: str, event_type: str, data: dict) -> int:\n        sent = 0\n        for client in self.clients.values():\n            if client.user_id == user_id:\n                await client.queue.put(self._format_event(event_type, data))\n                sent += 1\n        return sent\n\n    async def broadcast(self, event_type: str, data: dict) -> int:\n        event = self._format_event(event_type, data)\n        for client in self.clients.values():\n            await client.queue.put(event)\n        return len(self.clients)\n```\n\n### FastAPI Routes\n\n```python\n# sse_routes.py\nfrom fastapi import APIRouter, Request, Depends\nfrom .sse_server import SSEServer\n\nrouter = APIRouter()\nsse = SSEServer()\n\n@router.on_event(\"startup\")\nasync def startup():\n    await sse.start()\n\n@router.on_event(\"shutdown\")\nasync def shutdown():\n    await sse.stop()\n\n@router.get(\"\u002Fevents\")\nasync def events(request: Request, user_id: str = Depends(get_current_user_id)):\n    return await sse.connect(request, user_id)\n\n@router.post(\"\u002Fnotify\u002F{user_id}\")\nasync def notify(user_id: str, event_type: str, message: str):\n    sent = await sse.send_to_user(user_id, \"notification\", {\n        \"type\": event_type,\n        \"message\": message,\n    })\n    return {\"sent\": sent}\n```\n\n## Frontend Client\n\n```typescript\n\u002F\u002F sse-client.ts\ninterface SSEClientOptions {\n  url: string;\n  onMessage?: (event: MessageEvent) => void;\n  onError?: (error: Event) => void;\n  onOpen?: () => void;\n  reconnectDelay?: number;\n  maxRetries?: number;\n}\n\nclass SSEClient {\n  private eventSource: EventSource | null = null;\n  private retries = 0;\n  private handlers = new Map\u003Cstring, Set\u003C(data: unknown) => void>>();\n\n  constructor(private options: SSEClientOptions) {}\n\n  connect(): void {\n    if (this.eventSource) {\n      this.eventSource.close();\n    }\n\n    this.eventSource = new EventSource(this.options.url);\n\n    this.eventSource.onopen = () => {\n      this.retries = 0;\n      this.options.onOpen?.();\n    };\n\n    this.eventSource.onerror = (error) => {\n      this.options.onError?.(error);\n      this.handleReconnect();\n    };\n\n    this.eventSource.onmessage = (event) => {\n      this.options.onMessage?.(event);\n    };\n\n    \u002F\u002F Register typed event handlers\n    for (const [type, handlers] of this.handlers) {\n      this.eventSource.addEventListener(type, (event: MessageEvent) => {\n        const data = JSON.parse(event.data);\n        handlers.forEach(handler => handler(data));\n      });\n    }\n  }\n\n  on\u003CT>(eventType: string, handler: (data: T) => void): () => void {\n    if (!this.handlers.has(eventType)) {\n      this.handlers.set(eventType, new Set());\n      \n      \u002F\u002F Add listener if already connected\n      if (this.eventSource) {\n        this.eventSource.addEventListener(eventType, (event: MessageEvent) => {\n          const data = JSON.parse(event.data);\n          this.handlers.get(eventType)?.forEach(h => h(data));\n        });\n      }\n    }\n\n    this.handlers.get(eventType)!.add(handler);\n\n    \u002F\u002F Return unsubscribe function\n    return () => {\n      this.handlers.get(eventType)?.delete(handler);\n    };\n  }\n\n  private handleReconnect(): void {\n    const maxRetries = this.options.maxRetries ?? 10;\n    const delay = this.options.reconnectDelay ?? 1000;\n\n    if (this.retries >= maxRetries) {\n      console.error('SSE: Max retries reached');\n      return;\n    }\n\n    this.retries++;\n    const backoff = delay * Math.pow(2, this.retries - 1);\n    \n    console.log(`SSE: Reconnecting in ${backoff}ms (attempt ${this.retries})`);\n    setTimeout(() => this.connect(), backoff);\n  }\n\n  disconnect(): void {\n    if (this.eventSource) {\n      this.eventSource.close();\n      this.eventSource = null;\n    }\n  }\n}\n\n\u002F\u002F Usage\nconst sse = new SSEClient({ url: '\u002Fapi\u002Fevents' });\n\nsse.on\u003C{ type: string; message: string }>('notification', (data) => {\n  showNotification(data.type, data.message);\n});\n\nsse.on\u003C{ taskId: string; progress: number }>('progress', (data) => {\n  updateProgressBar(data.taskId, data.progress);\n});\n\nsse.connect();\n```\n\n## React Hook\n\n```typescript\n\u002F\u002F useSSE.ts\nimport { useEffect, useRef, useCallback } from 'react';\n\nfunction useSSE(url: string) {\n  const eventSourceRef = useRef\u003CEventSource | null>(null);\n  const handlersRef = useRef\u003CMap\u003Cstring, (data: unknown) => void>>(new Map());\n\n  useEffect(() => {\n    const eventSource = new EventSource(url);\n    eventSourceRef.current = eventSource;\n\n    eventSource.onerror = () => {\n      \u002F\u002F Browser handles reconnection automatically\n      console.log('SSE connection error, reconnecting...');\n    };\n\n    return () => {\n      eventSource.close();\n    };\n  }, [url]);\n\n  const subscribe = useCallback(\u003CT>(\n    eventType: string,\n    handler: (data: T) => void\n  ) => {\n    const eventSource = eventSourceRef.current;\n    if (!eventSource) return () => {};\n\n    const wrappedHandler = (event: MessageEvent) => {\n      handler(JSON.parse(event.data));\n    };\n\n    eventSource.addEventListener(eventType, wrappedHandler);\n\n    return () => {\n      eventSource.removeEventListener(eventType, wrappedHandler);\n    };\n  }, []);\n\n  return { subscribe };\n}\n\n\u002F\u002F Usage in component\nfunction Dashboard() {\n  const { subscribe } = useSSE('\u002Fapi\u002Fevents');\n  const [notifications, setNotifications] = useState([]);\n\n  useEffect(() => {\n    return subscribe('notification', (data) => {\n      setNotifications(prev => [...prev, data]);\n    });\n  }, [subscribe]);\n\n  return \u003CNotificationList items={notifications} \u002F>;\n}\n```\n\n## Best Practices\n\n1. **Send heartbeats**: Keep connections alive through proxies\n2. **Use event IDs**: Enable automatic replay on reconnect\n3. **Disable buffering**: Set `X-Accel-Buffering: no` for nginx\n4. **Handle reconnection**: Browser does it automatically, but add backoff\n5. **Clean up on disconnect**: Remove clients from memory\n\n## Common Mistakes\n\n- Not disabling proxy buffering (events arrive in batches)\n- Not sending heartbeats (connections timeout)\n- Not handling client disconnects (memory leak)\n- Using SSE for bidirectional communication (use WebSocket)\n- Not using event IDs (lose events on reconnect)\n",{"name":5,"license":15,"metadata":44,"description":7,"compatibility":47},{"time":45,"source":46,"category":31},"3h","drift-masterguide","TypeScript\u002FJavaScript, Python","main","1ca81b0a7de199942400f965edd4d7544077ac5d",".claude\u002Fskills\u002Fsse-streaming","https:\u002F\u002Fgithub.com\u002FCoralShades\u002Facm-ai","https:\u002F\u002Fgithub.com\u002FCoralShades","coralshades.com.au","2026-04-18 00:45:07",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add CoralShades\u002Facm-ai --skill sse-streaming",{"tool":61,"command":62},"bunx","bunx skills add CoralShades\u002Facm-ai --skill sse-streaming",{"tool":64,"command":65},"pnpm","pnpm dlx skills add CoralShades\u002Facm-ai --skill sse-streaming","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FCoralShades\u002Facm-ai\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsse-streaming\u002FSKILL.md",true,[69],{"path":70,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":73,"sourceHtmlUrl":74},"README.md","REFERENCE","参考文档",3932,"https:\u002F\u002Fgithub.com\u002Fdmlguq456\u002Fhearting\u002Fblob\u002Fmain\u002Fadapters\u002Fclaude\u002Fskills\u002Fcode-plan\u002FREADME.md",[76,95,108,124,146,155],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":83,"publishedAt":39},"01M6C63HKXA890HHV47WBAX0TB","uncodixfy","Prevents generic AI\u002FCodex UI patterns when generating frontend code. Use this skill whenever generating HTML, CSS, React, Vue, Svelte, or any frontend UI code to enforce clean, human-designed aesthetics inspired by Linear, Raycast, Stripe, and GitHub instead of typical AI-generated UI.","https:\u002F\u002Fgithub.com\u002FCoralShades\u002Facm-ai\u002Fblob\u002Fmain\u002F.qwen\u002Fskills\u002Funcodixfy\u002FSKILL.md",[82],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[78,84,85,86,87,88,89,90,91,92,93,38,94],"github","frontend","css","codex","react","code","linear","ui","vue","generated","html",{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":99,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":39},"01M6C63FJ2GEBBGZ5XSMV40KXB","runpodctl","Runpod CLI to manage your GPU workloads.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FCoralShades\u002Facm-ai\u002Fblob\u002Fmain\u002F.qwen\u002Fskills\u002Frunpodctl\u002FSKILL.md",[],[97,103,104,105,106,107],"macos","cli","linux","gpu","Bash",{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":39},"01M6C63DPAV46TFVQ01SFYPJ7X","langgraph-persistence","INVOKE THIS SKILL when your LangGraph needs to persist state, remember conversations, travel through history, or configure subgraph checkpointer scoping. Covers checkpointers, thread_id, time travel, Store, and subgraph persistence modes.","https:\u002F\u002Fgithub.com\u002FCoralShades\u002Facm-ai\u002Fblob\u002Fmain\u002F.qwen\u002Fskills\u002Flanggraph-persistence\u002FSKILL.md",[],[115,116,117,118,119,120,121,122,123],"langgraph persistence","langgraph","persistence","travel","history","scoping","remember","state","configure",{"skillNo":125,"name":126,"nameZh":6,"description":127,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":128,"categories":129,"keywords":135,"publishedAt":39},"01M6C63BNS9CQEBTB8RNSSBFPA","langgraph-human-in-the-loop","INVOKE THIS SKILL when implementing human-in-the-loop patterns, pausing for approval, or handling errors in LangGraph. Covers interrupt(), Command(resume=...), approval\u002Fvalidation workflows, and the 4-tier error handling strategy.","https:\u002F\u002Fgithub.com\u002FCoralShades\u002Facm-ai\u002Fblob\u002Fmain\u002F.qwen\u002Fskills\u002Flanggraph-human-in-the-loop\u002FSKILL.md",[130],{"categoryNo":131,"categoryName":132,"taxonomyType":133,"taxonomyTypeDesc":134},"01JBSEEDCAT000000000000038","人力资源","PROFESSION","适用职业",[136,137,116,138,139,140,141,142,143,144,145],"langgraph human in the loop","loop","workflows","error handling","validation","human-in-the-loop","command","strategy","approval","resume",{"skillNo":147,"name":148,"nameZh":6,"description":149,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":150,"categories":151,"keywords":152,"publishedAt":39},"01M6C639GVYZFX3NFPV5FBDR4F","langgraph-fundamentals","INVOKE THIS SKILL when writing ANY LangGraph code. Covers StateGraph, state schemas, nodes, edges, Command, Send, invoke, streaming, and error handling.","https:\u002F\u002Fgithub.com\u002FCoralShades\u002Facm-ai\u002Fblob\u002Fmain\u002F.qwen\u002Fskills\u002Flanggraph-fundamentals\u002FSKILL.md",[],[153,116,139,122,24,154,142,89],"langgraph fundamentals","writing",{"skillNo":156,"name":157,"nameZh":6,"description":158,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":159,"categories":160,"keywords":161,"publishedAt":39},"01M6C6375N34YX2GZ3SD3R7XR2","langchain-rag","INVOKE THIS SKILL when building ANY retrieval-augmented generation (RAG) system. Covers document loaders, RecursiveCharacterTextSplitter, embeddings (OpenAI), and vector stores (Chroma, FAISS, Pinecone).","https:\u002F\u002Fgithub.com\u002FCoralShades\u002Facm-ai\u002Fblob\u002Fmain\u002F.qwen\u002Fskills\u002Flangchain-rag\u002FSKILL.md",[],[162,163,164,165,166,167,168,169,170,171],"rag","langchain rag","langchain","embeddings","vector","openai","chroma","faiss","vector stores","system"]