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