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