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

queries.ts

375 lines12.3 KB

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