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