Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 type CheckpointDiffTarget,
4 type ComposerPathSearchTarget,
5} from "@t3tools/client-runtime/state/threads";
6import {
7 createThreadSearchResultsAtomFamily,
8 makeThreadSearchKey,
9 visibleThreadSearch,
10 type EnvironmentThreadSearchMatch,
11 type SettledThreadSearch,
12 type ThreadSearchResultsState,
13 type ThreadSearchScope,
14} from "@t3tools/client-runtime/state/thread-search";
15import {
16 ProjectSearchContentsError,
17 PROJECT_SEARCH_CONTENTS_QUERY_MAX_LENGTH,
18 THREAD_SEARCH_QUERY_MAX_LENGTH,
19} from "@t3tools/contracts";
20import { messageSearchTokens } from "@t3tools/shared/paletteSearch";
21import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
22import type {
23 EnvironmentId,
24 OrchestrationV2GetTurnItemResult,
25 ProjectContentMatch,
26 ProjectEntry,
27 ProjectEntryKind,
28 ThreadId,
29 TurnItemId,
30 VcsListRefsResult,
31 VcsRef,
32} from "@t3tools/contracts";
33import * as Cause from "effect/Cause";
34import * as Schema from "effect/Schema";
35import { AsyncResult, Atom } from "effect/reactivity";
36import { useEffect, useState } from "react";
37
38import { appAtomRegistry } from "../rpc/atomRegistry";
39import { useFilesystemReadAccess } from "./filesystem";
40import { orchestrationEnvironment } from "./orchestration";
41import { olderSettledThreads, threadFamilies } from "./threads";
42import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
43import { projectContentSearch, projectEnvironment } from "./projects";
44import { useEnvironmentQuery } from "./query";
45import { vcsEnvironment } from "./vcs";
46
47const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120;
48const COMPOSER_PATH_SEARCH_LIMIT = 80;
49const PROJECT_CONTENT_SEARCH_DEBOUNCE_MS = 120;
50const PROJECT_CONTENT_SEARCH_LIMIT = 500;
51const PROJECT_CONTENT_SEARCH_SCAN_RETRY_MS = 30_000;
52const isProjectSearchContentsError = Schema.is(ProjectSearchContentsError);
53const THREAD_SEARCH_DEBOUNCE_MS = 120;
54const VCS_REF_LIST_LIMIT = 100;
55const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
56const EMPTY_PROJECT_ENTRIES: ReadonlyArray<ProjectEntry> = [];
57const EMPTY_CONTENT_MATCHES: ReadonlyArray<ProjectContentMatch> = [];
58const INITIAL_BRANCH_CURSORS = [undefined] as const;
59const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
60const EMPTY_THREAD_SEARCH_ATOM = Atom.make<ThreadSearchResultsState>({
61 matches: EMPTY_THREAD_SEARCH_MATCHES,
62 isLoading: false,
63 rows: [],
64}).pipe(Atom.withLabel("web:thread-search:empty"));
65
66const olderSettledBeforeAtom = Atom.family((environmentId: EnvironmentId) =>
67 Atom.make((get) => get(olderSettledThreads.olderSettledAtom(environmentId))?.before ?? null).pipe(
68 Atom.withLabel(`web:older-settled-before:${environmentId}`),
69 ),
70);
71// Whether any of these environments leaves older settled threads out, so short queries matter.
72const anyOlderSettledAtom = Atom.family((environmentIdsKey: string) =>
73 Atom.make((get) =>
74 (JSON.parse(environmentIdsKey) as ReadonlyArray<EnvironmentId>).some(
75 (environmentId) => get(olderSettledBeforeAtom(environmentId)) !== null,
76 ),
77 ).pipe(Atom.withLabel(`web:any-older-settled:${environmentIdsKey}`)),
78);
79const threadSearch = createThreadSearchResultsAtomFamily({
80 getSearchAtom: (environmentId, input) =>
81 input.olderSettledBefore === undefined
82 ? orchestrationEnvironment.threadSearch({ environmentId, input })
83 : olderSettledThreads.searchAtom(environmentId, input),
84 olderSettledBefore: olderSettledBeforeAtom,
85 labelPrefix: "web:thread-search",
86});
87
88export function useDebouncedValue<A>(value: A, delayMs: number): A {
89 const [debounced, setDebounced] = useState(value);
90
91 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- debounce timer that publishes the value after delayMs
92 useEffect(() => {
93 const timer = window.setTimeout(() => {
94 setDebounced(value);
95 }, delayMs);
96 return () => {
97 window.clearTimeout(timer);
98 };
99 }, [delayMs, value]);
100
101 return debounced;
102}
103
104/**
105 * Server matches for a thread search: message hits, and on environments that leave older settled
106 * threads out of the shell, the rows of the best older matches, mounted into the thread list while
107 * they show so the caller's own ranking finds them.
108 */
109export function useThreadSearch(
110 environmentIds: ReadonlyArray<EnvironmentId>,
111 query: string,
112 scope: ThreadSearchScope = {},
113): {
114 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
115 readonly query: string;
116 readonly isPending: boolean;
117} {
118 // A pasted wall of text searches by its start rather than failing the request.
119 const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim();
120 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
121 const anyOlderSettled = useAtomValue(anyOlderSettledAtom(JSON.stringify(environmentIds)));
122 // Messages need a word of three or more letters; older settled titles match from two.
123 const canSearch =
124 environmentIds.length > 0 &&
125 ((scope.titlesOnly !== true && messageSearchTokens(normalizedQuery).long.length > 0) ||
126 (anyOlderSettled && normalizedQuery.length >= 2));
127 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
128 const searchKeyOf = (searchQuery: string) =>
129 makeThreadSearchKey(environmentIds, searchQuery, scope);
130 const searchKey = settledQuery === null ? null : searchKeyOf(settledQuery);
131 const result = useAtomValue(
132 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearch.results(searchKey),
133 );
134 const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading);
135 // What fast environments returned shows without waiting for a slow one;
136 // callers keep shown rows in place with `nextShownOrder`.
137 const ready =
138 settledQuery !== null &&
139 (!result.isLoading || result.matches.length > 0 || result.rows.length > 0)
140 ? { query: settledQuery, matches: result.matches }
141 : null;
142 // Kept from earlier renders: React's pattern for information from previous renders.
143 const [previous, setPrevious] = useState<SettledThreadSearch | null>(null);
144 if (ready !== null && previous?.matches !== ready.matches) setPrevious(ready);
145 const visible = canSearch
146 ? visibleThreadSearch(normalizedQuery, ready, previous)
147 : { query: "", matches: EMPTY_THREAD_SEARCH_MATCHES };
148 // The shown results' rows stay mounted until newer results replace them.
149 const shownKey = visible.query === "" ? null : searchKeyOf(visible.query);
150 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mounts the shown search results' rows into the thread family registry until newer results replace them
151 useEffect(() => {
152 if (shownKey === null) return;
153 const environments = (JSON.parse(shownKey) as [ReadonlyArray<EnvironmentId>])[0];
154 const releases = environments.map((environmentId) =>
155 threadFamilies.mountRows(
156 appAtomRegistry,
157 environmentId,
158 `search:${shownKey}`,
159 threadSearch.rows(shownKey, environmentId),
160 ),
161 );
162 return () => {
163 for (const release of releases) release();
164 };
165 }, [shownKey]);
166 return {
167 matches: visible.matches,
168 query: visible.query,
169 isPending,
170 };
171}
172
173function vcsRefPageAtom(targetKey: string, cursor: number | undefined) {
174 const [environmentId, cwd, query] = JSON.parse(targetKey) as [EnvironmentId, string, string];
175 return vcsEnvironment.listRefs({
176 environmentId,
177 input: {
178 cwd,
179 ...(query.length > 0 ? { query } : {}),
180 ...(cursor === undefined ? {} : { cursor }),
181 limit: VCS_REF_LIST_LIMIT,
182 },
183 });
184}
185
186const EMPTY_VCS_REF_PAGES_ATOM = Atom.make<
187 ReadonlyArray<Atom.Type<ReturnType<typeof vcsRefPageAtom>>>
188>([]).pipe(Atom.withLabel("web:vcs-ref-pages:empty"));
189
190const vcsRefPagesAtom = Atom.family((pagesKey: string) => {
191 const [targetKey, cursors] = JSON.parse(pagesKey) as [string, Array<number | null>];
192 const pageAtoms = cursors.map((cursor) => vcsRefPageAtom(targetKey, cursor ?? undefined));
193 return Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
194 Atom.withLabel(`web:vcs-ref-pages:${pagesKey}`),
195 );
196});
197
198export function usePaginatedBranches(target: VcsRefTarget) {
199 // Leave unkeyed; mismatches already reset cursors, and a seeded key would break caching across the hook.
200 const [pagination, setPagination] = useState<{
201 readonly targetKey: string | null;
202 readonly cursors: ReadonlyArray<number | undefined>;
203 }>({
204 targetKey: null,
205 cursors: INITIAL_BRANCH_CURSORS,
206 });
207 const { environmentId, cwd } = target;
208 const query = target.query?.trim() ?? "";
209 const targetKey =
210 environmentId !== null && cwd !== null ? JSON.stringify([environmentId, cwd, query]) : null;
211 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
212 const pagesKey = targetKey === null ? null : JSON.stringify([targetKey, cursors]);
213 const results = useAtomValue(
214 pagesKey === null ? EMPTY_VCS_REF_PAGES_ATOM : vcsRefPagesAtom(pagesKey),
215 );
216 const values = results.flatMap((result) => {
217 const value = AsyncResult.getOrElse(result, () => null);
218 return value === null ? [] : [value];
219 });
220 const refs = new Map<string, VcsRef>();
221 for (const value of values) {
222 for (const ref of value.refs) {
223 refs.set(ref.name, ref);
224 }
225 }
226 const first = values[0] ?? null;
227 const last = values.at(-1) ?? null;
228 const data: VcsListRefsResult | null =
229 first === null || last === null
230 ? null
231 : {
232 refs: [...refs.values()],
233 isRepo: first.isRepo,
234 hasPrimaryRemote: first.hasPrimaryRemote,
235 nextCursor: last.nextCursor,
236 totalCount: Math.max(...values.map((value) => value.totalCount)),
237 };
238 const failed = results.find((result) => result._tag === "Failure");
239 const isFetchingNextPage = isPaginatedBranchesNextPagePending(results);
240 const error =
241 failed?._tag === "Failure"
242 ? (() => {
243 const cause = Cause.squash(failed.cause);
244 return cause instanceof Error && cause.message.trim().length > 0
245 ? cause.message
246 : "Failed to load refs.";
247 })()
248 : null;
249 const refresh = () => {
250 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
251 if (targetKey !== null) {
252 appAtomRegistry.refresh(vcsRefPageAtom(targetKey, undefined));
253 }
254 };
255 const nextCursor = data?.nextCursor;
256 const loadNext = () => {
257 if (targetKey === null || nextCursor === null || nextCursor === undefined) {
258 return;
259 }
260 setPagination((current) => {
261 const currentCursors =
262 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
263 return currentCursors.includes(nextCursor)
264 ? { targetKey, cursors: currentCursors }
265 : { targetKey, cursors: [...currentCursors, nextCursor] };
266 });
267 };
268
269 return {
270 data,
271 refs: data?.refs ?? EMPTY_REFS,
272 error,
273 isPending: results.some((result) => result.waiting),
274 isFetchingNextPage,
275 refresh,
276 loadNext,
277 };
278}
279
280type ProjectPathSearchTarget = ComposerPathSearchTarget & {
281 readonly kind?: ProjectEntryKind | undefined;
282 readonly imageOnly?: boolean | undefined;
283};
284
285function areProjectPathSearchTargetsEqual(
286 left: ProjectPathSearchTarget,
287 right: ProjectPathSearchTarget,
288): boolean {
289 return (
290 left.environmentId === right.environmentId &&
291 left.cwd === right.cwd &&
292 left.query === right.query &&
293 left.kind === right.kind &&
294 left.imageOnly === right.imageOnly
295 );
296}
297
298export function useProjectPathSearch(
299 target: ProjectPathSearchTarget,
300 limit: number,
301 options?: { readonly allowEmptyQuery?: boolean },
302) {
303 const allowEmptyQuery = options?.allowEmptyQuery === true;
304 const normalizedTarget = {
305 environmentId: target.environmentId,
306 cwd: target.cwd,
307 query: target.query == null ? null : target.query.trim(),
308 kind: target.kind,
309 imageOnly: target.imageOnly,
310 };
311 const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
312 const fileAccess = useFilesystemReadAccess(debouncedTarget.environmentId);
313 const { canReadFiles } = fileAccess;
314 const searchTarget =
315 debouncedTarget.environmentId !== null &&
316 debouncedTarget.cwd !== null &&
317 debouncedTarget.query !== null &&
318 (allowEmptyQuery || debouncedTarget.query.length > 0)
319 ? {
320 environmentId: debouncedTarget.environmentId,
321 input: {
322 cwd: debouncedTarget.cwd,
323 query: debouncedTarget.query.slice(0, 256).replace(/[\uD800-\uDBFF]$/, ""),
324 limit,
325 ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
326 ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
327 },
328 }
329 : null;
330 const result = useEnvironmentQuery(
331 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
332 );
333 const hasTarget = searchTarget !== null;
334
335 return {
336 entries: result.data?.entries ?? EMPTY_PROJECT_ENTRIES,
337 error:
338 !hasTarget || fileAccess.isPending
339 ? null
340 : canReadFiles
341 ? result.error
342 : (fileAccess.error ?? "This connection cannot search host files."),
343 isPending:
344 !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) ||
345 (hasTarget && (fileAccess.isPending || result.isPending)),
346 searchedTarget: debouncedTarget,
347 searchedQuery: debouncedTarget.query ?? "",
348 truncated: result.data?.truncated ?? false,
349 refresh: result.refresh,
350 };
351}
352
353export function useComposerPathSearch(target: ComposerPathSearchTarget) {
354 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT, { allowEmptyQuery: true });
355}
356
357interface ProjectContentSearchTarget {
358 readonly environmentId: EnvironmentId | null;
359 readonly cwd: string | null;
360 readonly query: string;
361 readonly caseSensitive: boolean;
362 readonly wholeWord: boolean;
363 readonly useRegex: boolean;
364}
365
366export function useProjectContentSearch(target: ProjectContentSearchTarget) {
367 const hasTarget = target.environmentId !== null && target.cwd !== null;
368 const fileAccess = useFilesystemReadAccess(target.environmentId);
369 const canReadFiles = hasTarget && fileAccess.canReadFiles;
370 const isCheckingAccess = hasTarget && fileAccess.isPending;
371 // Preserve query whitespace; trim only to detect blank input.
372 const query = target.query;
373 const hasQuery = query.trim().length > 0;
374 const queryTooLong = query.length > PROJECT_SEARCH_CONTENTS_QUERY_MAX_LENGTH;
375 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
376 const result = useEnvironmentQuery(
377 canReadFiles &&
378 target.environmentId !== null &&
379 target.cwd !== null &&
380 hasQuery &&
381 !queryTooLong &&
382 debouncedQuery.trim().length > 0 &&
383 debouncedQuery.length <= PROJECT_SEARCH_CONTENTS_QUERY_MAX_LENGTH
384 ? projectContentSearch({
385 environmentId: target.environmentId,
386 input: {
387 cwd: target.cwd,
388 query: debouncedQuery,
389 limit: PROJECT_CONTENT_SEARCH_LIMIT,
390 caseSensitive: target.caseSensitive,
391 wholeWord: target.wholeWord,
392 useRegex: target.useRegex,
393 },
394 })
395 : null,
396 );
397 // Only once the timeout has come back: a refresh restarts a search still in flight.
398 const settledScanTimeout =
399 !result.isPending &&
400 isProjectSearchContentsError(result.failure) &&
401 result.failure.failure === "search_index_scan_timed_out"
402 ? result.failure
403 : null;
404 const { refresh } = result;
405 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- retry timer: nothing tells the client when the server's first scan ends
406 useEffect(() => {
407 if (settledScanTimeout === null) return;
408 const timer = window.setTimeout(refresh, PROJECT_CONTENT_SEARCH_SCAN_RETRY_MS);
409 return () => {
410 window.clearTimeout(timer);
411 };
412 }, [refresh, settledScanTimeout]);
413
414 return {
415 canReadFiles,
416 isCheckingAccess,
417 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
418 error:
419 !hasTarget || isCheckingAccess
420 ? null
421 : !canReadFiles
422 ? (fileAccess.error ?? "This connection cannot search host files.")
423 : queryTooLong
424 ? `Search is limited to ${PROJECT_SEARCH_CONTENTS_QUERY_MAX_LENGTH} characters.`
425 : result.error,
426 isPending:
427 isCheckingAccess ||
428 (canReadFiles && hasQuery && !queryTooLong && (query !== debouncedQuery || result.isPending)),
429 hasQuery,
430 truncated: result.data?.truncated ?? false,
431 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
432 };
433}
434
435export function useCheckpointDiff(
436 target: CheckpointDiffTarget,
437 options?: { readonly enabled?: boolean },
438) {
439 const enabled =
440 options?.enabled !== false &&
441 target.environmentId !== null &&
442 target.threadId !== null &&
443 target.fromTurnCount !== null &&
444 target.toTurnCount !== null;
445 const fullThreadTarget =
446 enabled && target.fromTurnCount === 0
447 ? {
448 environmentId: target.environmentId!,
449 input: {
450 threadId: target.threadId!,
451 toTurnCount: target.toTurnCount!,
452 ignoreWhitespace: target.ignoreWhitespace,
453 },
454 }
455 : null;
456 const turnTarget =
457 enabled && target.fromTurnCount !== 0
458 ? {
459 environmentId: target.environmentId!,
460 input: {
461 threadId: target.threadId!,
462 fromTurnCount: target.fromTurnCount!,
463 toTurnCount: target.toTurnCount!,
464 ignoreWhitespace: target.ignoreWhitespace,
465 },
466 }
467 : null;
468 const fullThread = useEnvironmentQuery(
469 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
470 );
471 const turn = useEnvironmentQuery(
472 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
473 );
474 return fullThreadTarget === null ? turn : fullThread;
475}
476
477/** Reads one item's detail from somewhere other than the environment, as the guest page does. */
478export type TurnItemDetailSource = (input: {
479 readonly threadId: ThreadId;
480 readonly itemId: TurnItemId;
481 readonly revision: string;
482}) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2GetTurnItemResult, unknown>>;
483
484export function useTurnItemDetail(
485 target: {
486 readonly environmentId: EnvironmentId;
487 readonly threadId: ThreadId;
488 readonly itemId: TurnItemId;
489 readonly revision: string;
490 } | null,
491 source?: TurnItemDetailSource,
492) {
493 const input =
494 target === null
495 ? null
496 : { threadId: target.threadId, itemId: target.itemId, revision: target.revision };
497 return useEnvironmentQuery<OrchestrationV2GetTurnItemResult, unknown>(
498 target === null || input === null
499 ? null
500 : source
501 ? source(input)
502 : orchestrationEnvironment.turnItem({ environmentId: target.environmentId, input }),
503 );
504}