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

queries.ts

349 lines11.6 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 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 };
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 );
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 refresh: result.refresh,
258 };
260​
261export function useComposerPathSearch(target: ComposerPathSearchTarget) {
262 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
264​
265interface ProjectContentSearchTarget {
266 readonly environmentId: EnvironmentId | null;
267 readonly cwd: string | null;
268 readonly query: string;
269 readonly caseSensitive: boolean;
270 readonly wholeWord: boolean;
271 readonly useRegex: boolean;
273​
274export function useProjectContentSearch(target: ProjectContentSearchTarget) {
275 // Whitespace is significant in content queries; trimming is only used to
276 // decide whether the input is blank.
277 const query = target.query;
278 const hasQuery = query.trim().length > 0;
279 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
280 const result = useEnvironmentQuery(
281 target.environmentId !== null &&
282 target.cwd !== null &&
283 hasQuery &&
284 debouncedQuery.trim().length > 0
285 ? projectContentSearch({
286 environmentId: target.environmentId,
287 input: {
288 cwd: target.cwd,
289 query: debouncedQuery,
290 limit: PROJECT_CONTENT_SEARCH_LIMIT,
291 caseSensitive: target.caseSensitive,
292 wholeWord: target.wholeWord,
293 useRegex: target.useRegex,
294 },
295 })
296 : null,
297 );
298​
299 return {
300 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
301 error: result.error,
302 isPending: hasQuery && (query !== debouncedQuery || result.isPending),
303 hasQuery,
304 truncated: result.data?.truncated ?? false,
305 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
306 };
308​
309export function useCheckpointDiff(
310 target: CheckpointDiffTarget,
311 options?: { readonly enabled?: boolean },
312) {
313 const enabled =
314 options?.enabled !== false &&
315 target.environmentId !== null &&
316 target.threadId !== null &&
317 target.fromTurnCount !== null &&
318 target.toTurnCount !== null;
319 const fullThreadTarget =
320 enabled && target.fromTurnCount === 0
321 ? {
322 environmentId: target.environmentId!,
323 input: {
324 threadId: target.threadId!,
325 toTurnCount: target.toTurnCount!,
326 ignoreWhitespace: target.ignoreWhitespace,
327 },
328 }
329 : null;
330 const turnTarget =
331 enabled && target.fromTurnCount !== 0
332 ? {
333 environmentId: target.environmentId!,
334 input: {
335 threadId: target.threadId!,
336 fromTurnCount: target.fromTurnCount!,
337 toTurnCount: target.toTurnCount!,
338 ignoreWhitespace: target.ignoreWhitespace,
339 },
340 }
341 : null;
342 const fullThread = useEnvironmentQuery(
343 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
344 );
345 const turn = useEnvironmentQuery(
346 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
347 );
348 return fullThreadTarget === null ? turn : fullThread;