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, useLayoutEffect, useRef, useState, type RefObject } from "react";
5import { useStableCallback } from "~/hooks/useStableCallback";
6import { orchestrationEnvironment } from "~/state/orchestration";
7import { useThreadProjection } from "~/state/entities";
8import { useEnvironmentQuery } from "~/state/query";
9import { useDebouncedValue } from "~/state/queries";
10import {
11 type ThreadFindPositionReader,
12 type ThreadFindStart,
13 stepThreadFindIndex,
14} from "./threadFind";
15import {
16 subscribeThreadFindOpen,
17 subscribeThreadFindQuery,
18 takeThreadFindQuery,
19} from "./threadFindActionBus";
20import { toastManager } from "../ui/toast";
21
22const EMPTY_SKILLS: readonly InlineSkill[] = [];
23
24const CLOSED_FIND = {
25 threadKey: null as string | null,
26 query: "",
27 offset: 0,
28 start: undefined as ThreadFindStart | undefined,
29 focusRequestId: 0,
30 navigationId: 0,
31 requestId: 0,
32 localSelection: null as {
33 base: OrchestrationV2SearchThreadResult;
34 baseNavigationId: number;
35 activeIndex: number;
36 match: NonNullable<OrchestrationV2SearchThreadResult["match"]>;
37 navigationId: number;
38 } | null,
39};
40
41export function useThreadFind({
42 thread,
43 enabled,
44 progressive = false,
45 skills = EMPTY_SKILLS,
46}: {
47 thread: ScopedThreadRef | null;
48 enabled: boolean;
49 progressive?: boolean;
50 skills?: readonly InlineSkill[];
51}) {
52 // Read here rather than passed in: a streamed delta re-renders only the find
53 // provider, which refreshes open results from it.
54 const content = useThreadProjection(enabled ? thread : null)?.projection;
55 // Held in state so the timeline props that carry it can be stored in state too.
56 const [positionReader] = useState<RefObject<ThreadFindPositionReader | null>>(() => ({
57 current: null,
58 }));
59 const lastContentRef = useRef(content);
60 const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
61 const refreshAfterSearchRef = useRef(false);
62 const threadKey = thread ? scopedThreadKey(thread) : null;
63 const [state, setState] = useState(CLOSED_FIND);
64 if (state.threadKey !== null && (!enabled || state.threadKey !== threadKey))
65 setState(CLOSED_FIND);
66 const isOpen = enabled && threadKey !== null && state.threadKey === threadKey;
67 const open = useStableCallback(() => {
68 if (threadKey === null) return;
69 if (!enabled) {
70 toastManager.add({
71 id: "thread-find-unavailable",
72 title: "Thread search is unavailable on this server.",
73 description: "Update the server to enable it.",
74 });
75 return;
76 }
77 const start =
78 state.threadKey === threadKey && state.query.trim()
79 ? positionReader.current?.(state.query.trim())
80 : undefined;
81 setState((previous) => {
82 const current = previous.threadKey === threadKey ? previous : CLOSED_FIND;
83 return {
84 ...current,
85 threadKey,
86 focusRequestId: previous.focusRequestId + 1,
87 ...(current.query.trim()
88 ? {
89 start,
90 offset: 0,
91 localSelection: null,
92 navigationId: current.navigationId + 1,
93 requestId: current.navigationId + 1,
94 }
95 : {}),
96 };
97 });
98 });
99 const close = useStableCallback(() => setState(CLOSED_FIND));
100 useEffect(() => subscribeThreadFindOpen(open), [open]);
101 const openOnQuery = useStableCallback((query: string, start?: ThreadFindStart) => {
102 if (threadKey === null) return;
103 setState((previous) => ({
104 ...(previous.threadKey === threadKey ? previous : CLOSED_FIND),
105 threadKey,
106 query,
107 offset: 0,
108 start,
109 localSelection: null,
110 focusRequestId: previous.focusRequestId + 1,
111 navigationId: previous.navigationId + 1,
112 requestId: previous.navigationId + 1,
113 }));
114 });
115 // A palette message result opens find on its query, at its message, once
116 // this thread shows.
117 useEffect(() => {
118 if (threadKey === null || !enabled) return;
119 const take = () => {
120 const find = takeThreadFindQuery(threadKey);
121 if (find !== null) openOnQuery(find.query, find.start);
122 };
123 take();
124 return subscribeThreadFindQuery(take);
125 }, [enabled, openOnQuery, threadKey]);
126
127 const remote = useServerResults(
128 isOpen ? thread : null,
129 state.query,
130 state.offset,
131 state.requestId,
132 state.start,
133 skills,
134 progressive,
135 );
136 const status: "loading" | "error" | null = remote.error
137 ? "error"
138 : remote.isPending && remote.data === null
139 ? "loading"
140 : null;
141 const localSelection = rebaseLocalSelection(
142 state.localSelection,
143 remote.data,
144 remote.navigationId,
145 );
146 const count = remote.data?.totalMatches ?? 0;
147 const activeIndex = localSelection?.activeIndex ?? remote.data?.activeIndex ?? 0;
148 const selectedMatch = localSelection?.match ?? remote.data?.match;
149 const entryId = selectedMatch?.entryId;
150 const runId = selectedMatch?.runId;
151 const occurrence = selectedMatch?.occurrence;
152 const counting = remote.data?.complete === false;
153 const navigationId = localSelection?.navigationId ?? remote.navigationId;
154 const findExpanded = isOpen && state.query.trim().length > 0;
155 const findQuery = isOpen && remote.data?.match ? state.query : "";
156 const nextTimeline = {
157 findOpen: isOpen,
158 findExpanded,
159 findQuery,
160 activeFindMatch:
161 entryId !== undefined && occurrence !== undefined
162 ? { entryId, runId: runId ?? null, occurrence }
163 : null,
164 findNavigationId: navigationId,
165 };
166 // Finishing the count or a pending response must not rerender the timeline or
167 // request another jump, so these keep their identity until a field changes.
168 const [storedTimeline, setTimeline] = useState(() => ({
169 fields: nextTimeline,
170 props: { ...nextTimeline, findPositionReaderRef: positionReader },
171 }));
172 let timeline = storedTimeline;
173 if (!sameTimeline(timeline.fields, nextTimeline)) {
174 timeline = {
175 fields: nextTimeline,
176 props: { ...nextTimeline, findPositionReaderRef: positionReader },
177 };
178 setTimeline(timeline);
179 }
180 const match = timeline.fields.activeFindMatch;
181 const step = (delta: number) => {
182 if (count === 0 || counting) return;
183 setState((previous) => {
184 const local = rebaseLocalSelection(previous.localSelection, remote.data, remote.navigationId);
185 const pending = previous.navigationId !== (local?.navigationId ?? remote.navigationId);
186 const selected = local?.match ?? remote.data?.match;
187 const nextIndex = stepThreadFindIndex(
188 local?.activeIndex ?? remote.data?.activeIndex ?? 0,
189 count,
190 delta,
191 );
192 const entry = remote.data?.navigation?.find(
193 (entry) => nextIndex >= entry.startIndex && nextIndex < entry.startIndex + entry.count,
194 );
195 const nextNavigationId = previous.navigationId + 1;
196 if (
197 !pending &&
198 !remote.isPending &&
199 entry &&
200 remote.data &&
201 (!local ||
202 local.base === remote.data ||
203 remote.data.navigation?.some(
204 (entry) =>
205 entry.entryId === local.match.entryId && local.match.occurrence < entry.count,
206 )) &&
207 refreshTimerRef.current === null &&
208 lastContentRef.current === content
209 ) {
210 return {
211 ...previous,
212 navigationId: nextNavigationId,
213 localSelection: {
214 base: remote.data,
215 baseNavigationId: remote.navigationId,
216 activeIndex: nextIndex,
217 match: {
218 entryId: entry.entryId,
219 runId: entry.runId,
220 occurrence: nextIndex - entry.startIndex,
221 },
222 navigationId: nextNavigationId,
223 },
224 };
225 }
226 return {
227 ...previous,
228 start:
229 pending || !selected
230 ? previous.start
231 : { entryId: selected.entryId, occurrence: selected.occurrence },
232 offset: pending ? previous.offset + delta : delta,
233 navigationId: nextNavigationId,
234 requestId: nextNavigationId,
235 };
236 });
237 };
238
239 const refreshLiveResultsRef = useRef(() => {});
240 useLayoutEffect(() => {
241 refreshLiveResultsRef.current = () => {
242 if (!isOpen || !state.query.trim()) return;
243 // Paging can change client content while the server is still counting.
244 // Coalesce those updates instead of repeatedly restarting the scan.
245 if (progressive && remote.isPending) {
246 refreshAfterSearchRef.current = true;
247 return;
248 }
249 if (!match || state.navigationId !== navigationId) {
250 remote.refresh();
251 return;
252 }
253 const start = { entryId: match.entryId, occurrence: match.occurrence };
254 if (
255 state.offset === 0 &&
256 state.start?.entryId === start.entryId &&
257 state.start.occurrence === start.occurrence &&
258 state.requestId === state.navigationId
259 ) {
260 remote.refresh();
261 } else {
262 setState((previous) => ({
263 ...previous,
264 start,
265 offset: 0,
266 requestId: previous.navigationId,
267 }));
268 }
269 };
270 });
271 useEffect(() => {
272 if (!refreshAfterSearchRef.current || remote.isPending) return;
273 refreshAfterSearchRef.current = false;
274 if (!remote.error) refreshLiveResultsRef.current();
275 }, [remote.isPending, remote.error]);
276 useEffect(() => {
277 if (lastContentRef.current === content) return;
278 lastContentRef.current = content;
279 if (!isOpen || !state.query.trim() || refreshTimerRef.current !== null) return;
280 refreshTimerRef.current = setTimeout(() => {
281 refreshTimerRef.current = null;
282 refreshLiveResultsRef.current();
283 }, 300);
284 }, [content, isOpen, state.query]);
285 useEffect(() => {
286 if (!isOpen || threadKey === null || !state.query.trim()) return;
287 return () => {
288 if (refreshTimerRef.current !== null) clearTimeout(refreshTimerRef.current);
289 refreshTimerRef.current = null;
290 refreshAfterSearchRef.current = false;
291 };
292 }, [threadKey, isOpen, state.query]);
293
294 return {
295 isOpen,
296 open,
297 close,
298 barProps: {
299 open: isOpen,
300 query: state.query,
301 matchCount: count,
302 counting,
303 activeIndex,
304 status,
305 focusRequestId: state.focusRequestId,
306 onRetry: remote.refresh,
307 onQueryChange: (query: string) => {
308 const start = positionReader.current?.(query.trim());
309 setState((previous) => ({
310 ...previous,
311 query,
312 offset: 0,
313 start,
314 localSelection: null,
315 navigationId: previous.navigationId + 1,
316 requestId: previous.navigationId + 1,
317 }));
318 },
319 onNext: () => step(1),
320 onPrevious: () => step(-1),
321 onClose: close,
322 },
323 timelineProps: timeline.props,
324 };
325}
326
327type TimelineFields = Omit<
328 ReturnType<typeof useThreadFind>["timelineProps"],
329 "findPositionReaderRef"
330>;
331
332function sameTimeline(a: TimelineFields, b: TimelineFields) {
333 const aMatch = a.activeFindMatch;
334 const bMatch = b.activeFindMatch;
335 return (
336 a.findOpen === b.findOpen &&
337 a.findExpanded === b.findExpanded &&
338 a.findQuery === b.findQuery &&
339 a.findNavigationId === b.findNavigationId &&
340 (aMatch === null || bMatch === null
341 ? aMatch === bMatch
342 : aMatch.entryId === bMatch.entryId &&
343 aMatch.runId === bMatch.runId &&
344 aMatch.occurrence === bMatch.occurrence)
345 );
346}
347
348function rebaseLocalSelection(
349 selection: typeof CLOSED_FIND.localSelection,
350 data: OrchestrationV2SearchThreadResult | null,
351 navigationId: number,
352) {
353 if (!selection || !data) return null;
354 if (selection.base === data && selection.baseNavigationId === navigationId) return selection;
355 if (navigationId >= selection.navigationId) return null;
356 const entry = data.navigation?.find((entry) => entry.entryId === selection.match.entryId);
357 if (!entry || selection.match.occurrence >= entry.count) return selection;
358 const activeIndex = entry.startIndex + selection.match.occurrence;
359 return activeIndex === selection.activeIndex ? selection : { ...selection, activeIndex };
360}
361
362function useServerResults(
363 thread: ScopedThreadRef | null,
364 query: string,
365 offset: number,
366 navigationId: number,
367 start: ThreadFindStart | undefined,
368 skills: readonly InlineSkill[],
369 progressive: boolean,
370) {
371 const skillLabels = skills.map(({ name, displayName }) => ({ name, displayName }));
372 const normalizedQuery = query.trim();
373 const debouncedQuery = useDebouncedValue(normalizedQuery, 100);
374 const environmentId = thread?.environmentId;
375 const threadId = thread?.threadId;
376 const target =
377 environmentId && threadId && debouncedQuery && normalizedQuery === debouncedQuery
378 ? {
379 environmentId,
380 input: {
381 threadId,
382 query: debouncedQuery,
383 ...(start ? { start } : {}),
384 ...(offset !== 0 ? { offset } : {}),
385 skills: skillLabels,
386 },
387 }
388 : null;
389 const targetKey = target ? JSON.stringify([progressive, target]) : null;
390 // Resolving the atom only when the request changes keeps unrelated renders from
391 // touching the atom family.
392 const [storedAtom, setStoredAtom] = useState(() => ({
393 key: targetKey,
394 atom: resolveThreadFindAtom(target, progressive),
395 }));
396 let atom = storedAtom.atom;
397 if (storedAtom.key !== targetKey) {
398 atom = resolveThreadFindAtom(target, progressive);
399 setStoredAtom({ key: targetKey, atom });
400 }
401 const result = useEnvironmentQuery(atom);
402 const key = thread
403 ? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels])
404 : null;
405 const [previous, setPrevious] = useState({
406 key,
407 data: result.data,
408 navigationId,
409 });
410 if (
411 previous.key !== key ||
412 (result.data !== null &&
413 (!result.isPending || (progressive && previous.data !== result.data)) &&
414 (previous.data !== result.data || previous.navigationId !== navigationId))
415 ) {
416 const response = result.data;
417 setPrevious({
418 key,
419 data: response,
420 navigationId,
421 });
422 }
423 return {
424 ...result,
425 data: key === previous.key && !result.error ? previous.data : null,
426 navigationId: previous.navigationId,
427 isPending:
428 thread !== null &&
429 normalizedQuery.length > 0 &&
430 (normalizedQuery !== debouncedQuery || result.isPending),
431 };
432}
433
434function resolveThreadFindAtom(
435 target: Parameters<typeof orchestrationEnvironment.threadFind>[0] | null,
436 progressive: boolean,
437) {
438 if (!target) return null;
439 return progressive
440 ? orchestrationEnvironment.threadFindProgressive(target)
441 : orchestrationEnvironment.threadFind(target);
442}