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

queries.ts

411 lines13.4 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 ProjectEntry,
16 ProjectEntryKind,
17 ThreadId,
18 TurnItemId,
19 VcsListRefsResult,
20 VcsRef,
21} from "@t3tools/contracts";
22import * as Cause from "effect/Cause";
23import * as Option from "effect/Option";
24import { AsyncResult, Atom } from "effect/reactivity";
25import { useEffect, useState } from "react";
26​
27import { appAtomRegistry } from "../rpc/atomRegistry";
28import { useFilesystemReadAccess } from "./filesystem";
29import { orchestrationEnvironment } from "./orchestration";
30import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
31import { projectContentSearch, projectEnvironment } from "./projects";
32import { useEnvironmentQuery } from "./query";
33import { vcsEnvironment } from "./vcs";
34​
35const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120;
36const COMPOSER_PATH_SEARCH_LIMIT = 80;
37const PROJECT_CONTENT_SEARCH_DEBOUNCE_MS = 120;
38const PROJECT_CONTENT_SEARCH_LIMIT = 500;
39const THREAD_SEARCH_DEBOUNCE_MS = 200;
40const VCS_REF_LIST_LIMIT = 100;
41const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
42const EMPTY_PROJECT_ENTRIES: ReadonlyArray<ProjectEntry> = [];
43const EMPTY_CONTENT_MATCHES: ReadonlyArray<ProjectContentMatch> = [];
44const INITIAL_BRANCH_CURSORS = [undefined] as const;
45const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
46const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
47 matches: EMPTY_THREAD_SEARCH_MATCHES,
48 isLoading: false,
49}).pipe(Atom.withLabel("web:thread-search:empty"));
50​
51const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
52 getSearchAtom: (environmentId, query) =>
53 orchestrationEnvironment.threadSearch({
54 environmentId,
55 input: { query },
56 }),
57 labelPrefix: "web:thread-search",
58});
59​
60export function useDebouncedValue<A>(value: A, delayMs: number): A {
61 const [debounced, setDebounced] = useState(value);
62​
63 useEffect(() => {
64 const timer = window.setTimeout(() => {
65 setDebounced(value);
66 }, delayMs);
67 return () => {
68 window.clearTimeout(timer);
69 };
70 }, [delayMs, value]);
71​
72 return debounced;
74​
75export function useThreadSearch(
76 environmentIds: ReadonlyArray<EnvironmentId>,
77 query: string,
78): {
79 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
80 readonly query: string;
81 readonly isPending: boolean;
82} {
83 const normalizedQuery = query.trim();
84 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
85 const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
86 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
87 const searchKey =
88 settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery);
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​
100// A hook so its result is frozen: `refresh` hands a page atom to the registry,
101// which the compiler would treat as a mutation and leave pagesAtom uncached,
102// resubscribing every render.
103function useBranchPageAtoms(
104 environmentId: EnvironmentId | null,
105 cwd: string | null,
106 query: string,
107 cursors: ReadonlyArray<number | undefined>,
108 targetKey: string | null,
109) {
110 // Calls no hooks, so the compiler needs the directive to memoize it.
111 "use memo";
112 const pageAtoms =
113 environmentId !== null && cwd !== null
114 ? cursors.map((cursor) =>
115 vcsEnvironment.listRefs({
116 environmentId,
117 input: {
118 cwd,
119 ...(query.length > 0 ? { query } : {}),
120 ...(cursor === undefined ? {} : { cursor }),
121 limit: VCS_REF_LIST_LIMIT,
122 },
123 }),
124 )
125 : [];
126 const pagesAtom = Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
127 Atom.withLabel(`web:vcs-ref-pages:${targetKey ?? "empty"}`),
128 );
129 return { pageAtoms, pagesAtom };
131​
132export function usePaginatedBranches(target: VcsRefTarget) {
133 const query = target.query?.trim() ?? "";
134 const targetKey =
135 target.environmentId !== null && target.cwd !== null
136 ? JSON.stringify([target.environmentId, target.cwd, query])
137 : null;
138 const [pagination, setPagination] = useState<{
139 readonly targetKey: string | null;
140 readonly cursors: ReadonlyArray<number | undefined>;
141 }>({
142 targetKey,
143 cursors: INITIAL_BRANCH_CURSORS,
144 });
145 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
146 const { pageAtoms, pagesAtom } = useBranchPageAtoms(
147 target.environmentId,
148 target.cwd,
149 query,
150 cursors,
151 targetKey,
152 );
153 const results = useAtomValue(pagesAtom);
154 const values = results.flatMap((result) => {
155 const value = Option.getOrNull(AsyncResult.value(result));
156 return value === null ? [] : [value];
157 });
158 const refs = new Map<string, VcsRef>();
159 for (const value of values) {
160 for (const ref of value.refs) {
161 refs.set(ref.name, ref);
162 }
163 }
164 const first = values[0] ?? null;
165 const last = values.at(-1) ?? null;
166 const data: VcsListRefsResult | null =
167 first === null || last === null
168 ? null
169 : {
170 refs: [...refs.values()],
171 isRepo: first.isRepo,
172 hasPrimaryRemote: first.hasPrimaryRemote,
173 nextCursor: last.nextCursor,
174 totalCount: Math.max(...values.map((value) => value.totalCount)),
175 };
176 const failed = results.find((result) => result._tag === "Failure");
177 const isFetchingNextPage = isPaginatedBranchesNextPagePending(results);
178 const error =
179 failed?._tag === "Failure"
180 ? (() => {
181 const cause = Cause.squash(failed.cause);
182 return cause instanceof Error && cause.message.trim().length > 0
183 ? cause.message
184 : "Failed to load refs.";
185 })()
186 : null;
187 const refresh = () => {
188 const firstPage = pageAtoms[0];
189 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
190 if (firstPage !== undefined) {
191 appAtomRegistry.refresh(firstPage);
192 }
193 };
194 const nextCursor = data?.nextCursor;
195 const loadNext = () => {
196 if (targetKey === null || nextCursor === null || nextCursor === undefined) {
197 return;
198 }
199 setPagination((current) => {
200 const currentCursors =
201 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
202 return currentCursors.includes(nextCursor)
203 ? { targetKey, cursors: currentCursors }
204 : { targetKey, cursors: [...currentCursors, nextCursor] };
205 });
206 };
207​
208 return {
209 data,
210 refs: data?.refs ?? EMPTY_REFS,
211 error,
212 isPending: results.some((result) => result.waiting),
213 isFetchingNextPage,
214 refresh,
215 loadNext,
216 };
218​
219type ProjectPathSearchTarget = ComposerPathSearchTarget & {
220 readonly kind?: ProjectEntryKind | undefined;
221 readonly imageOnly?: boolean | undefined;
222};
223​
224export function areProjectPathSearchTargetsEqual(
225 left: ProjectPathSearchTarget,
226 right: ProjectPathSearchTarget,
227): boolean {
228 return (
229 left.environmentId === right.environmentId &&
230 left.cwd === right.cwd &&
231 left.query === right.query &&
232 left.kind === right.kind &&
233 left.imageOnly === right.imageOnly
234 );
236​
237export function useProjectPathSearch(
238 target: ProjectPathSearchTarget,
239 limit: number,
240 options?: { readonly allowEmptyQuery?: boolean },
241) {
242 const allowEmptyQuery = options?.allowEmptyQuery === true;
243 const normalizedTarget = {
244 environmentId: target.environmentId,
245 cwd: target.cwd,
246 query: target.query == null ? null : target.query.trim(),
247 kind: target.kind,
248 imageOnly: target.imageOnly,
249 };
250 const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
251 const fileAccess = useFilesystemReadAccess(debouncedTarget.environmentId);
252 const { canReadFiles } = fileAccess;
253 const searchTarget =
254 debouncedTarget.environmentId !== null &&
255 debouncedTarget.cwd !== null &&
256 debouncedTarget.query !== null &&
257 (allowEmptyQuery || debouncedTarget.query.length > 0)
258 ? {
259 environmentId: debouncedTarget.environmentId,
260 input: {
261 cwd: debouncedTarget.cwd,
262 query: debouncedTarget.query,
263 limit,
264 ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
265 ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
266 },
267 }
268 : null;
269 const result = useEnvironmentQuery(
270 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
271 );
272 const hasTarget = searchTarget !== null;
273​
274 return {
275 entries: result.data?.entries ?? EMPTY_PROJECT_ENTRIES,
276 error:
277 !hasTarget || fileAccess.isPending
278 ? null
279 : canReadFiles
280 ? result.error
281 : (fileAccess.error ?? "This connection cannot search host files."),
282 isPending:
283 !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) ||
284 (hasTarget && (fileAccess.isPending || result.isPending)),
285 searchedQuery: debouncedTarget.query ?? "",
286 truncated: result.data?.truncated ?? false,
287 refresh: result.refresh,
288 };
290​
291export function useComposerPathSearch(target: ComposerPathSearchTarget) {
292 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
294​
295interface ProjectContentSearchTarget {
296 readonly environmentId: EnvironmentId | null;
297 readonly cwd: string | null;
298 readonly query: string;
299 readonly caseSensitive: boolean;
300 readonly wholeWord: boolean;
301 readonly useRegex: boolean;
303​
304export function useProjectContentSearch(target: ProjectContentSearchTarget) {
305 const hasTarget = target.environmentId !== null && target.cwd !== null;
306 const fileAccess = useFilesystemReadAccess(target.environmentId);
307 const canReadFiles = hasTarget && fileAccess.canReadFiles;
308 const isCheckingAccess = hasTarget && fileAccess.isPending;
309 // Whitespace is significant in content queries; trimming is only used to
310 // decide whether the input is blank.
311 const query = target.query;
312 const hasQuery = query.trim().length > 0;
313 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
314 const result = useEnvironmentQuery(
315 canReadFiles &&
316 target.environmentId !== null &&
317 target.cwd !== null &&
318 hasQuery &&
319 debouncedQuery.trim().length > 0
320 ? projectContentSearch({
321 environmentId: target.environmentId,
322 input: {
323 cwd: target.cwd,
324 query: debouncedQuery,
325 limit: PROJECT_CONTENT_SEARCH_LIMIT,
326 caseSensitive: target.caseSensitive,
327 wholeWord: target.wholeWord,
328 useRegex: target.useRegex,
329 },
330 })
331 : null,
332 );
333​
334 return {
335 canReadFiles,
336 isCheckingAccess,
337 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
338 error:
339 !hasTarget || isCheckingAccess
340 ? null
341 : canReadFiles
342 ? result.error
343 : (fileAccess.error ?? "This connection cannot search host files."),
344 isPending:
345 isCheckingAccess ||
346 (canReadFiles && hasQuery && (query !== debouncedQuery || result.isPending)),
347 hasQuery,
348 truncated: result.data?.truncated ?? false,
349 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
350 };
352​
353export function useCheckpointDiff(
354 target: CheckpointDiffTarget,
355 options?: { readonly enabled?: boolean },
356) {
357 const enabled =
358 options?.enabled !== false &&
359 target.environmentId !== null &&
360 target.threadId !== null &&
361 target.fromTurnCount !== null &&
362 target.toTurnCount !== null;
363 const fullThreadTarget =
364 enabled && target.fromTurnCount === 0
365 ? {
366 environmentId: target.environmentId!,
367 input: {
368 threadId: target.threadId!,
369 toTurnCount: target.toTurnCount!,
370 ignoreWhitespace: target.ignoreWhitespace,
371 },
372 }
373 : null;
374 const turnTarget =
375 enabled && target.fromTurnCount !== 0
376 ? {
377 environmentId: target.environmentId!,
378 input: {
379 threadId: target.threadId!,
380 fromTurnCount: target.fromTurnCount!,
381 toTurnCount: target.toTurnCount!,
382 ignoreWhitespace: target.ignoreWhitespace,
383 },
384 }
385 : null;
386 const fullThread = useEnvironmentQuery(
387 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
388 );
389 const turn = useEnvironmentQuery(
390 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
391 );
392 return fullThreadTarget === null ? turn : fullThread;
394​
395export function useTurnItemDetail(
396 target: {
397 readonly environmentId: EnvironmentId;
398 readonly threadId: ThreadId;
399 readonly itemId: TurnItemId;
400 readonly revision: string;
401 } | null,
402) {
403 return useEnvironmentQuery(
404 target === null
405 ? null
406 : orchestrationEnvironment.turnItem({
407 environmentId: target.environmentId,
408 input: { threadId: target.threadId, itemId: target.itemId, revision: target.revision },
409 }),
410 );