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 focusRequestId: state.focusRequestId,
218 onRetry: remote.refresh,
219 onQueryChange: (query: string) => {
220 if (threadKey !== null) setThreadFindQuery(threadKey, query);
221 },
222 onNext: () => step(1),
223 onPrevious: () => step(-1),
224 onClose: closeThreadFind,
225 },
226 timelineProps: timeline,
227 };
228}
229
230export interface TimelineFields {
231 readonly findOpen: boolean;
232 readonly findExpanded: boolean;
233 readonly findQuery: string;
234 readonly activeFindMatch: ThreadFindMatch | null;
235 readonly findNavigationId: number;
236}
237
238function sameTimeline(a: TimelineFields, b: TimelineFields) {
239 const aMatch = a.activeFindMatch;
240 const bMatch = b.activeFindMatch;
241 return (
242 a.findOpen === b.findOpen &&
243 a.findExpanded === b.findExpanded &&
244 a.findQuery === b.findQuery &&
245 a.findNavigationId === b.findNavigationId &&
246 (aMatch === null || bMatch === null
247 ? aMatch === bMatch
248 : aMatch.entryId === bMatch.entryId &&
249 aMatch.runId === bMatch.runId &&
250 aMatch.occurrence === bMatch.occurrence)
251 );
252}
253
254function rebaseLocalSelection(
255 selection: ThreadFindLocalSelection | null,
256 data: OrchestrationV2SearchThreadResult | null,
257 navigationId: number,
258) {
259 if (!selection || !data) return null;
260 if (selection.base === data && selection.baseNavigationId === navigationId) return selection;
261 if (navigationId >= selection.navigationId) return null;
262 const entry = data.navigation?.find((entry) => entry.entryId === selection.match.entryId);
263 if (!entry || selection.match.occurrence >= entry.count) return selection;
264 const activeIndex = entry.startIndex + selection.match.occurrence;
265 return activeIndex === selection.activeIndex ? selection : { ...selection, activeIndex };
266}
267
268function useServerResults(
269 thread: ScopedThreadRef | null,
270 query: string,
271 offset: number,
272 navigationId: number,
273 start: ThreadFindStart | undefined,
274 skills: readonly InlineSkill[],
275 progressive: boolean,
276) {
277 const skillLabels = skills.map(({ name, displayName }) => ({ name, displayName }));
278 const normalizedQuery = query.trim();
279 const debouncedQuery = useDebouncedValue(normalizedQuery, 100);
280 const environmentId = thread?.environmentId;
281 const threadId = thread?.threadId;
282 const target =
283 environmentId && threadId && debouncedQuery && normalizedQuery === debouncedQuery
284 ? {
285 environmentId,
286 input: {
287 threadId,
288 query: debouncedQuery,
289 ...(start ? { start } : {}),
290 ...(offset !== 0 ? { offset } : {}),
291 skills: skillLabels,
292 },
293 }
294 : null;
295 const targetKey = target ? JSON.stringify([progressive, target]) : null;
296 const [storedAtom, setStoredAtom] = useState(() => ({
297 key: targetKey,
298 atom: resolveThreadFindAtom(target, progressive),
299 }));
300 let atom = storedAtom.atom;
301 if (storedAtom.key !== targetKey) {
302 atom = resolveThreadFindAtom(target, progressive);
303 setStoredAtom({ key: targetKey, atom });
304 }
305 const result = useEnvironmentQuery(atom);
306 const key = thread
307 ? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels])
308 : null;
309 const [previous, setPrevious] = useState({
310 key,
311 data: result.data,
312 navigationId,
313 });
314 if (
315 previous.key !== key ||
316 (result.data !== null &&
317 (!result.isPending || (progressive && previous.data !== result.data)) &&
318 (previous.data !== result.data || previous.navigationId !== navigationId))
319 ) {
320 const response = result.data;
321 setPrevious({
322 key,
323 data: response,
324 navigationId,
325 });
326 }
327 return {
328 ...result,
329 data: key === previous.key && !result.error ? previous.data : null,
330 navigationId: previous.navigationId,
331 isPending:
332 thread !== null &&
333 normalizedQuery.length > 0 &&
334 (normalizedQuery !== debouncedQuery || result.isPending),
335 };
336}
337
338function resolveThreadFindAtom(
339 target: Parameters<typeof orchestrationEnvironment.threadFind>[0] | null,
340 progressive: boolean,
341) {
342 if (!target) return null;
343 return progressive
344 ? orchestrationEnvironment.threadFindProgressive(target)
345 : orchestrationEnvironment.threadFind(target);
346}