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

queries.ts

456 lines16.4 KB

1import {
2 composerPullRequestsFromLinks,
3 filterComposerPullRequestMatches,
4} from "@t3tools/shared/composerPullRequestMatches";
5import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
6import { environmentSession } from "./session";
7import { useEnvironmentPresentation } from "./presentation";
8import type { VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
9import type {
10 EnvironmentId,
11 OrchestrationV2ProjectedTurnItem,
12 ProjectId,
13 ThreadPullRequestLink,
14 VcsListRefsResult,
15 VcsRef,
16} from "@t3tools/contracts";
17import {
18 createThreadSearchResultsAtomFamily,
19 makeThreadSearchKey,
20 visibleThreadSearch,
21 type EnvironmentThreadSearchMatch,
22 type SettledThreadSearch,
23 type ThreadSearchResultsState,
24 type ThreadSearchScope,
25} from "@t3tools/client-runtime/state/thread-search";
26import { THREAD_SEARCH_QUERY_MAX_LENGTH } from "@t3tools/contracts";
27import { messageSearchTokens } from "@t3tools/shared/paletteSearch";
28import { useAtomValue } from "@effect/atom-react";
29import * as Cause from "effect/Cause";
30import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
31import * as Option from "effect/Option";
32import { AsyncResult, Atom } from "effect/reactivity";
33import { useEffect, useMemo, useState } from "react";
34​
35import { appAtomRegistry } from "./atom-registry";
36import { orchestrationEnvironment } from "./orchestration";
37import { olderSettledThreads, threadFamilies } from "./threads";
38import { projectEnvironment } from "./projects";
39import { useEnvironmentQuery } from "./query";
40import { vcsEnvironment } from "./vcs";
41import { composerPullRequests } from "./pull-requests";
42import {
43 buildCheckpointDiffTargets,
44 normalizeComposerPathSearchQuery,
45 type CheckpointDiffTarget,
46} from "./queryTargets";
47​
48const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
49const COMPOSER_PATH_SEARCH_LIMIT = 20;
50const THREAD_SEARCH_DEBOUNCE_MS = 120;
51const VCS_REF_LIST_LIMIT = 100;
52const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
53const INITIAL_BRANCH_CURSORS = [undefined] as const;
54const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
55const EMPTY_THREAD_SEARCH_ATOM = Atom.make<ThreadSearchResultsState>({
56 matches: EMPTY_THREAD_SEARCH_MATCHES,
57 isLoading: false,
58 rows: [],
59}).pipe(Atom.withLabel("mobile:thread-search:empty"));
60​
61const olderSettledBeforeAtom = Atom.family((environmentId: EnvironmentId) =>
62 Atom.make((get) => get(olderSettledThreads.olderSettledAtom(environmentId))?.before ?? null).pipe(
63 Atom.withLabel(`mobile:older-settled-before:${environmentId}`),
64 ),
65);
66// Whether any of these environments leaves older settled threads out, so short queries matter.
67const anyOlderSettledAtom = Atom.family((environmentIdsKey: string) =>
68 Atom.make((get) =>
69 (JSON.parse(environmentIdsKey) as ReadonlyArray<EnvironmentId>).some(
70 (environmentId) => get(olderSettledBeforeAtom(environmentId)) !== null,
71 ),
72 ).pipe(Atom.withLabel(`mobile:any-older-settled:${environmentIdsKey}`)),
73);
74const threadSearch = createThreadSearchResultsAtomFamily({
75 getSearchAtom: (environmentId, input) =>
76 input.olderSettledBefore === undefined
77 ? orchestrationEnvironment.threadSearch({ environmentId, input })
78 : olderSettledThreads.searchAtom(environmentId, input),
79 olderSettledBefore: olderSettledBeforeAtom,
80 labelPrefix: "mobile:thread-search",
81});
82​
83export interface ComposerPathSearchTarget {
84 readonly environmentId: EnvironmentId | null;
85 readonly cwd: string | null;
86 readonly query: string | null;
88​
89export function useDebouncedValue<A>(value: A, delayMs: number): A {
90 const [debounced, setDebounced] = useState(value);
91​
92 useEffect(() => {
93 const timer = setTimeout(() => {
94 setDebounced(value);
95 }, delayMs);
96 return () => {
97 clearTimeout(timer);
98 };
99 }, [delayMs, value]);
100​
101 return debounced;
103​
104export function useComposerPullRequestSearch(input: {
105 environmentId: EnvironmentId | null;
106 projectId: ProjectId | null;
107 repository: string | null;
108 threadPullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
109 query: string | null;
110}) {
111 const query = useDebouncedValue(input.query, 180);
112 const linked =
113 input.projectId === null
114 ? []
115 : composerPullRequestsFromLinks(input.threadPullRequests ?? [], input.projectId);
116 const ready =
117 query === input.query &&
118 query !== null &&
119 input.environmentId !== null &&
120 input.projectId !== null &&
121 input.repository !== null;
122 const numeric = query !== null && /^\d*$/.test(query);
123 const list = useEnvironmentQuery(
124 ready
125 ? composerPullRequests.list({
126 environmentId: input.environmentId!,
127 input: {
128 projectId: input.projectId!,
129 state: "all",
130 limit: 200,
131 ...(!numeric && query ? { query } : {}),
132 },
133 })
134 : null,
135 );
136 const number = numeric && query ? Number(query) : null;
137 const hasExact = list.data?.entries.some(
138 (entry) =>
139 entry.number === number && entry.repository.toLowerCase() === input.repository?.toLowerCase(),
140 );
141 const exact = useEnvironmentQuery(
142 ready && number !== null && Number.isSafeInteger(number) && number > 0 && !hasExact
143 ? composerPullRequests.detail({
144 environmentId: input.environmentId!,
145 input: { projectId: input.projectId!, repository: input.repository!, number },
146 })
147 : null,
148 );
149 const entries = (() => {
150 if (!ready) return [];
151 if (numeric) {
152 return filterComposerPullRequestMatches({
153 entries: [...(exact.data ? [exact.data] : []), ...(list.data?.entries ?? [])],
154 linked,
155 projectId: input.projectId!,
156 repository: input.repository!,
157 query: query ?? "",
158 limit: 20,
159 });
160 }
161 const words = (query ?? "").toLowerCase().split(/\s+/).filter(Boolean);
162 const found = [...(exact.data ? [exact.data] : []), ...(list.data?.entries ?? [])].filter(
163 (entry) =>
164 entry.projectId === input.projectId &&
165 entry.repository.toLowerCase() === input.repository?.toLowerCase() &&
166 words.every((word) =>
167 `${entry.title} ${entry.headBranch} ${entry.baseBranch}`.toLowerCase().includes(word),
168 ),
169 );
170 const unique = new Map<number, (typeof found)[number]>();
171 for (const entry of found) if (!unique.has(entry.number)) unique.set(entry.number, entry);
172 return [...unique.values()]
173 .sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
174 .slice(0, 20);
175 })();
176 return {
177 entries,
178 isPending: input.query !== null && (query !== input.query || list.isPending || exact.isPending),
179 error: list.error ?? list.data?.errors[0]?.message ?? exact.error,
180 };
182​
183/**
184 * Server matches for a thread search: message hits, and on environments that leave older settled
185 * threads out of the shell, the rows of the best older matches, mounted into the thread list while
186 * they show so the caller's own ranking finds them.
187 */
188export function useThreadSearch(
189 environmentIds: ReadonlyArray<EnvironmentId>,
190 query: string,
191 scope: ThreadSearchScope = {},
192): {
193 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
194 /** The query `matches` are for, which lags the typed one while a search runs. */
195 readonly query: string;
196 readonly isPending: boolean;
197} {
198 // A pasted wall of text searches by its start rather than failing the request.
199 const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim();
200 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
201 const anyOlderSettled = useAtomValue(anyOlderSettledAtom(JSON.stringify(environmentIds)));
202 // Messages need a word of three or more letters; older settled titles match from two.
203 const canSearch =
204 environmentIds.length > 0 &&
205 ((scope.titlesOnly !== true && messageSearchTokens(normalizedQuery).long.length > 0) ||
206 (anyOlderSettled && normalizedQuery.length >= 2));
207 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
208 const searchKeyOf = (searchQuery: string) =>
209 makeThreadSearchKey(environmentIds, searchQuery, scope);
210 const searchKey = settledQuery === null ? null : searchKeyOf(settledQuery);
211 const result = useAtomValue(
212 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearch.results(searchKey),
213 );
214 const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading);
215 // What fast environments returned shows without waiting for a slow one;
216 // callers keep shown rows in place with `nextShownOrder`.
217 const ready =
218 settledQuery !== null &&
219 (!result.isLoading || result.matches.length > 0 || result.rows.length > 0)
220 ? { query: settledQuery, matches: result.matches }
221 : null;
222 // Kept from earlier renders: React's pattern for information from previous renders.
223 const [previous, setPrevious] = useState<SettledThreadSearch | null>(null);
224 if (ready !== null && previous?.matches !== ready.matches) setPrevious(ready);
225 const visible = canSearch
226 ? visibleThreadSearch(normalizedQuery, ready, previous)
227 : { query: "", matches: EMPTY_THREAD_SEARCH_MATCHES };
228 // The shown results' rows stay mounted until newer results replace them.
229 const shownKey = visible.query === "" ? null : searchKeyOf(visible.query);
230 useEffect(() => {
231 if (shownKey === null) return;
232 const environments = (JSON.parse(shownKey) as [ReadonlyArray<EnvironmentId>])[0];
233 const releases = environments.map((environmentId) =>
234 threadFamilies.mountRows(
235 appAtomRegistry,
236 environmentId,
237 `search:${shownKey}`,
238 threadSearch.rows(shownKey, environmentId),
239 ),
240 );
241 return () => {
242 for (const release of releases) release();
243 };
244 }, [shownKey]);
245 return {
246 matches: visible.matches,
247 query: visible.query,
248 isPending,
249 };
251​
252export function useBranches(input: {
253 readonly environmentId: EnvironmentId | null;
254 readonly cwd: string | null;
255 readonly query?: string | null;
256}) {
257 const query = input.query?.trim() ?? "";
258 return useEnvironmentQuery(
259 input.environmentId !== null && input.cwd !== null
260 ? vcsEnvironment.listRefs({
261 environmentId: input.environmentId,
262 input: {
263 cwd: input.cwd,
264 ...(query.length > 0 ? { query } : {}),
265 limit: VCS_REF_LIST_LIMIT,
266 },
267 })
268 : null,
269 );
271​
272export function usePaginatedBranches(target: VcsRefTarget) {
273 const query = target.query?.trim() ?? "";
274 const targetKey =
275 target.environmentId !== null && target.cwd !== null
276 ? JSON.stringify([target.environmentId, target.cwd, query])
277 : null;
278 const [pagination, setPagination] = useState<{
279 readonly targetKey: string | null;
280 readonly cursors: ReadonlyArray<number | undefined>;
281 }>({
282 targetKey,
283 cursors: INITIAL_BRANCH_CURSORS,
284 });
285 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
286 const pageAtoms =
287 target.environmentId !== null && target.cwd !== null
288 ? cursors.map((cursor) =>
289 vcsEnvironment.listRefs({
290 environmentId: target.environmentId!,
291 input: {
292 cwd: target.cwd!,
293 ...(query.length > 0 ? { query } : {}),
294 ...(cursor === undefined ? {} : { cursor }),
295 limit: VCS_REF_LIST_LIMIT,
296 },
297 }),
298 )
299 : [];
300 const pagesAtom = Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
301 Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
302 );
303 const results = useAtomValue(pagesAtom);
304 const values = results.flatMap((result) => {
305 const value = Option.getOrNull(AsyncResult.value(result));
306 return value === null ? [] : [value];
307 });
308 const refs = new Map<string, VcsRef>();
309 for (const value of values) {
310 for (const ref of value.refs) {
311 refs.set(ref.name, ref);
312 }
313 }
314 const first = values[0] ?? null;
315 const last = values.at(-1) ?? null;
316 const data: VcsListRefsResult | null =
317 first === null || last === null
318 ? null
319 : {
320 refs: [...refs.values()],
321 isRepo: first.isRepo,
322 hasPrimaryRemote: first.hasPrimaryRemote,
323 nextCursor: last.nextCursor,
324 totalCount: Math.max(...values.map((value) => value.totalCount)),
325 };
326 const lastResult = results.at(-1);
327 const isFetchingNextPage =
328 results.length > 1 &&
329 lastResult?.waiting === true &&
330 Option.isNone(AsyncResult.value(lastResult));
331 const failed = results.find((result) => result._tag === "Failure");
332 const error =
333 failed?._tag === "Failure"
334 ? (() => {
335 const cause = Cause.squash(failed.cause);
336 return cause instanceof Error && cause.message.trim().length > 0
337 ? cause.message
338 : "Failed to load refs.";
339 })()
340 : null;
341 const refresh = () => {
342 const firstPage = pageAtoms[0];
343 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
344 if (firstPage !== undefined) {
345 appAtomRegistry.refresh(firstPage);
346 }
347 };
348 const loadNext = () => {
349 if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {
350 return;
351 }
352 setPagination((current) => {
353 const currentCursors =
354 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
355 return currentCursors.includes(data.nextCursor!)
356 ? { targetKey, cursors: currentCursors }
357 : { targetKey, cursors: [...currentCursors, data.nextCursor!] };
358 });
359 };
360​
361 return {
362 data,
363 refs: data?.refs ?? EMPTY_REFS,
364 error,
365 isPending: results.some((result) => result.waiting),
366 isFetchingNextPage,
367 refresh,
368 loadNext,
369 };
371​
372export function useComposerPathSearch(target: ComposerPathSearchTarget) {
373 const query = normalizeComposerPathSearchQuery(target.query);
374 const normalizedTarget = useMemo(
375 () => ({ environmentId: target.environmentId, cwd: target.cwd, query }),
376 [target.environmentId, target.cwd, query],
377 );
378 const debouncedTarget = useDebouncedValue(normalizedTarget, COMPOSER_PATH_SEARCH_DEBOUNCE_MS);
379 const fileAccessSession = useEnvironmentQuery(
380 debouncedTarget.environmentId === null
381 ? null
382 : environmentSession.sessionStateAtom(debouncedTarget.environmentId),
383 );
384 const fileEnvironment = useEnvironmentPresentation(debouncedTarget.environmentId);
385 const fileAccess = resolveFilesystemReadAccess({
386 isCatalogReady: fileEnvironment.isReady,
387 connection: fileEnvironment.presentation?.connection ?? null,
388 session: fileAccessSession.data,
389 sessionError: fileAccessSession.error,
390 });
391 const { canReadFiles } = fileAccess;
392 const searchTarget =
393 debouncedTarget.environmentId !== null &&
394 debouncedTarget.cwd !== null &&
395 debouncedTarget.query.length > 0
396 ? {
397 environmentId: debouncedTarget.environmentId,
398 input: {
399 cwd: debouncedTarget.cwd,
400 query: debouncedTarget.query,
401 limit: COMPOSER_PATH_SEARCH_LIMIT,
402 },
403 }
404 : null;
405 const result = useEnvironmentQuery(
406 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
407 );
408 const hasTarget = searchTarget !== null;
409​
410 return {
411 entries: result.data?.entries ?? [],
412 error:
413 !hasTarget || fileAccess.isPending
414 ? null
415 : canReadFiles
416 ? result.error
417 : (fileAccess.error ?? "This connection cannot search host files."),
418 isPending:
419 normalizedTarget.query !== debouncedTarget.query ||
420 (hasTarget && (fileAccess.isPending || result.isPending)),
421 refresh: result.refresh,
422 };
424​
425export function useCheckpointDiff(target: CheckpointDiffTarget) {
426 const targets = buildCheckpointDiffTargets(target);
427 const fullThread = useEnvironmentQuery(
428 targets.fullThread === null
429 ? null
430 : orchestrationEnvironment.fullThreadDiff(targets.fullThread),
431 );
432 const turn = useEnvironmentQuery(
433 targets.turn === null ? null : orchestrationEnvironment.turnDiff(targets.turn),
434 );
435 return targets.fullThread === null ? turn : fullThread;
437​
438export function useTurnItemDetail(
439 target: {
440 readonly environmentId: EnvironmentId;
441 readonly row: OrchestrationV2ProjectedTurnItem;
442 } | null,
443) {
444 return useEnvironmentQuery(
445 target === null
446 ? null
447 : orchestrationEnvironment.turnItem({
448 environmentId: target.environmentId,
449 input: {
450 threadId: target.row.sourceThreadId,
451 itemId: target.row.sourceItemId,
452 revision: turnItemDetailRevision(target.row.item),
453 },
454 }),
455 );