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

queries.ts

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