Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

queries.ts

365 lines12.0 KB

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;
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 };
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 );
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 };
213​
214type ProjectPathSearchTarget = ComposerPathSearchTarget & {
215 readonly kind?: ProjectEntryKind | undefined;
216 readonly imageOnly?: boolean | undefined;
217};
218​
219export function areProjectPathSearchTargetsEqual(
220 left: ProjectPathSearchTarget,
221 right: ProjectPathSearchTarget,
222): boolean {
223 return (
224 left.environmentId === right.environmentId &&
225 left.cwd === right.cwd &&
226 left.query === right.query &&
227 left.kind === right.kind &&
228 left.imageOnly === right.imageOnly
229 );
231​
232export function useProjectPathSearch(
233 target: ProjectPathSearchTarget,
234 limit: number,
235 options?: { readonly allowEmptyQuery?: boolean },
236) {
237 const allowEmptyQuery = options?.allowEmptyQuery === true;
238 const normalizedTarget = useMemo(
239 () => ({
240 environmentId: target.environmentId,
241 cwd: target.cwd,
242 query: target.query == null ? null : target.query.trim(),
243 kind: target.kind,
244 imageOnly: target.imageOnly,
245 }),
246 [target.cwd, target.environmentId, target.imageOnly, target.kind, target.query],
247 );
248 const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
249 const result = useEnvironmentQuery(
250 debouncedTarget.environmentId !== null &&
251 debouncedTarget.cwd !== null &&
252 debouncedTarget.query !== null &&
253 (allowEmptyQuery || debouncedTarget.query.length > 0)
254 ? projectEnvironment.searchEntries({
255 environmentId: debouncedTarget.environmentId,
256 input: {
257 cwd: debouncedTarget.cwd,
258 query: debouncedTarget.query,
259 limit,
260 ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
261 ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
262 },
263 })
264 : null,
265 );
266​
267 return {
268 entries: result.data?.entries ?? [],
269 error: result.error,
270 isPending:
271 !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) || result.isPending,
272 searchedQuery: debouncedTarget.query ?? "",
273 refresh: result.refresh,
274 };
276​
277export function useComposerPathSearch(target: ComposerPathSearchTarget) {
278 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
280​
281interface ProjectContentSearchTarget {
282 readonly environmentId: EnvironmentId | null;
283 readonly cwd: string | null;
284 readonly query: string;
285 readonly caseSensitive: boolean;
286 readonly wholeWord: boolean;
287 readonly useRegex: boolean;
289​
290export function useProjectContentSearch(target: ProjectContentSearchTarget) {
291 // Whitespace is significant in content queries; trimming is only used to
292 // decide whether the input is blank.
293 const query = target.query;
294 const hasQuery = query.trim().length > 0;
295 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
296 const result = useEnvironmentQuery(
297 target.environmentId !== null &&
298 target.cwd !== null &&
299 hasQuery &&
300 debouncedQuery.trim().length > 0
301 ? projectContentSearch({
302 environmentId: target.environmentId,
303 input: {
304 cwd: target.cwd,
305 query: debouncedQuery,
306 limit: PROJECT_CONTENT_SEARCH_LIMIT,
307 caseSensitive: target.caseSensitive,
308 wholeWord: target.wholeWord,
309 useRegex: target.useRegex,
310 },
311 })
312 : null,
313 );
314​
315 return {
316 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
317 error: result.error,
318 isPending: hasQuery && (query !== debouncedQuery || result.isPending),
319 hasQuery,
320 truncated: result.data?.truncated ?? false,
321 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
322 };
324​
325export function useCheckpointDiff(
326 target: CheckpointDiffTarget,
327 options?: { readonly enabled?: boolean },
328) {
329 const enabled =
330 options?.enabled !== false &&
331 target.environmentId !== null &&
332 target.threadId !== null &&
333 target.fromTurnCount !== null &&
334 target.toTurnCount !== null;
335 const fullThreadTarget =
336 enabled && target.fromTurnCount === 0
337 ? {
338 environmentId: target.environmentId!,
339 input: {
340 threadId: target.threadId!,
341 toTurnCount: target.toTurnCount!,
342 ignoreWhitespace: target.ignoreWhitespace,
343 },
344 }
345 : null;
346 const turnTarget =
347 enabled && target.fromTurnCount !== 0
348 ? {
349 environmentId: target.environmentId!,
350 input: {
351 threadId: target.threadId!,
352 fromTurnCount: target.fromTurnCount!,
353 toTurnCount: target.toTurnCount!,
354 ignoreWhitespace: target.ignoreWhitespace,
355 },
356 }
357 : null;
358 const fullThread = useEnvironmentQuery(
359 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
360 );
361 const turn = useEnvironmentQuery(
362 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
363 );
364 return fullThreadTarget === null ? turn : fullThread;