import { useQuery } from "@tanstack/react-query"; import { getDreamTask } from "@/services/memory"; import { queryKeys } from "@/lib/query-keys"; import { useRuntimeContext } from "@/providers/runtime-context-provider"; import { DREAM_TERMINAL_STATUSES, type DreamTaskSummary } from "@/types/memory"; const POLL_INTERVAL_MS = 5_000; /** * Watch a single dream task. Polls every 5s while the task is in a * non-terminal state, then stops automatically — terminal data won't * change anymore so further fetches just spend QPS budget. * * `refetchIntervalInBackground: false` lets the polling pause when the * tab is hidden so a forgotten Dream tab doesn't keep hitting the * engine forever. */ export function useDreamTask( memoryStoreName: string, dreamId: string | undefined, ) { const { context, ready } = useRuntimeContext(); return useQuery({ queryKey: queryKeys.dreamTask( context.dataScopeKey, memoryStoreName, dreamId, ), queryFn: () => getDreamTask(memoryStoreName, dreamId!), enabled: ready && !!memoryStoreName && !!dreamId, refetchInterval: (query) => { const data = query.state.data; if (!data) return POLL_INTERVAL_MS; return DREAM_TERMINAL_STATUSES.has(data.status) ? false : POLL_INTERVAL_MS; }, refetchIntervalInBackground: false, }); }