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