import { useState, useEffect, useCallback, useRef } from "preact/hooks"; import type { ThreadData } from "./types"; export function useThreads(pollMs = 3000, windowMs = 24 * 60 * 60 * 1000) { const [threads, setThreads] = useState([]); const prevStatuses = useRef>({}); const refresh = useCallback(async () => { try { const since = Date.now() - windowMs; const r = await fetch(`/code/api/threads?since=${since}&t=${Date.now()}`); if (!r.ok) return; const data = await r.json(); const sorted: ThreadData[] = (data.threads || []).sort((a: ThreadData, b: ThreadData) => a.startedAt - b.startedAt); const prev = prevStatuses.current; const isFirstLoad = Object.keys(prev).length === 0; for (const t of sorted) { const key = `${t.channel}:${t.threadId}`; const wasActive = prev[key] === "processing" || prev[key] === "stalled"; if (!isFirstLoad && wasActive && t.status === "replied") { window.dispatchEvent(new CustomEvent("threadReplied", { detail: { threadId: t.threadId } })); } prev[key] = t.status; } setThreads(sorted); } catch {} }, [windowMs]); useEffect(() => { refresh(); const id = setInterval(refresh, pollMs); return () => clearInterval(id); }, [pollMs, windowMs, refresh]); return { threads, refresh }; }