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

queries.ts

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