Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

useReportSSE.ts

104 lines2.7 KB

1'use client'
2​
3import { useEffect, useRef, useCallback } from 'react'
4import type { RefreshResult, UIEffect, UIUpdate } from '@/lib/reports/types'
5​
6interface SSEMessage {
7 type: 'connected' | 'ping' | 'refresh' | 'effects'
8 reportId?: string
9 results?: RefreshResult[]
10 effects?: UIEffect[]
12​
13interface UseReportSSEOptions {
14 reportId: string | null
15 onRefresh: (results: RefreshResult[]) => void
16 onEffects?: (effects: UIEffect[]) => void
17 enabled?: boolean
19​
20/**
21 * Hook to connect to SSE endpoint for receiving push updates.
22 * Automatically reconnects on disconnect.
23 */
24export function useReportSSE({
25 reportId,
26 onRefresh,
27 onEffects,
28 enabled = true,
29}: UseReportSSEOptions) {
30 const eventSourceRef = useRef<EventSource | null>(null)
31 const reconnectTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
32​
33 const connect = useCallback(() => {
34 if (!reportId || !enabled) return
35​
36 // Clean up existing connection
37 if (eventSourceRef.current) {
38 eventSourceRef.current.close()
39 eventSourceRef.current = null
40 }
41​
42 const eventSource = new EventSource(`/api/report-sse?reportId=${reportId}`)
43 eventSourceRef.current = eventSource
44​
45 eventSource.onmessage = (event) => {
46 try {
47 const data: SSEMessage = JSON.parse(event.data)
48​
49 if (data.type === 'refresh' && data.results) {
50 onRefresh(data.results)
51 }
52​
53 if (data.type === 'effects' && data.effects && onEffects) {
54 onEffects(data.effects)
55 }
56 // 'connected' and 'ping' messages are handled silently
57 } catch {
58 console.error('[useReportSSE] Failed to parse message:', event.data)
59 }
60 }
61​
62 eventSource.onerror = () => {
63 // Close the connection and schedule reconnect
64 eventSource.close()
65 eventSourceRef.current = null
66​
67 // Reconnect after 3 seconds
68 reconnectTimeoutRef.current = setTimeout(() => {
69 connect()
70 }, 3000)
71 }
72 }, [reportId, enabled, onRefresh, onEffects])
73​
74 useEffect(() => {
75 connect()
76​
77 return () => {
78 // Clean up on unmount
79 if (eventSourceRef.current) {
80 eventSourceRef.current.close()
81 eventSourceRef.current = null
82 }
83 if (reconnectTimeoutRef.current) {
84 clearTimeout(reconnectTimeoutRef.current)
85 reconnectTimeoutRef.current = null
86 }
87 }
88 }, [connect])
90​
91/**
92 * Helper to convert refresh results to UI updates for use with applyUIUpdates.
93 */
94export function refreshResultsToUIUpdates(
95 results: RefreshResult[],
96): UIUpdate[] {
97 return results
98 .filter((r) => r.success && r.props)
99 .map((r) => ({
100 type: 'update' as const,
101 componentId: r.componentId,
102 props: r.props,
103 }))