| 1 | import { useState, useEffect, useCallback, useRef } from "react"; |
| 2 | |
| 3 | export interface EventSession { |
| 4 | id: string; |
| 5 | filename: string; |
| 6 | event_count: number; |
| 7 | size_bytes: number; |
| 8 | modified: string; |
| 9 | last_turn_id: string; |
| 10 | last_session_key: string; |
| 11 | } |
| 12 | |
| 13 | export interface EventRecord { |
| 14 | seq: number; |
| 15 | type: string; |
| 16 | turn_id: string; |
| 17 | timestamp: string; |
| 18 | session_key: string; |
| 19 | data: Record<string, any>; |
| 20 | } |
| 21 | |
| 22 | export function useEventStack() { |
| 23 | const [sessions, setSessions] = useState<EventSession[]>([]); |
| 24 | const [activeSession, setActiveSession] = useState<string | null>(null); |
| 25 | const [events, setEvents] = useState<EventRecord[]>([]); |
| 26 | const [loading, setLoading] = useState(false); |
| 27 | const fetchIdRef = useRef(0); |
| 28 | |
| 29 | const fetchSessions = useCallback(async () => { |
| 30 | try { |
| 31 | const res = await fetch("/api/eventstack/sessions"); |
| 32 | if (res.ok) setSessions(await res.json()); |
| 33 | } catch (e) { |
| 34 | console.error("Failed to fetch eventstack sessions", e); |
| 35 | } |
| 36 | }, []); |
| 37 | |
| 38 | const fetchEvents = useCallback(async (sessionId: string) => { |
| 39 | const thisId = ++fetchIdRef.current; |
| 40 | setLoading(true); |
| 41 | try { |
| 42 | const res = await fetch(`/api/eventstack/traces/${sessionId}`); |
| 43 | if (!res.ok) return; |
| 44 | const data = await res.json(); |
| 45 | if (fetchIdRef.current === thisId) setEvents(data); |
| 46 | } catch (e) { |
| 47 | console.error("Failed to fetch events", e); |
| 48 | } finally { |
| 49 | if (fetchIdRef.current === thisId) setLoading(false); |
| 50 | } |
| 51 | }, []); |
| 52 | |
| 53 | const switchSession = useCallback((id: string | null) => { |
| 54 | setActiveSession((prev) => { |
| 55 | if (prev !== id) setEvents([]); |
| 56 | return id; |
| 57 | }); |
| 58 | }, []); |
| 59 | |
| 60 | useEffect(() => { |
| 61 | fetchSessions(); |
| 62 | }, [fetchSessions]); |
| 63 | |
| 64 | useEffect(() => { |
| 65 | if (activeSession) { |
| 66 | fetchEvents(activeSession); |
| 67 | } else { |
| 68 | fetchIdRef.current++; |
| 69 | setEvents([]); |
| 70 | setLoading(false); |
| 71 | } |
| 72 | }, [activeSession, fetchEvents]); |
| 73 | |
| 74 | return { |
| 75 | sessions, |
| 76 | activeSession, |
| 77 | setActiveSession: switchSession, |
| 78 | events, |
| 79 | loading, |
| 80 | refresh: useCallback(async () => { |
| 81 | await fetchSessions(); |
| 82 | if (activeSession) fetchEvents(activeSession); |
| 83 | }, [fetchSessions, fetchEvents, activeSession]), |
| 84 | }; |
| 85 | } |
| 86 |