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 // Keep timeline identity stable during count and response updates to avoid extra jumps.
167 const [storedTimeline, setTimeline] = useState(() => ({
168 fields: nextTimeline,
169 props: { ...nextTimeline, findPositionReaderRef: positionReader },
170 }));
171 let timeline = storedTimeline;
172 if (!sameTimeline(timeline.fields, nextTimeline)) {
173 timeline = {
174 fields: nextTimeline,
175 props: { ...nextTimeline, findPositionReaderRef: positionReader },
176 };
177 setTimeline(timeline);
178 }
179 const match = timeline.fields.activeFindMatch;
180 const step = (delta: number) => {
181 if (count === 0 || counting) return;
182 setState((previous) => {
183 const local = rebaseLocalSelection(previous.localSelection, remote.data, remote.navigationId);
184 const pending = previous.navigationId !== (local?.navigationId ?? remote.navigationId);
185 const selected = local?.match ?? remote.data?.match;
186 const nextIndex = stepThreadFindIndex(
187 local?.activeIndex ?? remote.data?.activeIndex ?? 0,
188 count,
189 delta,
190 );
191 const entry = remote.data?.navigation?.find(
192 (entry) => nextIndex >= entry.startIndex && nextIndex < entry.startIndex + entry.count,
193 );
194 const nextNavigationId = previous.navigationId + 1;
195 if (
196 !pending &&
197 !remote.isPending &&
198 entry &&
199 remote.data &&
200 (!local ||
201 local.base === remote.data ||
202 remote.data.navigation?.some(
203 (entry) =>
204 entry.entryId === local.match.entryId && local.match.occurrence < entry.count,
205 )) &&
206 refreshTimerRef.current === null &&
207 lastContentRef.current === content
208 ) {
209 return {
210 ...previous,
211 navigationId: nextNavigationId,
212 localSelection: {
213 base: remote.data,
214 baseNavigationId: remote.navigationId,
215 activeIndex: nextIndex,
216 match: {
217 entryId: entry.entryId,
218 runId: entry.runId,
219 occurrence: nextIndex - entry.startIndex,
220 },
221 navigationId: nextNavigationId,
222 },
223 };
224 }
225 return {
226 ...previous,
227 start:
228 pending || !selected
229 ? previous.start
230 : { entryId: selected.entryId, occurrence: selected.occurrence },
231 offset: pending ? previous.offset + delta : delta,
232 navigationId: nextNavigationId,
233 requestId: nextNavigationId,
234 };
235 });
236 };
237
238 const refreshLiveResultsRef = useRef(() => {});
239 useLayoutEffect(() => {
240 refreshLiveResultsRef.current = () => {
241 if (!isOpen || !state.query.trim()) return;
242 // Coalesce paging updates while the server counts to avoid restarting scans.
243 if (progressive && remote.isPending) {
244 refreshAfterSearchRef.current = true;
245 return;
246 }
247 if (!match || state.navigationId !== navigationId) {
248 remote.refresh();
249 return;
250 }
251 const start = { entryId: match.entryId, occurrence: match.occurrence };
252 if (
253 state.offset === 0 &&
254 state.start?.entryId === start.entryId &&
255 state.start.occurrence === start.occurrence &&
256 state.requestId === state.navigationId
257 ) {
258 remote.refresh();
259 } else {
260 setState((previous) => ({
261 ...previous,
262 start,
263 offset: 0,
264 requestId: previous.navigationId,
265 }));
266 }
267 };
268 });
269 useEffect(() => {
270 if (!refreshAfterSearchRef.current || remote.isPending) return;
271 refreshAfterSearchRef.current = false;
272 if (!remote.error) refreshLiveResultsRef.current();
273 }, [remote.isPending, remote.error]);
274 useEffect(() => {
275 if (lastContentRef.current === content) return;
276 lastContentRef.current = content;
277 if (!isOpen || !state.query.trim() || refreshTimerRef.current !== null) return;
278 refreshTimerRef.current = setTimeout(() => {
279 refreshTimerRef.current = null;
280 refreshLiveResultsRef.current();
281 }, 300);
282 }, [content, isOpen, state.query]);
283 useEffect(() => {
284 if (!isOpen || threadKey === null || !state.query.trim()) return;
285 return () => {
286 if (refreshTimerRef.current !== null) clearTimeout(refreshTimerRef.current);
287 refreshTimerRef.current = null;
288 refreshAfterSearchRef.current = false;
289 };
290 }, [threadKey, isOpen, state.query]);
291
292 return {
293 isOpen,
294 open,
295 close,
296 barProps: {
297 open: isOpen,
298 query: state.query,
299 matchCount: count,
300 counting,
301 activeIndex,
302 status,
303 focusRequestId: state.focusRequestId,
304 onRetry: remote.refresh,
305 onQueryChange: (query: string) => {
306 const start = positionReader.current?.(query.trim());
307 setState((previous) => ({
308 ...previous,
309 query,
310 offset: 0,
311 start,
312 localSelection: null,
313 navigationId: previous.navigationId + 1,
314 requestId: previous.navigationId + 1,
315 }));
316 },
317 onNext: () => step(1),
318 onPrevious: () => step(-1),
319 onClose: close,
320 },
321 timelineProps: timeline.props,
322 };
323}
324
325type TimelineFields = Omit<
326 ReturnType<typeof useThreadFind>["timelineProps"],
327 "findPositionReaderRef"
328>;
329
330function sameTimeline(a: TimelineFields, b: TimelineFields) {
331 const aMatch = a.activeFindMatch;
332 const bMatch = b.activeFindMatch;
333 return (
334 a.findOpen === b.findOpen &&
335 a.findExpanded === b.findExpanded &&
336 a.findQuery === b.findQuery &&
337 a.findNavigationId === b.findNavigationId &&
338 (aMatch === null || bMatch === null
339 ? aMatch === bMatch
340 : aMatch.entryId === bMatch.entryId &&
341 aMatch.runId === bMatch.runId &&
342 aMatch.occurrence === bMatch.occurrence)
343 );
344}
345
346function rebaseLocalSelection(
347 selection: typeof CLOSED_FIND.localSelection,
348 data: OrchestrationV2SearchThreadResult | null,
349 navigationId: number,
350) {
351 if (!selection || !data) return null;
352 if (selection.base === data && selection.baseNavigationId === navigationId) return selection;
353 if (navigationId >= selection.navigationId) return null;
354 const entry = data.navigation?.find((entry) => entry.entryId === selection.match.entryId);
355 if (!entry || selection.match.occurrence >= entry.count) return selection;
356 const activeIndex = entry.startIndex + selection.match.occurrence;
357 return activeIndex === selection.activeIndex ? selection : { ...selection, activeIndex };
358}
359
360function useServerResults(
361 thread: ScopedThreadRef | null,
362 query: string,
363 offset: number,
364 navigationId: number,
365 start: ThreadFindStart | undefined,
366 skills: readonly InlineSkill[],
367 progressive: boolean,
368) {
369 const skillLabels = skills.map(({ name, displayName }) => ({ name, displayName }));
370 const normalizedQuery = query.trim();
371 const debouncedQuery = useDebouncedValue(normalizedQuery, 100);
372 const environmentId = thread?.environmentId;
373 const threadId = thread?.threadId;
374 const target =
375 environmentId && threadId && debouncedQuery && normalizedQuery === debouncedQuery
376 ? {
377 environmentId,
378 input: {
379 threadId,
380 query: debouncedQuery,
381 ...(start ? { start } : {}),
382 ...(offset !== 0 ? { offset } : {}),
383 skills: skillLabels,
384 },
385 }
386 : null;
387 const targetKey = target ? JSON.stringify([progressive, target]) : null;
388 const [storedAtom, setStoredAtom] = useState(() => ({
389 key: targetKey,
390 atom: resolveThreadFindAtom(target, progressive),
391 }));
392 let atom = storedAtom.atom;
393 if (storedAtom.key !== targetKey) {
394 atom = resolveThreadFindAtom(target, progressive);
395 setStoredAtom({ key: targetKey, atom });
396 }
397 const result = useEnvironmentQuery(atom);
398 const key = thread
399 ? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels])
400 : null;
401 const [previous, setPrevious] = useState({
402 key,
403 data: result.data,
404 navigationId,
405 });
406 if (
407 previous.key !== key ||
408 (result.data !== null &&
409 (!result.isPending || (progressive && previous.data !== result.data)) &&
410 (previous.data !== result.data || previous.navigationId !== navigationId))
411 ) {
412 const response = result.data;
413 setPrevious({
414 key,
415 data: response,
416 navigationId,
417 });
418 }
419 return {
420 ...result,
421 data: key === previous.key && !result.error ? previous.data : null,
422 navigationId: previous.navigationId,
423 isPending:
424 thread !== null &&
425 normalizedQuery.length > 0 &&
426 (normalizedQuery !== debouncedQuery || result.isPending),
427 };
428}
429
430function resolveThreadFindAtom(
431 target: Parameters<typeof orchestrationEnvironment.threadFind>[0] | null,
432 progressive: boolean,
433) {
434 if (!target) return null;
435 return progressive
436 ? orchestrationEnvironment.threadFindProgressive(target)
437 : orchestrationEnvironment.threadFind(target);
438}