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

queries.ts

477 lines17.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 visibleThreadSearch,
10 type EnvironmentThreadSearchMatch,
11 type SettledThreadSearch,
12 type ThreadSearchResultsState,
13 type ThreadSearchScope,
14} from "@t3tools/client-runtime/state/thread-search";
15import { THREAD_SEARCH_QUERY_MAX_LENGTH } from "@t3tools/contracts";
16import { messageSearchTokens } from "@t3tools/shared/paletteSearch";
17import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
18import type {
19 EnvironmentId,
20 OrchestrationV2GetTurnItemResult,
21 ProjectContentMatch,
22 ProjectEntry,
23 ProjectEntryKind,
24 ThreadId,
25 TurnItemId,
26 VcsListRefsResult,
27 VcsRef,
28} from "@t3tools/contracts";
29import * as Cause from "effect/Cause";
30import * as Option from "effect/Option";
31import { AsyncResult, Atom } from "effect/reactivity";
32import { useEffect, useState } from "react";
33​
34import { appAtomRegistry } from "../rpc/atomRegistry";
35import { useFilesystemReadAccess } from "./filesystem";
36import { orchestrationEnvironment } from "./orchestration";
37import { olderSettledThreads, threadFamilies } from "./threads";
38import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
39import { projectContentSearch, projectEnvironment } from "./projects";
40import { useEnvironmentQuery } from "./query";
41import { vcsEnvironment } from "./vcs";
42​
43const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120;
44const COMPOSER_PATH_SEARCH_LIMIT = 80;
45const PROJECT_CONTENT_SEARCH_DEBOUNCE_MS = 120;
46const PROJECT_CONTENT_SEARCH_LIMIT = 500;
47const THREAD_SEARCH_DEBOUNCE_MS = 120;
48const VCS_REF_LIST_LIMIT = 100;
49const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
50const EMPTY_PROJECT_ENTRIES: ReadonlyArray<ProjectEntry> = [];
51const EMPTY_CONTENT_MATCHES: ReadonlyArray<ProjectContentMatch> = [];
52const INITIAL_BRANCH_CURSORS = [undefined] as const;
53const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
54const EMPTY_THREAD_SEARCH_ATOM = Atom.make<ThreadSearchResultsState>({
55 matches: EMPTY_THREAD_SEARCH_MATCHES,
56 isLoading: false,
57 rows: [],
58}).pipe(Atom.withLabel("web:thread-search:empty"));
59​
60const olderSettledBeforeAtom = Atom.family((environmentId: EnvironmentId) =>
61 Atom.make((get) => get(olderSettledThreads.olderSettledAtom(environmentId))?.before ?? null).pipe(
62 Atom.withLabel(`web:older-settled-before:${environmentId}`),
63 ),
64);
65// Whether any of these environments leaves older settled threads out, so short queries matter.
66const anyOlderSettledAtom = Atom.family((environmentIdsKey: string) =>
67 Atom.make((get) =>
68 (JSON.parse(environmentIdsKey) as ReadonlyArray<EnvironmentId>).some(
69 (environmentId) => get(olderSettledBeforeAtom(environmentId)) !== null,
70 ),
71 ).pipe(Atom.withLabel(`web:any-older-settled:${environmentIdsKey}`)),
72);
73const threadSearch = createThreadSearchResultsAtomFamily({
74 getSearchAtom: (environmentId, input) =>
75 input.olderSettledBefore === undefined
76 ? orchestrationEnvironment.threadSearch({ environmentId, input })
77 : olderSettledThreads.searchAtom(environmentId, input),
78 olderSettledBefore: olderSettledBeforeAtom,
79 labelPrefix: "web:thread-search",
80});
81​
82export function useDebouncedValue<A>(value: A, delayMs: number): A {
83 const [debounced, setDebounced] = useState(value);
84​
85 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- debounce timer that publishes the value after delayMs
86 useEffect(() => {
87 const timer = window.setTimeout(() => {
88 setDebounced(value);
89 }, delayMs);
90 return () => {
91 window.clearTimeout(timer);
92 };
93 }, [delayMs, value]);
94​
95 return debounced;
97​
98/**
99 * Server matches for a thread search: message hits, and on environments that leave older settled
100 * threads out of the shell, the rows of the best older matches, mounted into the thread list while
101 * they show so the caller's own ranking finds them.
102 */
103export function useThreadSearch(
104 environmentIds: ReadonlyArray<EnvironmentId>,
105 query: string,
106 scope: ThreadSearchScope = {},
107): {
108 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
109 readonly query: string;
110 readonly isPending: boolean;
111} {
112 // A pasted wall of text searches by its start rather than failing the request.
113 const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim();
114 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
115 const anyOlderSettled = useAtomValue(anyOlderSettledAtom(JSON.stringify(environmentIds)));
116 // Messages need a word of three or more letters; older settled titles match from two.
117 const canSearch =
118 environmentIds.length > 0 &&
119 ((scope.titlesOnly !== true && messageSearchTokens(normalizedQuery).long.length > 0) ||
120 (anyOlderSettled && normalizedQuery.length >= 2));
121 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
122 const searchKeyOf = (searchQuery: string) =>
123 makeThreadSearchKey(environmentIds, searchQuery, scope);
124 const searchKey = settledQuery === null ? null : searchKeyOf(settledQuery);
125 const result = useAtomValue(
126 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearch.results(searchKey),
127 );
128 const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading);
129 // What fast environments returned shows without waiting for a slow one;
130 // callers keep shown rows in place with `nextShownOrder`.
131 const ready =
132 settledQuery !== null &&
133 (!result.isLoading || result.matches.length > 0 || result.rows.length > 0)
134 ? { query: settledQuery, matches: result.matches }
135 : null;
136 // Kept from earlier renders: React's pattern for information from previous renders.
137 const [previous, setPrevious] = useState<SettledThreadSearch | null>(null);
138 if (ready !== null && previous?.matches !== ready.matches) setPrevious(ready);
139 const visible = canSearch
140 ? visibleThreadSearch(normalizedQuery, ready, previous)
141 : { query: "", matches: EMPTY_THREAD_SEARCH_MATCHES };
142 // The shown results' rows stay mounted until newer results replace them.
143 const shownKey = visible.query === "" ? null : searchKeyOf(visible.query);
144 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mounts the shown search results' rows into the thread family registry until newer results replace them
145 useEffect(() => {
146 if (shownKey === null) return;
147 const environments = (JSON.parse(shownKey) as [ReadonlyArray<EnvironmentId>])[0];
148 const releases = environments.map((environmentId) =>
149 threadFamilies.mountRows(
150 appAtomRegistry,
151 environmentId,
152 `search:${shownKey}`,
153 threadSearch.rows(shownKey, environmentId),
154 ),
155 );
156 return () => {
157 for (const release of releases) release();
158 };
159 }, [shownKey]);
160 return {
161 matches: visible.matches,
162 query: visible.query,
163 isPending,
164 };
166​
167function vcsRefPageAtom(targetKey: string, cursor: number | undefined) {
168 const [environmentId, cwd, query] = JSON.parse(targetKey) as [EnvironmentId, string, string];
169 return vcsEnvironment.listRefs({
170 environmentId,
171 input: {
172 cwd,
173 ...(query.length > 0 ? { query } : {}),
174 ...(cursor === undefined ? {} : { cursor }),
175 limit: VCS_REF_LIST_LIMIT,
176 },
177 });
179​
180const EMPTY_VCS_REF_PAGES_ATOM = Atom.make<
181 ReadonlyArray<Atom.Type<ReturnType<typeof vcsRefPageAtom>>>
182>([]).pipe(Atom.withLabel("web:vcs-ref-pages:empty"));
183​
184const vcsRefPagesAtom = Atom.family((pagesKey: string) => {
185 const [targetKey, cursors] = JSON.parse(pagesKey) as [string, Array<number | null>];
186 const pageAtoms = cursors.map((cursor) => vcsRefPageAtom(targetKey, cursor ?? undefined));
187 return Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
188 Atom.withLabel(`web:vcs-ref-pages:${pagesKey}`),
189 );
190});
191​
192export function usePaginatedBranches(target: VcsRefTarget) {
193 // Leave unkeyed; mismatches already reset cursors, and a seeded key would break caching across the hook.
194 const [pagination, setPagination] = useState<{
195 readonly targetKey: string | null;
196 readonly cursors: ReadonlyArray<number | undefined>;
197 }>({
198 targetKey: null,
199 cursors: INITIAL_BRANCH_CURSORS,
200 });
201 const { environmentId, cwd } = target;
202 const query = target.query?.trim() ?? "";
203 const targetKey =
204 environmentId !== null && cwd !== null ? JSON.stringify([environmentId, cwd, query]) : null;
205 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
206 const pagesKey = targetKey === null ? null : JSON.stringify([targetKey, cursors]);
207 const results = useAtomValue(
208 pagesKey === null ? EMPTY_VCS_REF_PAGES_ATOM : vcsRefPagesAtom(pagesKey),
209 );
210 const values = results.flatMap((result) => {
211 const value = Option.getOrNull(AsyncResult.value(result));
212 return value === null ? [] : [value];
213 });
214 const refs = new Map<string, VcsRef>();
215 for (const value of values) {
216 for (const ref of value.refs) {
217 refs.set(ref.name, ref);
218 }
219 }
220 const first = values[0] ?? null;
221 const last = values.at(-1) ?? null;
222 const data: VcsListRefsResult | null =
223 first === null || last === null
224 ? null
225 : {
226 refs: [...refs.values()],
227 isRepo: first.isRepo,
228 hasPrimaryRemote: first.hasPrimaryRemote,
229 nextCursor: last.nextCursor,
230 totalCount: Math.max(...values.map((value) => value.totalCount)),
231 };
232 const failed = results.find((result) => result._tag === "Failure");
233 const isFetchingNextPage = isPaginatedBranchesNextPagePending(results);
234 const error =
235 failed?._tag === "Failure"
236 ? (() => {
237 const cause = Cause.squash(failed.cause);
238 return cause instanceof Error && cause.message.trim().length > 0
239 ? cause.message
240 : "Failed to load refs.";
241 })()
242 : null;
243 const refresh = () => {
244 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
245 if (targetKey !== null) {
246 appAtomRegistry.refresh(vcsRefPageAtom(targetKey, undefined));
247 }
248 };
249 const nextCursor = data?.nextCursor;
250 const loadNext = () => {
251 if (targetKey === null || nextCursor === null || nextCursor === undefined) {
252 return;
253 }
254 setPagination((current) => {
255 const currentCursors =
256 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
257 return currentCursors.includes(nextCursor)
258 ? { targetKey, cursors: currentCursors }
259 : { targetKey, cursors: [...currentCursors, nextCursor] };
260 });
261 };
262​
263 return {
264 data,
265 refs: data?.refs ?? EMPTY_REFS,
266 error,
267 isPending: results.some((result) => result.waiting),
268 isFetchingNextPage,
269 refresh,
270 loadNext,
271 };
273​
274type ProjectPathSearchTarget = ComposerPathSearchTarget & {
275 readonly kind?: ProjectEntryKind | undefined;
276 readonly imageOnly?: boolean | undefined;
277};
278​
279function areProjectPathSearchTargetsEqual(
280 left: ProjectPathSearchTarget,
281 right: ProjectPathSearchTarget,
282): boolean {
283 return (
284 left.environmentId === right.environmentId &&
285 left.cwd === right.cwd &&
286 left.query === right.query &&
287 left.kind === right.kind &&
288 left.imageOnly === right.imageOnly
289 );
291​
292export function useProjectPathSearch(
293 target: ProjectPathSearchTarget,
294 limit: number,
295 options?: { readonly allowEmptyQuery?: boolean },
296) {
297 const allowEmptyQuery = options?.allowEmptyQuery === true;
298 const normalizedTarget = {
299 environmentId: target.environmentId,
300 cwd: target.cwd,
301 query: target.query == null ? null : target.query.trim(),
302 kind: target.kind,
303 imageOnly: target.imageOnly,
304 };
305 const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
306 const fileAccess = useFilesystemReadAccess(debouncedTarget.environmentId);
307 const { canReadFiles } = fileAccess;
308 const searchTarget =
309 debouncedTarget.environmentId !== null &&
310 debouncedTarget.cwd !== null &&
311 debouncedTarget.query !== null &&
312 (allowEmptyQuery || debouncedTarget.query.length > 0)
313 ? {
314 environmentId: debouncedTarget.environmentId,
315 input: {
316 cwd: debouncedTarget.cwd,
317 query: debouncedTarget.query,
318 limit,
319 ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
320 ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
321 },
322 }
323 : null;
324 const result = useEnvironmentQuery(
325 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
326 );
327 const hasTarget = searchTarget !== null;
328​
329 return {
330 entries: result.data?.entries ?? EMPTY_PROJECT_ENTRIES,
331 error:
332 !hasTarget || fileAccess.isPending
333 ? null
334 : canReadFiles
335 ? result.error
336 : (fileAccess.error ?? "This connection cannot search host files."),
337 isPending:
338 !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) ||
339 (hasTarget && (fileAccess.isPending || result.isPending)),
340 searchedTarget: debouncedTarget,
341 searchedQuery: debouncedTarget.query ?? "",
342 truncated: result.data?.truncated ?? false,
343 refresh: result.refresh,
344 };
346​
347export function useComposerPathSearch(target: ComposerPathSearchTarget) {
348 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
350​
351interface ProjectContentSearchTarget {
352 readonly environmentId: EnvironmentId | null;
353 readonly cwd: string | null;
354 readonly query: string;
355 readonly caseSensitive: boolean;
356 readonly wholeWord: boolean;
357 readonly useRegex: boolean;
359​
360export function useProjectContentSearch(target: ProjectContentSearchTarget) {
361 const hasTarget = target.environmentId !== null && target.cwd !== null;
362 const fileAccess = useFilesystemReadAccess(target.environmentId);
363 const canReadFiles = hasTarget && fileAccess.canReadFiles;
364 const isCheckingAccess = hasTarget && fileAccess.isPending;
365 // Preserve query whitespace; trim only to detect blank input.
366 const query = target.query;
367 const hasQuery = query.trim().length > 0;
368 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
369 const result = useEnvironmentQuery(
370 canReadFiles &&
371 target.environmentId !== null &&
372 target.cwd !== null &&
373 hasQuery &&
374 debouncedQuery.trim().length > 0
375 ? projectContentSearch({
376 environmentId: target.environmentId,
377 input: {
378 cwd: target.cwd,
379 query: debouncedQuery,
380 limit: PROJECT_CONTENT_SEARCH_LIMIT,
381 caseSensitive: target.caseSensitive,
382 wholeWord: target.wholeWord,
383 useRegex: target.useRegex,
384 },
385 })
386 : null,
387 );
388​
389 return {
390 canReadFiles,
391 isCheckingAccess,
392 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
393 error:
394 !hasTarget || isCheckingAccess
395 ? null
396 : canReadFiles
397 ? result.error
398 : (fileAccess.error ?? "This connection cannot search host files."),
399 isPending:
400 isCheckingAccess ||
401 (canReadFiles && hasQuery && (query !== debouncedQuery || result.isPending)),
402 hasQuery,
403 truncated: result.data?.truncated ?? false,
404 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
405 };
407​
408export function useCheckpointDiff(
409 target: CheckpointDiffTarget,
410 options?: { readonly enabled?: boolean },
411) {
412 const enabled =
413 options?.enabled !== false &&
414 target.environmentId !== null &&
415 target.threadId !== null &&
416 target.fromTurnCount !== null &&
417 target.toTurnCount !== null;
418 const fullThreadTarget =
419 enabled && target.fromTurnCount === 0
420 ? {
421 environmentId: target.environmentId!,
422 input: {
423 threadId: target.threadId!,
424 toTurnCount: target.toTurnCount!,
425 ignoreWhitespace: target.ignoreWhitespace,
426 },
427 }
428 : null;
429 const turnTarget =
430 enabled && target.fromTurnCount !== 0
431 ? {
432 environmentId: target.environmentId!,
433 input: {
434 threadId: target.threadId!,
435 fromTurnCount: target.fromTurnCount!,
436 toTurnCount: target.toTurnCount!,
437 ignoreWhitespace: target.ignoreWhitespace,
438 },
439 }
440 : null;
441 const fullThread = useEnvironmentQuery(
442 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
443 );
444 const turn = useEnvironmentQuery(
445 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
446 );
447 return fullThreadTarget === null ? turn : fullThread;
449​
450/** Reads one item's detail from somewhere other than the environment, as the guest page does. */
451export type TurnItemDetailSource = (input: {
452 readonly threadId: ThreadId;
453 readonly itemId: TurnItemId;
454 readonly revision: string;
455}) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2GetTurnItemResult, unknown>>;
456​
457export function useTurnItemDetail(
458 target: {
459 readonly environmentId: EnvironmentId;
460 readonly threadId: ThreadId;
461 readonly itemId: TurnItemId;
462 readonly revision: string;
463 } | null,
464 source?: TurnItemDetailSource,
465) {
466 const input =
467 target === null
468 ? null
469 : { threadId: target.threadId, itemId: target.itemId, revision: target.revision };
470 return useEnvironmentQuery<OrchestrationV2GetTurnItemResult, unknown>(
471 target === null || input === null
472 ? null
473 : source
474 ? source(input)
475 : orchestrationEnvironment.turnItem({ environmentId: target.environmentId, input }),
476 );