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

queries.ts

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