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

queries.ts

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