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