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