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