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 { AsyncResult, Atom } from "effect/reactivity";
31import { useEffect, useState } from "react";
32
33import { appAtomRegistry } from "../rpc/atomRegistry";
34import { useFilesystemReadAccess } from "./filesystem";
35import { orchestrationEnvironment } from "./orchestration";
36import { olderSettledThreads, threadFamilies } from "./threads";
37import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
38import { projectContentSearch, projectEnvironment } from "./projects";
39import { useEnvironmentQuery } from "./query";
40import { vcsEnvironment } from "./vcs";
41
42const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120;
43const COMPOSER_PATH_SEARCH_LIMIT = 80;
44const PROJECT_CONTENT_SEARCH_DEBOUNCE_MS = 120;
45const PROJECT_CONTENT_SEARCH_LIMIT = 500;
46const THREAD_SEARCH_DEBOUNCE_MS = 120;
47const VCS_REF_LIST_LIMIT = 100;
48const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
49const EMPTY_PROJECT_ENTRIES: ReadonlyArray<ProjectEntry> = [];
50const EMPTY_CONTENT_MATCHES: ReadonlyArray<ProjectContentMatch> = [];
51const INITIAL_BRANCH_CURSORS = [undefined] as const;
52const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
53const EMPTY_THREAD_SEARCH_ATOM = Atom.make<ThreadSearchResultsState>({
54 matches: EMPTY_THREAD_SEARCH_MATCHES,
55 isLoading: false,
56 rows: [],
57}).pipe(Atom.withLabel("web:thread-search:empty"));
58
59const olderSettledBeforeAtom = Atom.family((environmentId: EnvironmentId) =>
60 Atom.make((get) => get(olderSettledThreads.olderSettledAtom(environmentId))?.before ?? null).pipe(
61 Atom.withLabel(`web:older-settled-before:${environmentId}`),
62 ),
63);
64// Whether any of these environments leaves older settled threads out, so short queries matter.
65const anyOlderSettledAtom = Atom.family((environmentIdsKey: string) =>
66 Atom.make((get) =>
67 (JSON.parse(environmentIdsKey) as ReadonlyArray<EnvironmentId>).some(
68 (environmentId) => get(olderSettledBeforeAtom(environmentId)) !== null,
69 ),
70 ).pipe(Atom.withLabel(`web:any-older-settled:${environmentIdsKey}`)),
71);
72const threadSearch = createThreadSearchResultsAtomFamily({
73 getSearchAtom: (environmentId, input) =>
74 input.olderSettledBefore === undefined
75 ? orchestrationEnvironment.threadSearch({ environmentId, input })
76 : olderSettledThreads.searchAtom(environmentId, input),
77 olderSettledBefore: olderSettledBeforeAtom,
78 labelPrefix: "web:thread-search",
79});
80
81export function useDebouncedValue<A>(value: A, delayMs: number): A {
82 const [debounced, setDebounced] = useState(value);
83
84 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- debounce timer that publishes the value after delayMs
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 // 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
144 useEffect(() => {
145 if (shownKey === null) return;
146 const environments = (JSON.parse(shownKey) as [ReadonlyArray<EnvironmentId>])[0];
147 const releases = environments.map((environmentId) =>
148 threadFamilies.mountRows(
149 appAtomRegistry,
150 environmentId,
151 `search:${shownKey}`,
152 threadSearch.rows(shownKey, environmentId),
153 ),
154 );
155 return () => {
156 for (const release of releases) release();
157 };
158 }, [shownKey]);
159 return {
160 matches: visible.matches,
161 query: visible.query,
162 isPending,
163 };
164}
165
166function vcsRefPageAtom(targetKey: string, cursor: number | undefined) {
167 const [environmentId, cwd, query] = JSON.parse(targetKey) as [EnvironmentId, string, string];
168 return vcsEnvironment.listRefs({
169 environmentId,
170 input: {
171 cwd,
172 ...(query.length > 0 ? { query } : {}),
173 ...(cursor === undefined ? {} : { cursor }),
174 limit: VCS_REF_LIST_LIMIT,
175 },
176 });
177}
178
179const EMPTY_VCS_REF_PAGES_ATOM = Atom.make<
180 ReadonlyArray<Atom.Type<ReturnType<typeof vcsRefPageAtom>>>
181>([]).pipe(Atom.withLabel("web:vcs-ref-pages:empty"));
182
183const vcsRefPagesAtom = Atom.family((pagesKey: string) => {
184 const [targetKey, cursors] = JSON.parse(pagesKey) as [string, Array<number | null>];
185 const pageAtoms = cursors.map((cursor) => vcsRefPageAtom(targetKey, cursor ?? undefined));
186 return Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
187 Atom.withLabel(`web:vcs-ref-pages:${pagesKey}`),
188 );
189});
190
191export function usePaginatedBranches(target: VcsRefTarget) {
192 // Leave unkeyed; mismatches already reset cursors, and a seeded key would break caching across the hook.
193 const [pagination, setPagination] = useState<{
194 readonly targetKey: string | null;
195 readonly cursors: ReadonlyArray<number | undefined>;
196 }>({
197 targetKey: null,
198 cursors: INITIAL_BRANCH_CURSORS,
199 });
200 const { environmentId, cwd } = target;
201 const query = target.query?.trim() ?? "";
202 const targetKey =
203 environmentId !== null && cwd !== null ? JSON.stringify([environmentId, cwd, query]) : null;
204 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
205 const pagesKey = targetKey === null ? null : JSON.stringify([targetKey, cursors]);
206 const results = useAtomValue(
207 pagesKey === null ? EMPTY_VCS_REF_PAGES_ATOM : vcsRefPagesAtom(pagesKey),
208 );
209 const values = results.flatMap((result) => {
210 const value = AsyncResult.getOrElse(result, () => null);
211 return value === null ? [] : [value];
212 });
213 const refs = new Map<string, VcsRef>();
214 for (const value of values) {
215 for (const ref of value.refs) {
216 refs.set(ref.name, ref);
217 }
218 }
219 const first = values[0] ?? null;
220 const last = values.at(-1) ?? null;
221 const data: VcsListRefsResult | null =
222 first === null || last === null
223 ? null
224 : {
225 refs: [...refs.values()],
226 isRepo: first.isRepo,
227 hasPrimaryRemote: first.hasPrimaryRemote,
228 nextCursor: last.nextCursor,
229 totalCount: Math.max(...values.map((value) => value.totalCount)),
230 };
231 const failed = results.find((result) => result._tag === "Failure");
232 const isFetchingNextPage = isPaginatedBranchesNextPagePending(results);
233 const error =
234 failed?._tag === "Failure"
235 ? (() => {
236 const cause = Cause.squash(failed.cause);
237 return cause instanceof Error && cause.message.trim().length > 0
238 ? cause.message
239 : "Failed to load refs.";
240 })()
241 : null;
242 const refresh = () => {
243 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
244 if (targetKey !== null) {
245 appAtomRegistry.refresh(vcsRefPageAtom(targetKey, undefined));
246 }
247 };
248 const nextCursor = data?.nextCursor;
249 const loadNext = () => {
250 if (targetKey === null || nextCursor === null || nextCursor === undefined) {
251 return;
252 }
253 setPagination((current) => {
254 const currentCursors =
255 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
256 return currentCursors.includes(nextCursor)
257 ? { targetKey, cursors: currentCursors }
258 : { targetKey, cursors: [...currentCursors, nextCursor] };
259 });
260 };
261
262 return {
263 data,
264 refs: data?.refs ?? EMPTY_REFS,
265 error,
266 isPending: results.some((result) => result.waiting),
267 isFetchingNextPage,
268 refresh,
269 loadNext,
270 };
271}
272
273type ProjectPathSearchTarget = ComposerPathSearchTarget & {
274 readonly kind?: ProjectEntryKind | undefined;
275 readonly imageOnly?: boolean | undefined;
276};
277
278function areProjectPathSearchTargetsEqual(
279 left: ProjectPathSearchTarget,
280 right: ProjectPathSearchTarget,
281): boolean {
282 return (
283 left.environmentId === right.environmentId &&
284 left.cwd === right.cwd &&
285 left.query === right.query &&
286 left.kind === right.kind &&
287 left.imageOnly === right.imageOnly
288 );
289}
290
291export function useProjectPathSearch(
292 target: ProjectPathSearchTarget,
293 limit: number,
294 options?: { readonly allowEmptyQuery?: boolean },
295) {
296 const allowEmptyQuery = options?.allowEmptyQuery === true;
297 const normalizedTarget = {
298 environmentId: target.environmentId,
299 cwd: target.cwd,
300 query: target.query == null ? null : target.query.trim(),
301 kind: target.kind,
302 imageOnly: target.imageOnly,
303 };
304 const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
305 const fileAccess = useFilesystemReadAccess(debouncedTarget.environmentId);
306 const { canReadFiles } = fileAccess;
307 const searchTarget =
308 debouncedTarget.environmentId !== null &&
309 debouncedTarget.cwd !== null &&
310 debouncedTarget.query !== null &&
311 (allowEmptyQuery || debouncedTarget.query.length > 0)
312 ? {
313 environmentId: debouncedTarget.environmentId,
314 input: {
315 cwd: debouncedTarget.cwd,
316 query: debouncedTarget.query.slice(0, 256).replace(/[\uD800-\uDBFF]$/, ""),
317 limit,
318 ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
319 ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
320 },
321 }
322 : null;
323 const result = useEnvironmentQuery(
324 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
325 );
326 const hasTarget = searchTarget !== null;
327
328 return {
329 entries: result.data?.entries ?? EMPTY_PROJECT_ENTRIES,
330 error:
331 !hasTarget || fileAccess.isPending
332 ? null
333 : canReadFiles
334 ? result.error
335 : (fileAccess.error ?? "This connection cannot search host files."),
336 isPending:
337 !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) ||
338 (hasTarget && (fileAccess.isPending || result.isPending)),
339 searchedTarget: debouncedTarget,
340 searchedQuery: debouncedTarget.query ?? "",
341 truncated: result.data?.truncated ?? false,
342 refresh: result.refresh,
343 };
344}
345
346export function useComposerPathSearch(target: ComposerPathSearchTarget) {
347 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
348}
349
350interface ProjectContentSearchTarget {
351 readonly environmentId: EnvironmentId | null;
352 readonly cwd: string | null;
353 readonly query: string;
354 readonly caseSensitive: boolean;
355 readonly wholeWord: boolean;
356 readonly useRegex: boolean;
357}
358
359export function useProjectContentSearch(target: ProjectContentSearchTarget) {
360 const hasTarget = target.environmentId !== null && target.cwd !== null;
361 const fileAccess = useFilesystemReadAccess(target.environmentId);
362 const canReadFiles = hasTarget && fileAccess.canReadFiles;
363 const isCheckingAccess = hasTarget && fileAccess.isPending;
364 // Preserve query whitespace; trim only to detect blank input.
365 const query = target.query;
366 const hasQuery = query.trim().length > 0;
367 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
368 const result = useEnvironmentQuery(
369 canReadFiles &&
370 target.environmentId !== null &&
371 target.cwd !== null &&
372 hasQuery &&
373 debouncedQuery.trim().length > 0
374 ? projectContentSearch({
375 environmentId: target.environmentId,
376 input: {
377 cwd: target.cwd,
378 query: debouncedQuery,
379 limit: PROJECT_CONTENT_SEARCH_LIMIT,
380 caseSensitive: target.caseSensitive,
381 wholeWord: target.wholeWord,
382 useRegex: target.useRegex,
383 },
384 })
385 : null,
386 );
387
388 return {
389 canReadFiles,
390 isCheckingAccess,
391 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
392 error:
393 !hasTarget || isCheckingAccess
394 ? null
395 : canReadFiles
396 ? result.error
397 : (fileAccess.error ?? "This connection cannot search host files."),
398 isPending:
399 isCheckingAccess ||
400 (canReadFiles && hasQuery && (query !== debouncedQuery || result.isPending)),
401 hasQuery,
402 truncated: result.data?.truncated ?? false,
403 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
404 };
405}
406
407export function useCheckpointDiff(
408 target: CheckpointDiffTarget,
409 options?: { readonly enabled?: boolean },
410) {
411 const enabled =
412 options?.enabled !== false &&
413 target.environmentId !== null &&
414 target.threadId !== null &&
415 target.fromTurnCount !== null &&
416 target.toTurnCount !== null;
417 const fullThreadTarget =
418 enabled && target.fromTurnCount === 0
419 ? {
420 environmentId: target.environmentId!,
421 input: {
422 threadId: target.threadId!,
423 toTurnCount: target.toTurnCount!,
424 ignoreWhitespace: target.ignoreWhitespace,
425 },
426 }
427 : null;
428 const turnTarget =
429 enabled && target.fromTurnCount !== 0
430 ? {
431 environmentId: target.environmentId!,
432 input: {
433 threadId: target.threadId!,
434 fromTurnCount: target.fromTurnCount!,
435 toTurnCount: target.toTurnCount!,
436 ignoreWhitespace: target.ignoreWhitespace,
437 },
438 }
439 : null;
440 const fullThread = useEnvironmentQuery(
441 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
442 );
443 const turn = useEnvironmentQuery(
444 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
445 );
446 return fullThreadTarget === null ? turn : fullThread;
447}
448
449/** Reads one item's detail from somewhere other than the environment, as the guest page does. */
450export type TurnItemDetailSource = (input: {
451 readonly threadId: ThreadId;
452 readonly itemId: TurnItemId;
453 readonly revision: string;
454}) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2GetTurnItemResult, unknown>>;
455
456export function useTurnItemDetail(
457 target: {
458 readonly environmentId: EnvironmentId;
459 readonly threadId: ThreadId;
460 readonly itemId: TurnItemId;
461 readonly revision: string;
462 } | null,
463 source?: TurnItemDetailSource,
464) {
465 const input =
466 target === null
467 ? null
468 : { threadId: target.threadId, itemId: target.itemId, revision: target.revision };
469 return useEnvironmentQuery<OrchestrationV2GetTurnItemResult, unknown>(
470 target === null || input === null
471 ? null
472 : source
473 ? source(input)
474 : orchestrationEnvironment.turnItem({ environmentId: target.environmentId, input }),
475 );
476}