| 1 | import { desktopHost } from "./desktopHost"; |
| 2 | import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; |
| 3 | import { app } from "./bridge"; |
| 4 | import { assertReadPage, isStaleRead, releaseReadSnapshot } from "./readSnapshot"; |
| 5 | import { loadProjectTreePageWindow } from "./projectTreeWindow"; |
| 6 | import type { HistorySearchHit, SessionMeta, HistorySessionPage, HistorySearchPage } from "./types"; |
| 7 | |
| 8 | export function useHistoryCatalog({ isTrash, suppliedSessions, scope, status, timeFilter, query }: { |
| 9 | isTrash: boolean; suppliedSessions: SessionMeta[]; scope: string; status: string; timeFilter: string; query: string; |
| 10 | }) { |
| 11 | const activeSession = suppliedSessions.find((session) => session.current); |
| 12 | const workspaceRoot = activeSession?.workspaceRoot ?? ""; |
| 13 | const identity = JSON.stringify([isTrash, scope, workspaceRoot, activeSession?.hostId ?? "", activeSession?.sessionId ?? "", activeSession?.path ?? "", status, timeFilter, query.trim()]); |
| 14 | const emptyView = { identity, sessions: [] as SessionMeta[], hits: [] as HistorySearchHit[], sessionCursor: "", searchCursor: "", partial: false, progress: { indexed: 0, total: 0 }, error: "", loading: false }; |
| 15 | const [view, setView] = useState(emptyView); |
| 16 | const viewRef = useRef(view); viewRef.current = view; |
| 17 | const generation = useRef(0); |
| 18 | const pending = useRef<number | null>(null); |
| 19 | const refreshPending = useRef(false); |
| 20 | const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); |
| 21 | const lastStart = useRef(0); |
| 22 | const ids = useRef({ sessions: "", search: "" }); |
| 23 | const windowSize = useRef({ sessions: 50, search: 50 }); |
| 24 | const identityRef = useRef(identity); |
| 25 | const scheduleRef = useRef<() => void>(() => {}); |
| 26 | |
| 27 | const fetchPage = useCallback(async (append: boolean, seq: number) => { |
| 28 | if (seq !== generation.current || identityRef.current !== identity || isTrash) return; |
| 29 | if (append && viewRef.current.identity !== identity) return; |
| 30 | if (pending.current === seq) { if (!append) refreshPending.current = true; return; } |
| 31 | pending.current = seq; |
| 32 | lastStart.current = Date.now(); |
| 33 | const before = viewRef.current.identity === identity ? viewRef.current : { identity, sessions: [] as SessionMeta[], hits: [] as HistorySearchHit[], sessionCursor: "", searchCursor: "", partial: false, progress: { indexed: 0, total: 0 }, error: "", loading: false }; |
| 34 | viewRef.current = { ...before, loading: true, error: "" }; |
| 35 | setView(viewRef.current); |
| 36 | const desired = { sessions: append ? before.sessions.length + 50 : windowSize.current.sessions, search: append ? before.hits.length + 50 : windowSize.current.search }; |
| 37 | let page: HistorySessionPage | null = null; |
| 38 | let body: HistorySearchPage | null = null; |
| 39 | let replace = !append; |
| 40 | const releaseStaged = () => { |
| 41 | if (page?.snapshotId && page.snapshotId !== ids.current.sessions) releaseReadSnapshot(page.snapshotId); |
| 42 | if (body?.snapshotId && body.snapshotId !== ids.current.search) releaseReadSnapshot(body.snapshotId); |
| 43 | }; |
| 44 | try { |
| 45 | for (let attempt = 0; attempt < 2; attempt++) { |
| 46 | const base = { scope, workspaceRoot, status, timeFilter, query: query.trim() }; |
| 47 | // One generation owns both requests. allSettled also releases the |
| 48 | // successful sibling if the other request fails. |
| 49 | const results = await Promise.allSettled([ |
| 50 | replace || before.sessionCursor ? loadProjectTreePageWindow<SessionMeta, HistorySessionPage>(replace ? "" : before.sessionCursor, replace ? desired.sessions : 50, async (cursor, limit) => { |
| 51 | const result = await app.ListHistorySessions({ ...base, cursor, limit }); assertReadPage(result); return result; |
| 52 | }, desired.sessions, false) : Promise.resolve(null), |
| 53 | query.trim() && (replace || before.searchCursor) ? loadProjectTreePageWindow<HistorySearchHit, HistorySearchPage>(replace ? "" : before.searchCursor, replace ? desired.search : 50, async (cursor, limit) => { |
| 54 | const result = await app.SearchHistoryContent({ ...base, cursor, limit, kinds: [], toolName: "" }); assertReadPage(result); return result; |
| 55 | }, desired.search, false) : Promise.resolve(null), |
| 56 | ]); |
| 57 | page = results[0].status === "fulfilled" ? results[0].value : null; |
| 58 | body = results[1].status === "fulfilled" ? results[1].value : null; |
| 59 | const failure = results.find((result) => result.status === "rejected"); |
| 60 | if (!failure || failure.status !== "rejected") break; |
| 61 | releaseStaged(); page = null; body = null; |
| 62 | if (attempt === 1 || !isStaleRead(failure.reason)) throw failure.reason; |
| 63 | replace = true; |
| 64 | } |
| 65 | if (seq !== generation.current) { releaseStaged(); return; } |
| 66 | if (!replace && ((page?.snapshotId && ids.current.sessions && page.snapshotId !== ids.current.sessions) || (body?.snapshotId && ids.current.search && body.snapshotId !== ids.current.search))) throw new Error("Mixed history read snapshots"); |
| 67 | const sessions = replace ? page?.items ?? [] : [...before.sessions, ...(page?.items ?? [])]; |
| 68 | const hits = replace ? body?.items ?? [] : [...before.hits, ...(body?.items ?? [])]; |
| 69 | if (replace) { |
| 70 | if (ids.current.sessions !== page?.snapshotId) releaseReadSnapshot(ids.current.sessions); |
| 71 | if (ids.current.search !== body?.snapshotId) releaseReadSnapshot(ids.current.search); |
| 72 | ids.current = { sessions: page?.snapshotId ?? "", search: body?.snapshotId ?? "" }; |
| 73 | } |
| 74 | windowSize.current = { sessions: Math.max(50, desired.sessions), search: Math.max(50, desired.search) }; |
| 75 | const next = { identity, sessions, hits, sessionCursor: page?.nextCursor ?? (replace ? "" : before.sessionCursor), searchCursor: body?.nextCursor ?? (replace ? "" : before.searchCursor), partial: Boolean(page?.partial || body?.partial || (!replace && before.partial)), progress: body ? { indexed: body.status.indexed, total: body.status.total } : before.progress, loading: false, error: "" }; |
| 76 | viewRef.current = next; setView(next); |
| 77 | } catch (error) { |
| 78 | releaseStaged(); |
| 79 | if (seq === generation.current) setView((current) => ({ ...current, loading: false, error: error instanceof Error ? error.message : String(error) })); |
| 80 | } finally { |
| 81 | if (pending.current === seq) pending.current = null; |
| 82 | if (seq === generation.current && refreshPending.current) { refreshPending.current = false; scheduleRef.current(); } |
| 83 | } |
| 84 | }, [identity, isTrash, query, scope, status, timeFilter, workspaceRoot]); |
| 85 | |
| 86 | const schedule = useCallback(() => { |
| 87 | if (isTrash || desktopHost().kind === "none") return; |
| 88 | if (pending.current === generation.current) { refreshPending.current = true; return; } |
| 89 | if (timer.current !== undefined) return; |
| 90 | timer.current = setTimeout(() => { timer.current = undefined; void fetchPage(false, generation.current); }, Math.max(200, 500 - (Date.now() - lastStart.current))); |
| 91 | }, [fetchPage, isTrash]); |
| 92 | scheduleRef.current = schedule; |
| 93 | |
| 94 | useLayoutEffect(() => { |
| 95 | identityRef.current = identity; |
| 96 | const seq = ++generation.current; |
| 97 | releaseReadSnapshot(ids.current.sessions); releaseReadSnapshot(ids.current.search); |
| 98 | ids.current = { sessions: "", search: "" }; |
| 99 | windowSize.current = { sessions: 50, search: 50 }; |
| 100 | refreshPending.current = false; |
| 101 | const initial = !isTrash && desktopHost().kind !== "none" ? setTimeout(() => { void fetchPage(false, seq); }, query.trim() ? 200 : 0) : undefined; |
| 102 | return () => { |
| 103 | clearTimeout(initial); ++generation.current; |
| 104 | if (timer.current !== undefined) clearTimeout(timer.current); timer.current = undefined; |
| 105 | }; |
| 106 | }, [fetchPage, identity, isTrash, query]); |
| 107 | |
| 108 | useEffect(() => { |
| 109 | const host = desktopHost(); |
| 110 | if (isTrash || host.kind === "none") return; |
| 111 | return host.events.on("history-index:changed-v1", () => scheduleRef.current()); |
| 112 | }, [isTrash]); |
| 113 | |
| 114 | useEffect(() => () => { releaseReadSnapshot(ids.current.sessions); releaseReadSnapshot(ids.current.search); }, []); |
| 115 | const loadMore = useCallback(() => { if (viewRef.current.sessionCursor || viewRef.current.searchCursor) void fetchPage(true, generation.current); }, [fetchPage]); |
| 116 | const visible = view.identity === identity ? view : emptyView; |
| 117 | return { readIdentity: identity, sessions: isTrash || desktopHost().kind === "none" ? suppliedSessions : visible.sessions, nextCursor: isTrash ? "" : visible.sessionCursor || visible.searchCursor, partial: visible.partial, progress: visible.progress, searchHits: isTrash ? [] : visible.hits, loadMore, error: visible.error, loading: visible.loading, retry: schedule }; |
| 118 | } |
| 119 |