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

queries.ts

402 lines13.5 KB

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