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

queries.ts

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