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

queries.ts

421 lines14.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 visibleThreadSearch,
10 type EnvironmentThreadSearchMatch,
11 type SettledThreadSearch,
12} from "@t3tools/client-runtime/state/thread-search";
13import { THREAD_SEARCH_QUERY_MAX_LENGTH } from "@t3tools/contracts";
14import { messageSearchTokens } from "@t3tools/shared/paletteSearch";
15import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
16import type {
17 EnvironmentId,
18 ProjectContentMatch,
19 ProjectEntry,
20 ProjectEntryKind,
21 ThreadId,
22 TurnItemId,
23 VcsListRefsResult,
24 VcsRef,
25} from "@t3tools/contracts";
26import * as Cause from "effect/Cause";
27import * as Option from "effect/Option";
28import { AsyncResult, Atom } from "effect/reactivity";
29import { useEffect, useState } from "react";
30​
31import { appAtomRegistry } from "../rpc/atomRegistry";
32import { useFilesystemReadAccess } from "./filesystem";
33import { orchestrationEnvironment } from "./orchestration";
34import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
35import { projectContentSearch, projectEnvironment } from "./projects";
36import { useEnvironmentQuery } from "./query";
37import { vcsEnvironment } from "./vcs";
38​
39const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120;
40const COMPOSER_PATH_SEARCH_LIMIT = 80;
41const PROJECT_CONTENT_SEARCH_DEBOUNCE_MS = 120;
42const PROJECT_CONTENT_SEARCH_LIMIT = 500;
43const THREAD_SEARCH_DEBOUNCE_MS = 120;
44const VCS_REF_LIST_LIMIT = 100;
45const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
46const EMPTY_PROJECT_ENTRIES: ReadonlyArray<ProjectEntry> = [];
47const EMPTY_CONTENT_MATCHES: ReadonlyArray<ProjectContentMatch> = [];
48const INITIAL_BRANCH_CURSORS = [undefined] as const;
49const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
50const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
51 matches: EMPTY_THREAD_SEARCH_MATCHES,
52 isLoading: false,
53}).pipe(Atom.withLabel("web:thread-search:empty"));
54​
55const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
56 getSearchAtom: (environmentId, query) =>
57 orchestrationEnvironment.threadSearch({
58 environmentId,
59 input: { query },
60 }),
61 labelPrefix: "web:thread-search",
62});
63​
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 query: string;
85 readonly isPending: boolean;
86} {
87 // A pasted wall of text searches by its start rather than failing the request.
88 const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim();
89 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
90 // The server needs a word of three or more letters; shorter queries would always come back empty.
91 const canSearch =
92 environmentIds.length > 0 && messageSearchTokens(normalizedQuery).long.length > 0;
93 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
94 const searchKey =
95 settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery);
96 const result = useAtomValue(
97 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
98 );
99 const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading);
100 // What fast environments returned shows without waiting for a slow one;
101 // callers keep shown rows in place with `nextShownOrder`.
102 const ready =
103 settledQuery !== null && (!result.isLoading || result.matches.length > 0)
104 ? { query: settledQuery, matches: result.matches }
105 : null;
106 // Kept from earlier renders: React's pattern for information from previous renders.
107 const [previous, setPrevious] = useState<SettledThreadSearch | null>(null);
108 if (ready !== null && previous?.matches !== ready.matches) setPrevious(ready);
109 const visible = canSearch
110 ? visibleThreadSearch(normalizedQuery, ready, previous)
111 : { query: "", matches: EMPTY_THREAD_SEARCH_MATCHES };
112 return {
113 matches: visible.matches,
114 query: visible.query,
115 isPending,
116 };
118​
119function vcsRefPageAtom(targetKey: string, cursor: number | undefined) {
120 const [environmentId, cwd, query] = JSON.parse(targetKey) as [EnvironmentId, string, string];
121 return vcsEnvironment.listRefs({
122 environmentId,
123 input: {
124 cwd,
125 ...(query.length > 0 ? { query } : {}),
126 ...(cursor === undefined ? {} : { cursor }),
127 limit: VCS_REF_LIST_LIMIT,
128 },
129 });
131​
132const EMPTY_VCS_REF_PAGES_ATOM = Atom.make<
133 ReadonlyArray<Atom.Type<ReturnType<typeof vcsRefPageAtom>>>
134>([]).pipe(Atom.withLabel("web:vcs-ref-pages:empty"));
135​
136// Keyed by target and cursors so every render of the same pages reads the same atom.
137const vcsRefPagesAtom = Atom.family((pagesKey: string) => {
138 const [targetKey, cursors] = JSON.parse(pagesKey) as [string, Array<number | null>];
139 const pageAtoms = cursors.map((cursor) => vcsRefPageAtom(targetKey, cursor ?? undefined));
140 return Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
141 Atom.withLabel(`web:vcs-ref-pages:${pagesKey}`),
142 );
143});
144​
145export function usePaginatedBranches(target: VcsRefTarget) {
146 // Starts unkeyed: a key mismatch already resolves to the initial cursors, and seeding
147 // the key here would make every derivation below straddle this hook call.
148 const [pagination, setPagination] = useState<{
149 readonly targetKey: string | null;
150 readonly cursors: ReadonlyArray<number | undefined>;
151 }>({
152 targetKey: null,
153 cursors: INITIAL_BRANCH_CURSORS,
154 });
155 const { environmentId, cwd } = target;
156 const query = target.query?.trim() ?? "";
157 const targetKey =
158 environmentId !== null && cwd !== null ? JSON.stringify([environmentId, cwd, query]) : null;
159 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
160 const pagesKey = targetKey === null ? null : JSON.stringify([targetKey, cursors]);
161 const results = useAtomValue(
162 pagesKey === null ? EMPTY_VCS_REF_PAGES_ATOM : vcsRefPagesAtom(pagesKey),
163 );
164 const values = results.flatMap((result) => {
165 const value = Option.getOrNull(AsyncResult.value(result));
166 return value === null ? [] : [value];
167 });
168 const refs = new Map<string, VcsRef>();
169 for (const value of values) {
170 for (const ref of value.refs) {
171 refs.set(ref.name, ref);
172 }
173 }
174 const first = values[0] ?? null;
175 const last = values.at(-1) ?? null;
176 const data: VcsListRefsResult | null =
177 first === null || last === null
178 ? null
179 : {
180 refs: [...refs.values()],
181 isRepo: first.isRepo,
182 hasPrimaryRemote: first.hasPrimaryRemote,
183 nextCursor: last.nextCursor,
184 totalCount: Math.max(...values.map((value) => value.totalCount)),
185 };
186 const failed = results.find((result) => result._tag === "Failure");
187 const isFetchingNextPage = isPaginatedBranchesNextPagePending(results);
188 const error =
189 failed?._tag === "Failure"
190 ? (() => {
191 const cause = Cause.squash(failed.cause);
192 return cause instanceof Error && cause.message.trim().length > 0
193 ? cause.message
194 : "Failed to load refs.";
195 })()
196 : null;
197 const refresh = () => {
198 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
199 if (targetKey !== null) {
200 appAtomRegistry.refresh(vcsRefPageAtom(targetKey, undefined));
201 }
202 };
203 const nextCursor = data?.nextCursor;
204 const loadNext = () => {
205 if (targetKey === null || nextCursor === null || nextCursor === undefined) {
206 return;
207 }
208 setPagination((current) => {
209 const currentCursors =
210 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
211 return currentCursors.includes(nextCursor)
212 ? { targetKey, cursors: currentCursors }
213 : { targetKey, cursors: [...currentCursors, nextCursor] };
214 });
215 };
216​
217 return {
218 data,
219 refs: data?.refs ?? EMPTY_REFS,
220 error,
221 isPending: results.some((result) => result.waiting),
222 isFetchingNextPage,
223 refresh,
224 loadNext,
225 };
227​
228type ProjectPathSearchTarget = ComposerPathSearchTarget & {
229 readonly kind?: ProjectEntryKind | undefined;
230 readonly imageOnly?: boolean | undefined;
231};
232​
233function areProjectPathSearchTargetsEqual(
234 left: ProjectPathSearchTarget,
235 right: ProjectPathSearchTarget,
236): boolean {
237 return (
238 left.environmentId === right.environmentId &&
239 left.cwd === right.cwd &&
240 left.query === right.query &&
241 left.kind === right.kind &&
242 left.imageOnly === right.imageOnly
243 );
245​
246export function useProjectPathSearch(
247 target: ProjectPathSearchTarget,
248 limit: number,
249 options?: { readonly allowEmptyQuery?: boolean },
250) {
251 const allowEmptyQuery = options?.allowEmptyQuery === true;
252 const normalizedTarget = {
253 environmentId: target.environmentId,
254 cwd: target.cwd,
255 query: target.query == null ? null : target.query.trim(),
256 kind: target.kind,
257 imageOnly: target.imageOnly,
258 };
259 const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
260 const fileAccess = useFilesystemReadAccess(debouncedTarget.environmentId);
261 const { canReadFiles } = fileAccess;
262 const searchTarget =
263 debouncedTarget.environmentId !== null &&
264 debouncedTarget.cwd !== null &&
265 debouncedTarget.query !== null &&
266 (allowEmptyQuery || debouncedTarget.query.length > 0)
267 ? {
268 environmentId: debouncedTarget.environmentId,
269 input: {
270 cwd: debouncedTarget.cwd,
271 query: debouncedTarget.query,
272 limit,
273 ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
274 ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
275 },
276 }
277 : null;
278 const result = useEnvironmentQuery(
279 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
280 );
281 const hasTarget = searchTarget !== null;
282​
283 return {
284 entries: result.data?.entries ?? EMPTY_PROJECT_ENTRIES,
285 error:
286 !hasTarget || fileAccess.isPending
287 ? null
288 : canReadFiles
289 ? result.error
290 : (fileAccess.error ?? "This connection cannot search host files."),
291 isPending:
292 !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) ||
293 (hasTarget && (fileAccess.isPending || result.isPending)),
294 searchedTarget: debouncedTarget,
295 searchedQuery: debouncedTarget.query ?? "",
296 truncated: result.data?.truncated ?? false,
297 refresh: result.refresh,
298 };
300​
301export function useComposerPathSearch(target: ComposerPathSearchTarget) {
302 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
304​
305interface ProjectContentSearchTarget {
306 readonly environmentId: EnvironmentId | null;
307 readonly cwd: string | null;
308 readonly query: string;
309 readonly caseSensitive: boolean;
310 readonly wholeWord: boolean;
311 readonly useRegex: boolean;
313​
314export function useProjectContentSearch(target: ProjectContentSearchTarget) {
315 const hasTarget = target.environmentId !== null && target.cwd !== null;
316 const fileAccess = useFilesystemReadAccess(target.environmentId);
317 const canReadFiles = hasTarget && fileAccess.canReadFiles;
318 const isCheckingAccess = hasTarget && fileAccess.isPending;
319 // Whitespace is significant in content queries; trimming is only used to
320 // decide whether the input is blank.
321 const query = target.query;
322 const hasQuery = query.trim().length > 0;
323 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
324 const result = useEnvironmentQuery(
325 canReadFiles &&
326 target.environmentId !== null &&
327 target.cwd !== null &&
328 hasQuery &&
329 debouncedQuery.trim().length > 0
330 ? projectContentSearch({
331 environmentId: target.environmentId,
332 input: {
333 cwd: target.cwd,
334 query: debouncedQuery,
335 limit: PROJECT_CONTENT_SEARCH_LIMIT,
336 caseSensitive: target.caseSensitive,
337 wholeWord: target.wholeWord,
338 useRegex: target.useRegex,
339 },
340 })
341 : null,
342 );
343​
344 return {
345 canReadFiles,
346 isCheckingAccess,
347 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
348 error:
349 !hasTarget || isCheckingAccess
350 ? null
351 : canReadFiles
352 ? result.error
353 : (fileAccess.error ?? "This connection cannot search host files."),
354 isPending:
355 isCheckingAccess ||
356 (canReadFiles && hasQuery && (query !== debouncedQuery || result.isPending)),
357 hasQuery,
358 truncated: result.data?.truncated ?? false,
359 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
360 };
362​
363export function useCheckpointDiff(
364 target: CheckpointDiffTarget,
365 options?: { readonly enabled?: boolean },
366) {
367 const enabled =
368 options?.enabled !== false &&
369 target.environmentId !== null &&
370 target.threadId !== null &&
371 target.fromTurnCount !== null &&
372 target.toTurnCount !== null;
373 const fullThreadTarget =
374 enabled && target.fromTurnCount === 0
375 ? {
376 environmentId: target.environmentId!,
377 input: {
378 threadId: target.threadId!,
379 toTurnCount: target.toTurnCount!,
380 ignoreWhitespace: target.ignoreWhitespace,
381 },
382 }
383 : null;
384 const turnTarget =
385 enabled && target.fromTurnCount !== 0
386 ? {
387 environmentId: target.environmentId!,
388 input: {
389 threadId: target.threadId!,
390 fromTurnCount: target.fromTurnCount!,
391 toTurnCount: target.toTurnCount!,
392 ignoreWhitespace: target.ignoreWhitespace,
393 },
394 }
395 : null;
396 const fullThread = useEnvironmentQuery(
397 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
398 );
399 const turn = useEnvironmentQuery(
400 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
401 );
402 return fullThreadTarget === null ? turn : fullThread;
404​
405export function useTurnItemDetail(
406 target: {
407 readonly environmentId: EnvironmentId;
408 readonly threadId: ThreadId;
409 readonly itemId: TurnItemId;
410 readonly revision: string;
411 } | null,
412) {
413 return useEnvironmentQuery(
414 target === null
415 ? null
416 : orchestrationEnvironment.turnItem({
417 environmentId: target.environmentId,
418 input: { threadId: target.threadId, itemId: target.itemId, revision: target.revision },
419 }),
420 );