Open History to see the last commit
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 ThreadId,
14 ThreadPullRequestLink,
15 VcsListRefsResult,
16 VcsRef,
17} from "@t3tools/contracts";
18import {
19 createThreadSearchResultsAtomFamily,
20 makeThreadSearchKey,
21 type EnvironmentThreadSearchMatch,
22} from "@t3tools/client-runtime/state/thread-search";
23import { useAtomValue } from "@effect/atom-react";
24import * as Cause from "effect/Cause";
25import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
26import * as Option from "effect/Option";
27import { AsyncResult, Atom } from "effect/reactivity";
28import { useCallback, useEffect, useMemo, useState } from "react";
29
30import { appAtomRegistry } from "./atom-registry";
31import { orchestrationEnvironment } from "./orchestration";
32import { projectEnvironment } from "./projects";
33import { useEnvironmentQuery } from "./query";
34import { vcsEnvironment } from "./vcs";
35import { composerPullRequests } from "./pull-requests";
36import {
37 buildCheckpointDiffTargets,
38 normalizeComposerPathSearchQuery,
39 type CheckpointDiffTarget,
40} from "./queryTargets";
41
42const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
43const COMPOSER_PATH_SEARCH_LIMIT = 20;
44const THREAD_SEARCH_DEBOUNCE_MS = 200;
45const VCS_REF_LIST_LIMIT = 100;
46const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
47const INITIAL_BRANCH_CURSORS = [undefined] as const;
48const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
49const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
50 matches: EMPTY_THREAD_SEARCH_MATCHES,
51 isLoading: false,
52}).pipe(Atom.withLabel("mobile:thread-search:empty"));
53
54const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
55 getSearchAtom: (environmentId, query) =>
56 orchestrationEnvironment.threadSearch({
57 environmentId,
58 input: { query },
59 }),
60 labelPrefix: "mobile:thread-search",
61});
62
63export interface ComposerPathSearchTarget {
64 readonly environmentId: EnvironmentId | null;
65 readonly cwd: string | null;
66 readonly query: string | null;
67}
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;
82}
83
84export function useComposerPullRequestSearch(input: {
85 environmentId: EnvironmentId | null;
86 projectId: ProjectId | null;
87 repository: string | null;
88 threadPullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
89 query: string | null;
90}) {
91 const query = useDebouncedValue(input.query, 180);
92 const linked = useMemo(
93 () =>
94 input.projectId === null
95 ? []
96 : composerPullRequestsFromLinks(input.threadPullRequests ?? [], input.projectId),
97 [input.projectId, input.threadPullRequests],
98 );
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 = useMemo(() => {
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 }, [ready, exact.data, list.data, linked, input.projectId, input.repository, numeric, query]);
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 };
164}
165
166export function useThreadSearch(
167 environmentIds: ReadonlyArray<EnvironmentId>,
168 query: string,
169): {
170 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
171 readonly isPending: boolean;
172} {
173 const normalizedQuery = query.trim();
174 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
175 const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
176 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
177 const searchKey = useMemo(
178 () => (settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery)),
179 [environmentIds, settledQuery],
180 );
181 const result = useAtomValue(
182 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
183 );
184 const isDebouncing = canSearch && normalizedQuery !== debouncedQuery;
185 return {
186 matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches,
187 isPending: canSearch && (isDebouncing || result.isLoading),
188 };
189}
190
191export function useBranches(input: {
192 readonly environmentId: EnvironmentId | null;
193 readonly cwd: string | null;
194 readonly query?: string | null;
195}) {
196 const query = input.query?.trim() ?? "";
197 return useEnvironmentQuery(
198 input.environmentId !== null && input.cwd !== null
199 ? vcsEnvironment.listRefs({
200 environmentId: input.environmentId,
201 input: {
202 cwd: input.cwd,
203 ...(query.length > 0 ? { query } : {}),
204 limit: VCS_REF_LIST_LIMIT,
205 },
206 })
207 : null,
208 );
209}
210
211export function usePaginatedBranches(target: VcsRefTarget) {
212 const query = target.query?.trim() ?? "";
213 const targetKey =
214 target.environmentId !== null && target.cwd !== null
215 ? JSON.stringify([target.environmentId, target.cwd, query])
216 : null;
217 const [pagination, setPagination] = useState<{
218 readonly targetKey: string | null;
219 readonly cursors: ReadonlyArray<number | undefined>;
220 }>({
221 targetKey,
222 cursors: INITIAL_BRANCH_CURSORS,
223 });
224 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
225 const pageAtoms = useMemo(
226 () =>
227 target.environmentId !== null && target.cwd !== null
228 ? cursors.map((cursor) =>
229 vcsEnvironment.listRefs({
230 environmentId: target.environmentId!,
231 input: {
232 cwd: target.cwd!,
233 ...(query.length > 0 ? { query } : {}),
234 ...(cursor === undefined ? {} : { cursor }),
235 limit: VCS_REF_LIST_LIMIT,
236 },
237 }),
238 )
239 : [],
240 [cursors, query, target.cwd, target.environmentId],
241 );
242 const pagesAtom = useMemo(
243 () =>
244 Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
245 Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
246 ),
247 [pageAtoms, targetKey],
248 );
249 const results = useAtomValue(pagesAtom);
250 const values = results.flatMap((result) => {
251 const value = Option.getOrNull(AsyncResult.value(result));
252 return value === null ? [] : [value];
253 });
254 const refs = new Map<string, VcsRef>();
255 for (const value of values) {
256 for (const ref of value.refs) {
257 refs.set(ref.name, ref);
258 }
259 }
260 const first = values[0] ?? null;
261 const last = values.at(-1) ?? null;
262 const data: VcsListRefsResult | null =
263 first === null || last === null
264 ? null
265 : {
266 refs: [...refs.values()],
267 isRepo: first.isRepo,
268 hasPrimaryRemote: first.hasPrimaryRemote,
269 nextCursor: last.nextCursor,
270 totalCount: Math.max(...values.map((value) => value.totalCount)),
271 };
272 const lastResult = results.at(-1);
273 const isFetchingNextPage =
274 results.length > 1 &&
275 lastResult?.waiting === true &&
276 Option.isNone(AsyncResult.value(lastResult));
277 const failed = results.find((result) => result._tag === "Failure");
278 const error =
279 failed?._tag === "Failure"
280 ? (() => {
281 const cause = Cause.squash(failed.cause);
282 return cause instanceof Error && cause.message.trim().length > 0
283 ? cause.message
284 : "Failed to load refs.";
285 })()
286 : null;
287 const refresh = useCallback(() => {
288 const firstPage = pageAtoms[0];
289 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
290 if (firstPage !== undefined) {
291 appAtomRegistry.refresh(firstPage);
292 }
293 }, [pageAtoms, targetKey]);
294 const loadNext = useCallback(() => {
295 if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {
296 return;
297 }
298 setPagination((current) => {
299 const currentCursors =
300 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
301 return currentCursors.includes(data.nextCursor!)
302 ? { targetKey, cursors: currentCursors }
303 : { targetKey, cursors: [...currentCursors, data.nextCursor!] };
304 });
305 }, [data?.nextCursor, targetKey]);
306
307 return {
308 data,
309 refs: data?.refs ?? EMPTY_REFS,
310 error,
311 isPending: results.some((result) => result.waiting),
312 isFetchingNextPage,
313 refresh,
314 loadNext,
315 };
316}
317
318export function useComposerPathSearch(target: ComposerPathSearchTarget) {
319 const normalizedTarget = useMemo(
320 () => ({
321 environmentId: target.environmentId,
322 cwd: target.cwd,
323 query: normalizeComposerPathSearchQuery(target.query),
324 }),
325 [target.cwd, target.environmentId, target.query],
326 );
327 const debouncedTarget = useDebouncedValue(normalizedTarget, COMPOSER_PATH_SEARCH_DEBOUNCE_MS);
328 const fileAccessSession = useEnvironmentQuery(
329 debouncedTarget.environmentId === null
330 ? null
331 : environmentSession.sessionStateAtom(debouncedTarget.environmentId),
332 );
333 const fileEnvironment = useEnvironmentPresentation(debouncedTarget.environmentId);
334 const fileAccess = resolveFilesystemReadAccess({
335 isCatalogReady: fileEnvironment.isReady,
336 connection: fileEnvironment.presentation?.connection ?? null,
337 session: fileAccessSession.data,
338 sessionError: fileAccessSession.error,
339 });
340 const { canReadFiles } = fileAccess;
341 const searchTarget =
342 debouncedTarget.environmentId !== null &&
343 debouncedTarget.cwd !== null &&
344 debouncedTarget.query.length > 0
345 ? {
346 environmentId: debouncedTarget.environmentId,
347 input: {
348 cwd: debouncedTarget.cwd,
349 query: debouncedTarget.query,
350 limit: COMPOSER_PATH_SEARCH_LIMIT,
351 },
352 }
353 : null;
354 const result = useEnvironmentQuery(
355 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
356 );
357 const hasTarget = searchTarget !== null;
358
359 return {
360 entries: result.data?.entries ?? [],
361 error:
362 !hasTarget || fileAccess.isPending
363 ? null
364 : canReadFiles
365 ? result.error
366 : (fileAccess.error ?? "This connection cannot search host files."),
367 isPending:
368 normalizedTarget.query !== debouncedTarget.query ||
369 (hasTarget && (fileAccess.isPending || result.isPending)),
370 refresh: result.refresh,
371 };
372}
373
374export function useCheckpointDiff(target: CheckpointDiffTarget) {
375 const targets = useMemo(
376 () => buildCheckpointDiffTargets(target),
377 [
378 target.environmentId,
379 target.fromTurnCount,
380 target.ignoreWhitespace,
381 target.threadId,
382 target.toTurnCount,
383 ],
384 );
385 const fullThread = useEnvironmentQuery(
386 targets.fullThread === null
387 ? null
388 : orchestrationEnvironment.fullThreadDiff(targets.fullThread),
389 );
390 const turn = useEnvironmentQuery(
391 targets.turn === null ? null : orchestrationEnvironment.turnDiff(targets.turn),
392 );
393 return targets.fullThread === null ? turn : fullThread;
394}
395
396export function useTurnItemDetail(
397 target: {
398 readonly environmentId: EnvironmentId;
399 readonly row: OrchestrationV2ProjectedTurnItem;
400 } | null,
401) {
402 return useEnvironmentQuery(
403 target === null
404 ? null
405 : orchestrationEnvironment.turnItem({
406 environmentId: target.environmentId,
407 input: {
408 threadId: target.row.sourceThreadId,
409 itemId: target.row.sourceItemId,
410 revision: turnItemDetailRevision(target.row.item),
411 },
412 }),
413 );
414}