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