Open History to see the last commit
1import type { InlineSkill } from "@t3tools/shared/inlineSkills";
2import type { OrchestrationV2SearchThreadResult, ScopedThreadRef } from "@t3tools/contracts";
3import { scopedThreadKey } from "@t3tools/client-runtime/environment";
4import { useEffect, useEffectEvent, useRef, useState } from "react";
5import { orchestrationEnvironment } from "~/state/orchestration";
6import { useThreadProjection } from "~/state/entities";
7import { useEnvironmentQuery } from "~/state/query";
8import { useDebouncedValue } from "~/state/queries";
9import { type ThreadFindMatch, type ThreadFindStart, stepThreadFindIndex } from "./threadFind";
10import {
11 CLOSED_THREAD_FIND,
12 closeThreadFind,
13 setThreadFindQuery,
14 useThreadFindOpen,
15 useThreadFindStore,
16 type ThreadFindLocalSelection,
17 type ThreadFindState,
18} from "./threadFindStore";
19
20const EMPTY_SKILLS: readonly InlineSkill[] = [];
21
22export function useThreadFind({
23 thread,
24 enabled,
25 progressive = false,
26 skills = EMPTY_SKILLS,
27}: {
28 thread: ScopedThreadRef | null;
29 enabled: boolean;
30 progressive?: boolean;
31 skills?: readonly InlineSkill[];
32}) {
33 // Read here rather than passed in: a streamed delta re-renders only the find
34 // provider, which refreshes open results from it.
35 const content = useThreadProjection(enabled ? thread : null)?.projection;
36 const lastContentRef = useRef(content);
37 const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
38 const refreshAfterSearchRef = useRef(false);
39 const threadKey = thread ? scopedThreadKey(thread) : null;
40 const isOpen = useThreadFindOpen(thread, enabled);
41 const stored = useThreadFindStore();
42 const state = isOpen ? stored : CLOSED_THREAD_FIND;
43 const setState = (update: (previous: ThreadFindState) => Partial<ThreadFindState>) =>
44 useThreadFindStore.setState((previous) =>
45 previous.threadKey === threadKey ? update(previous) : previous,
46 );
47
48 const remote = useServerResults(
49 isOpen ? thread : null,
50 state.query,
51 state.offset,
52 state.requestId,
53 state.start,
54 skills,
55 progressive,
56 );
57 const status: "loading" | "error" | null = remote.error
58 ? "error"
59 : remote.isPending && remote.data === null
60 ? "loading"
61 : null;
62 const localSelection = rebaseLocalSelection(
63 state.localSelection,
64 remote.data,
65 remote.navigationId,
66 );
67 const count = remote.data?.totalMatches ?? 0;
68 const activeIndex = localSelection?.activeIndex ?? remote.data?.activeIndex ?? 0;
69 const selectedMatch = localSelection?.match ?? remote.data?.match;
70 const entryId = selectedMatch?.entryId;
71 const runId = selectedMatch?.runId;
72 const occurrence = selectedMatch?.occurrence;
73 const counting = remote.data?.complete === false;
74 const navigationId = localSelection?.navigationId ?? remote.navigationId;
75 const findExpanded = isOpen && state.query.trim().length > 0;
76 const findQuery = isOpen && remote.data?.match ? state.query : "";
77 const nextTimeline: TimelineFields = {
78 findOpen: isOpen,
79 findExpanded,
80 findQuery,
81 activeFindMatch:
82 entryId !== undefined && occurrence !== undefined
83 ? { entryId, runId: runId ?? null, occurrence }
84 : null,
85 findNavigationId: navigationId,
86 };
87 // Keep timeline identity stable during count and response updates to avoid extra jumps.
88 const [storedTimeline, setTimeline] = useState(nextTimeline);
89 let timeline = storedTimeline;
90 if (!sameTimeline(timeline, nextTimeline)) {
91 timeline = nextTimeline;
92 setTimeline(timeline);
93 }
94 const match = timeline.activeFindMatch;
95 const step = (delta: number) => {
96 if (count === 0 || counting) return;
97 setState((previous) => {
98 const local = rebaseLocalSelection(previous.localSelection, remote.data, remote.navigationId);
99 const pending = previous.navigationId !== (local?.navigationId ?? remote.navigationId);
100 const selected = local?.match ?? remote.data?.match;
101 const nextIndex = stepThreadFindIndex(
102 local?.activeIndex ?? remote.data?.activeIndex ?? 0,
103 count,
104 delta,
105 );
106 const entry = remote.data?.navigation?.find(
107 (entry) => nextIndex >= entry.startIndex && nextIndex < entry.startIndex + entry.count,
108 );
109 const nextNavigationId = previous.navigationId + 1;
110 if (
111 !pending &&
112 !remote.isPending &&
113 entry &&
114 remote.data &&
115 (!local ||
116 local.base === remote.data ||
117 remote.data.navigation?.some(
118 (entry) =>
119 entry.entryId === local.match.entryId && local.match.occurrence < entry.count,
120 )) &&
121 refreshTimerRef.current === null &&
122 lastContentRef.current === content
123 ) {
124 return {
125 ...previous,
126 navigationId: nextNavigationId,
127 localSelection: {
128 base: remote.data,
129 baseNavigationId: remote.navigationId,
130 activeIndex: nextIndex,
131 match: {
132 entryId: entry.entryId,
133 runId: entry.runId,
134 occurrence: nextIndex - entry.startIndex,
135 },
136 navigationId: nextNavigationId,
137 },
138 };
139 }
140 return {
141 ...previous,
142 start:
143 pending || !selected
144 ? previous.start
145 : { entryId: selected.entryId, occurrence: selected.occurrence },
146 offset: pending ? previous.offset + delta : delta,
147 navigationId: nextNavigationId,
148 requestId: nextNavigationId,
149 };
150 });
151 };
152
153 // Runs from the refresh timer and after a coalesced search settles, against
154 // the results and selection showing by then.
155 const refreshLiveResults = useEffectEvent(() => {
156 if (!isOpen || !state.query.trim()) return;
157 // Coalesce paging updates while the server counts to avoid restarting scans.
158 if (progressive && remote.isPending) {
159 refreshAfterSearchRef.current = true;
160 return;
161 }
162 if (!match || state.navigationId !== navigationId) {
163 remote.refresh();
164 return;
165 }
166 const start = { entryId: match.entryId, occurrence: match.occurrence };
167 if (
168 state.offset === 0 &&
169 state.start?.entryId === start.entryId &&
170 state.start.occurrence === start.occurrence &&
171 state.requestId === state.navigationId
172 ) {
173 remote.refresh();
174 } else {
175 setState((previous) => ({
176 ...previous,
177 start,
178 offset: 0,
179 requestId: previous.navigationId,
180 }));
181 }
182 });
183 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reruns a live refresh that was coalesced behind a server search once that search settles
184 useEffect(() => {
185 if (!refreshAfterSearchRef.current || remote.isPending) return;
186 refreshAfterSearchRef.current = false;
187 if (!remote.error) refreshLiveResults();
188 }, [remote.isPending, remote.error]);
189 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts a debounce timer to refresh find results when streamed thread content changes
190 useEffect(() => {
191 if (lastContentRef.current === content) return;
192 lastContentRef.current = content;
193 if (!isOpen || !state.query.trim() || refreshTimerRef.current !== null) return;
194 refreshTimerRef.current = setTimeout(() => {
195 refreshTimerRef.current = null;
196 refreshLiveResults();
197 }, 300);
198 }, [content, isOpen, state.query]);
199 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the pending refresh timer when the thread, open state or query changes
200 useEffect(() => {
201 if (!isOpen || threadKey === null || !state.query.trim()) return;
202 return () => {
203 if (refreshTimerRef.current !== null) clearTimeout(refreshTimerRef.current);
204 refreshTimerRef.current = null;
205 refreshAfterSearchRef.current = false;
206 };
207 }, [threadKey, isOpen, state.query]);
208
209 return {
210 barProps: {
211 open: isOpen,
212 query: state.query,
213 matchCount: count,
214 counting,
215 activeIndex,
216 status,
217 navigationId: state.navigationId,
218 settled:
219 status === "error" || (status === null && !counting && navigationId === state.navigationId),
220 focusRequestId: state.focusRequestId,
221 onRetry: remote.refresh,
222 onQueryChange: (query: string) => {
223 if (threadKey !== null) setThreadFindQuery(threadKey, query);
224 },
225 onNext: () => step(1),
226 onPrevious: () => step(-1),
227 onClose: closeThreadFind,
228 },
229 timelineProps: timeline,
230 };
231}
232
233export interface TimelineFields {
234 readonly findOpen: boolean;
235 readonly findExpanded: boolean;
236 readonly findQuery: string;
237 readonly activeFindMatch: ThreadFindMatch | null;
238 readonly findNavigationId: number;
239}
240
241function sameTimeline(a: TimelineFields, b: TimelineFields) {
242 const aMatch = a.activeFindMatch;
243 const bMatch = b.activeFindMatch;
244 return (
245 a.findOpen === b.findOpen &&
246 a.findExpanded === b.findExpanded &&
247 a.findQuery === b.findQuery &&
248 a.findNavigationId === b.findNavigationId &&
249 (aMatch === null || bMatch === null
250 ? aMatch === bMatch
251 : aMatch.entryId === bMatch.entryId &&
252 aMatch.runId === bMatch.runId &&
253 aMatch.occurrence === bMatch.occurrence)
254 );
255}
256
257function rebaseLocalSelection(
258 selection: ThreadFindLocalSelection | null,
259 data: OrchestrationV2SearchThreadResult | null,
260 navigationId: number,
261) {
262 if (!selection || !data) return null;
263 if (selection.base === data && selection.baseNavigationId === navigationId) return selection;
264 if (navigationId >= selection.navigationId) return null;
265 const entry = data.navigation?.find((entry) => entry.entryId === selection.match.entryId);
266 if (!entry || selection.match.occurrence >= entry.count) return selection;
267 const activeIndex = entry.startIndex + selection.match.occurrence;
268 return activeIndex === selection.activeIndex ? selection : { ...selection, activeIndex };
269}
270
271function useServerResults(
272 thread: ScopedThreadRef | null,
273 query: string,
274 offset: number,
275 navigationId: number,
276 start: ThreadFindStart | undefined,
277 skills: readonly InlineSkill[],
278 progressive: boolean,
279) {
280 const skillLabels = skills.map(({ name, displayName }) => ({ name, displayName }));
281 const normalizedQuery = query.trim();
282 const debouncedQuery = useDebouncedValue(normalizedQuery, 100);
283 const environmentId = thread?.environmentId;
284 const threadId = thread?.threadId;
285 const target =
286 environmentId && threadId && debouncedQuery && normalizedQuery === debouncedQuery
287 ? {
288 environmentId,
289 input: {
290 threadId,
291 query: debouncedQuery,
292 ...(start ? { start } : {}),
293 ...(offset !== 0 ? { offset } : {}),
294 skills: skillLabels,
295 },
296 }
297 : null;
298 const targetKey = target ? JSON.stringify([progressive, target]) : null;
299 const [storedAtom, setStoredAtom] = useState(() => ({
300 key: targetKey,
301 atom: resolveThreadFindAtom(target, progressive),
302 }));
303 let atom = storedAtom.atom;
304 if (storedAtom.key !== targetKey) {
305 atom = resolveThreadFindAtom(target, progressive);
306 setStoredAtom({ key: targetKey, atom });
307 }
308 const result = useEnvironmentQuery(atom);
309 const key = thread
310 ? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels])
311 : null;
312 const [previous, setPrevious] = useState({
313 key,
314 data: result.data,
315 navigationId,
316 });
317 if (
318 previous.key !== key ||
319 (result.data !== null &&
320 (!result.isPending || (progressive && previous.data !== result.data)) &&
321 (previous.data !== result.data || previous.navigationId !== navigationId))
322 ) {
323 const response = result.data;
324 setPrevious({
325 key,
326 data: response,
327 navigationId,
328 });
329 }
330 return {
331 ...result,
332 data: key === previous.key && !result.error ? previous.data : null,
333 navigationId: previous.navigationId,
334 isPending:
335 thread !== null &&
336 normalizedQuery.length > 0 &&
337 (normalizedQuery !== debouncedQuery || result.isPending),
338 };
339}
340
341function resolveThreadFindAtom(
342 target: Parameters<typeof orchestrationEnvironment.threadFind>[0] | null,
343 progressive: boolean,
344) {
345 if (!target) return null;
346 return progressive
347 ? orchestrationEnvironment.threadFindProgressive(target)
348 : orchestrationEnvironment.threadFind(target);
349}