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