import { useEffect } from "react"; import { useInfiniteQuery } from "@tanstack/react-query"; import { listDreamTasks } from "@/services/memory"; import { queryKeys } from "@/lib/query-keys"; import { useRuntimeContext } from "@/providers/runtime-context-provider"; import type { DreamTask, MemoryScope } from "@/types/memory"; /** * Cap on eager auto-pagination. The Dream list API returns tasks scope-major * (createdAt desc *within* a scope, but not globally), so to present a coherent * scope-grouped view the hook walks every page and lets the UI group across the * full result set. The cap keeps a scope with a very long history from fanning * out unbounded; when it is hit the caller surfaces a "load more" affordance. */ const MAX_AUTO_PAGES = 25; interface DreamTasksPage { items: DreamTask[]; totalCount: number; scope: MemoryScope; memoryStoreName: string; nextToken?: string; } export interface UseDreamTasksResult { /** All tasks loaded so far, flattened across auto-paginated pages. */ tasks: DreamTask[]; isLoading: boolean; isRefetching: boolean; isFetchingNextPage: boolean; hasNextPage: boolean; /** True when the auto-pagination cap was hit and more tasks remain unloaded. */ truncated: boolean; fetchNextPage: () => void; refetch: () => void; error: Error | null; errorCode: string | null; } export function useDreamTasks( memoryStoreName: string, scope: MemoryScope | null, options?: { limit?: number; status?: string; minTimestamp?: string; maxTimestamp?: string; }, ): UseDreamTasksResult { const { context, ready } = useRuntimeContext(); const limit = options?.limit ?? 50; const filters = { status: options?.status, minTimestamp: options?.minTimestamp, maxTimestamp: options?.maxTimestamp, }; const query = useInfiniteQuery({ // nextToken is intentionally omitted from the key — it is the pageParam, // so all pages of one filter share a single cache entry. queryKey: queryKeys.dreamTasks( context.dataScopeKey, memoryStoreName, scope, undefined, limit, filters, ), queryFn: ({ pageParam }) => listDreamTasks(memoryStoreName, scope!, { limit, nextToken: typeof pageParam === "string" ? pageParam : undefined, status: filters.status, minTimestamp: filters.minTimestamp, maxTimestamp: filters.maxTimestamp, }), getNextPageParam: (last) => last.nextToken ?? undefined, initialPageParam: undefined as string | undefined, enabled: ready && !!memoryStoreName && !!scope?.appId, }); const pageCount = query.data?.pages?.length ?? 0; const capReached = pageCount >= MAX_AUTO_PAGES; // Eagerly load remaining pages (up to the cap) so grouping spans the full // result set rather than a single page. useEffect(() => { if (query.hasNextPage && !query.isFetchingNextPage && !capReached) { void query.fetchNextPage(); } }, [query.hasNextPage, query.isFetchingNextPage, capReached, query]); const tasks = (query.data?.pages ?? []).flatMap( (page) => page.items ?? [], ) as DreamTask[]; const errorCode = query.error && "code" in query.error ? ((query.error as { code?: string }).code ?? null) : null; return { tasks, isLoading: query.isLoading, isRefetching: query.isRefetching, isFetchingNextPage: query.isFetchingNextPage, hasNextPage: Boolean(query.hasNextPage), truncated: Boolean(query.hasNextPage) && capReached, fetchNextPage: () => { if (query.hasNextPage && !query.isFetchingNextPage) query.fetchNextPage(); }, refetch: () => { void query.refetch(); }, error: query.error ?? null, errorCode, }; }