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 type EnvironmentThreadSearchMatch,
10} from "@t3tools/client-runtime/state/thread-search";
11import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
12import type {
13 EnvironmentId,
14 ProjectContentMatch,
15 ProjectEntryKind,
16 VcsListRefsResult,
17 VcsRef,
18} from "@t3tools/contracts";
19import * as Cause from "effect/Cause";
20import * as Option from "effect/Option";
21import { AsyncResult, Atom } from "effect/unstable/reactivity";
22import { useCallback, useEffect, useMemo, useState } from "react";
23
24import { appAtomRegistry } from "../rpc/atomRegistry";
25import { orchestrationEnvironment } from "./orchestration";
26import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
27import { projectContentSearch, projectEnvironment } from "./projects";
28import { useEnvironmentQuery } from "./query";
29import { vcsEnvironment } from "./vcs";
30
31const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120;
32const COMPOSER_PATH_SEARCH_LIMIT = 80;
33const PROJECT_CONTENT_SEARCH_DEBOUNCE_MS = 120;
34const PROJECT_CONTENT_SEARCH_LIMIT = 500;
35const THREAD_SEARCH_DEBOUNCE_MS = 200;
36const VCS_REF_LIST_LIMIT = 100;
37const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
38const EMPTY_CONTENT_MATCHES: ReadonlyArray<ProjectContentMatch> = [];
39const INITIAL_BRANCH_CURSORS = [undefined] as const;
40const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
41const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
42 matches: EMPTY_THREAD_SEARCH_MATCHES,
43 isLoading: false,
44}).pipe(Atom.withLabel("web:thread-search:empty"));
45
46const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
47 getSearchAtom: (environmentId, query) =>
48 orchestrationEnvironment.threadSearch({
49 environmentId,
50 input: { query },
51 }),
52 labelPrefix: "web:thread-search",
53});
54
55export function useDebouncedValue<A>(value: A, delayMs: number): A {
56 const [debounced, setDebounced] = useState(value);
57
58 useEffect(() => {
59 const timer = window.setTimeout(() => {
60 setDebounced(value);
61 }, delayMs);
62 return () => {
63 window.clearTimeout(timer);
64 };
65 }, [delayMs, value]);
66
67 return debounced;
68}
69
70export function useThreadSearch(
71 environmentIds: ReadonlyArray<EnvironmentId>,
72 query: string,
73): {
74 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
75 /** The settled query `matches` came from; it only changes when results do. */
76 readonly query: string;
77 readonly isPending: boolean;
78} {
79 const normalizedQuery = query.trim();
80 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
81 const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
82 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
83 const searchKey = useMemo(
84 () => (settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery)),
85 [environmentIds, settledQuery],
86 );
87 const result = useAtomValue(
88 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
89 );
90 const isDebouncing = canSearch && normalizedQuery !== debouncedQuery;
91 return {
92 matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches,
93 query: settledQuery ?? "",
94 isPending: canSearch && (isDebouncing || result.isLoading),
95 };
96}
97
98export function usePaginatedBranches(target: VcsRefTarget) {
99 const query = target.query?.trim() ?? "";
100 const targetKey =
101 target.environmentId !== null && target.cwd !== null
102 ? JSON.stringify([target.environmentId, target.cwd, query])
103 : null;
104 const [pagination, setPagination] = useState<{
105 readonly targetKey: string | null;
106 readonly cursors: ReadonlyArray<number | undefined>;
107 }>({
108 targetKey,
109 cursors: INITIAL_BRANCH_CURSORS,
110 });
111 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
112 const pageAtoms = useMemo(
113 () =>
114 target.environmentId !== null && target.cwd !== null
115 ? cursors.map((cursor) =>
116 vcsEnvironment.listRefs({
117 environmentId: target.environmentId!,
118 input: {
119 cwd: target.cwd!,
120 ...(query.length > 0 ? { query } : {}),
121 ...(cursor === undefined ? {} : { cursor }),
122 limit: VCS_REF_LIST_LIMIT,
123 },
124 }),
125 )
126 : [],
127 [cursors, query, target.cwd, target.environmentId],
128 );
129 const pagesAtom = useMemo(
130 () =>
131 Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
132 Atom.withLabel(`web:vcs-ref-pages:${targetKey ?? "empty"}`),
133 ),
134 [pageAtoms, targetKey],
135 );
136 const results = useAtomValue(pagesAtom);
137 const values = results.flatMap((result) => {
138 const value = Option.getOrNull(AsyncResult.value(result));
139 return value === null ? [] : [value];
140 });
141 const refs = new Map<string, VcsRef>();
142 for (const value of values) {
143 for (const ref of value.refs) {
144 refs.set(ref.name, ref);
145 }
146 }
147 const first = values[0] ?? null;
148 const last = values.at(-1) ?? null;
149 const data: VcsListRefsResult | null =
150 first === null || last === null
151 ? null
152 : {
153 refs: [...refs.values()],
154 isRepo: first.isRepo,
155 hasPrimaryRemote: first.hasPrimaryRemote,
156 nextCursor: last.nextCursor,
157 totalCount: Math.max(...values.map((value) => value.totalCount)),
158 };
159 const failed = results.find((result) => result._tag === "Failure");
160 const isFetchingNextPage = isPaginatedBranchesNextPagePending(results);
161 const error =
162 failed?._tag === "Failure"
163 ? (() => {
164 const cause = Cause.squash(failed.cause);
165 return cause instanceof Error && cause.message.trim().length > 0
166 ? cause.message
167 : "Failed to load refs.";
168 })()
169 : null;
170 const refresh = useCallback(() => {
171 const firstPage = pageAtoms[0];
172 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
173 if (firstPage !== undefined) {
174 appAtomRegistry.refresh(firstPage);
175 }
176 }, [pageAtoms, targetKey]);
177 const loadNext = useCallback(() => {
178 if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {
179 return;
180 }
181 setPagination((current) => {
182 const currentCursors =
183 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
184 return currentCursors.includes(data.nextCursor!)
185 ? { targetKey, cursors: currentCursors }
186 : { targetKey, cursors: [...currentCursors, data.nextCursor!] };
187 });
188 }, [data?.nextCursor, targetKey]);
189
190 return {
191 data,
192 refs: data?.refs ?? EMPTY_REFS,
193 error,
194 isPending: results.some((result) => result.waiting),
195 isFetchingNextPage,
196 refresh,
197 loadNext,
198 };
199}
200
201type ProjectPathSearchTarget = ComposerPathSearchTarget & {
202 readonly kind?: ProjectEntryKind | undefined;
203 readonly imageOnly?: boolean | undefined;
204};
205
206export function areProjectPathSearchTargetsEqual(
207 left: ProjectPathSearchTarget,
208 right: ProjectPathSearchTarget,
209): boolean {
210 return (
211 left.environmentId === right.environmentId &&
212 left.cwd === right.cwd &&
213 left.query === right.query &&
214 left.kind === right.kind &&
215 left.imageOnly === right.imageOnly
216 );
217}
218
219export function useProjectPathSearch(
220 target: ProjectPathSearchTarget,
221 limit: number,
222 options?: { readonly allowEmptyQuery?: boolean },
223) {
224 const allowEmptyQuery = options?.allowEmptyQuery === true;
225 const normalizedTarget = useMemo(
226 () => ({
227 environmentId: target.environmentId,
228 cwd: target.cwd,
229 query: target.query == null ? null : target.query.trim(),
230 kind: target.kind,
231 imageOnly: target.imageOnly,
232 }),
233 [target.cwd, target.environmentId, target.imageOnly, target.kind, target.query],
234 );
235 const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
236 const result = useEnvironmentQuery(
237 debouncedTarget.environmentId !== null &&
238 debouncedTarget.cwd !== null &&
239 debouncedTarget.query !== null &&
240 (allowEmptyQuery || debouncedTarget.query.length > 0)
241 ? projectEnvironment.searchEntries({
242 environmentId: debouncedTarget.environmentId,
243 input: {
244 cwd: debouncedTarget.cwd,
245 query: debouncedTarget.query,
246 limit,
247 ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
248 ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
249 },
250 })
251 : null,
252 );
253
254 return {
255 entries: result.data?.entries ?? [],
256 error: result.error,
257 isPending:
258 !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) || result.isPending,
259 searchedQuery: debouncedTarget.query ?? "",
260 truncated: result.data?.truncated ?? false,
261 refresh: result.refresh,
262 };
263}
264
265export function useComposerPathSearch(target: ComposerPathSearchTarget) {
266 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
267}
268
269interface ProjectContentSearchTarget {
270 readonly environmentId: EnvironmentId | null;
271 readonly cwd: string | null;
272 readonly query: string;
273 readonly caseSensitive: boolean;
274 readonly wholeWord: boolean;
275 readonly useRegex: boolean;
276}
277
278export function useProjectContentSearch(target: ProjectContentSearchTarget) {
279 // Whitespace is significant in content queries; trimming is only used to
280 // decide whether the input is blank.
281 const query = target.query;
282 const hasQuery = query.trim().length > 0;
283 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
284 const result = useEnvironmentQuery(
285 target.environmentId !== null &&
286 target.cwd !== null &&
287 hasQuery &&
288 debouncedQuery.trim().length > 0
289 ? projectContentSearch({
290 environmentId: target.environmentId,
291 input: {
292 cwd: target.cwd,
293 query: debouncedQuery,
294 limit: PROJECT_CONTENT_SEARCH_LIMIT,
295 caseSensitive: target.caseSensitive,
296 wholeWord: target.wholeWord,
297 useRegex: target.useRegex,
298 },
299 })
300 : null,
301 );
302
303 return {
304 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
305 error: result.error,
306 isPending: hasQuery && (query !== debouncedQuery || result.isPending),
307 hasQuery,
308 truncated: result.data?.truncated ?? false,
309 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
310 };
311}
312
313export function useCheckpointDiff(
314 target: CheckpointDiffTarget,
315 options?: { readonly enabled?: boolean },
316) {
317 const enabled =
318 options?.enabled !== false &&
319 target.environmentId !== null &&
320 target.threadId !== null &&
321 target.fromTurnCount !== null &&
322 target.toTurnCount !== null;
323 const fullThreadTarget =
324 enabled && target.fromTurnCount === 0
325 ? {
326 environmentId: target.environmentId!,
327 input: {
328 threadId: target.threadId!,
329 toTurnCount: target.toTurnCount!,
330 ignoreWhitespace: target.ignoreWhitespace,
331 },
332 }
333 : null;
334 const turnTarget =
335 enabled && target.fromTurnCount !== 0
336 ? {
337 environmentId: target.environmentId!,
338 input: {
339 threadId: target.threadId!,
340 fromTurnCount: target.fromTurnCount!,
341 toTurnCount: target.toTurnCount!,
342 ignoreWhitespace: target.ignoreWhitespace,
343 },
344 }
345 : null;
346 const fullThread = useEnvironmentQuery(
347 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
348 );
349 const turn = useEnvironmentQuery(
350 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
351 );
352 return fullThreadTarget === null ? turn : fullThread;
353}