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 ThreadPullRequestLink,
14 VcsListRefsResult,
15 VcsRef,
16} from "@t3tools/contracts";
17import {
18 createThreadSearchResultsAtomFamily,
19 makeThreadSearchKey,
20 type EnvironmentThreadSearchMatch,
21} from "@t3tools/client-runtime/state/thread-search";
22import { useAtomValue } from "@effect/atom-react";
23import * as Cause from "effect/Cause";
24import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
25import * as Option from "effect/Option";
26import { AsyncResult, Atom } from "effect/reactivity";
27import { useEffect, useState } from "react";
28
29import { appAtomRegistry } from "./atom-registry";
30import { orchestrationEnvironment } from "./orchestration";
31import { projectEnvironment } from "./projects";
32import { useEnvironmentQuery } from "./query";
33import { vcsEnvironment } from "./vcs";
34import { composerPullRequests } from "./pull-requests";
35import {
36 buildCheckpointDiffTargets,
37 normalizeComposerPathSearchQuery,
38 type CheckpointDiffTarget,
39} from "./queryTargets";
40
41const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
42const COMPOSER_PATH_SEARCH_LIMIT = 20;
43const THREAD_SEARCH_DEBOUNCE_MS = 200;
44const VCS_REF_LIST_LIMIT = 100;
45const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
46const INITIAL_BRANCH_CURSORS = [undefined] as const;
47const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
48const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
49 matches: EMPTY_THREAD_SEARCH_MATCHES,
50 isLoading: false,
51}).pipe(Atom.withLabel("mobile:thread-search:empty"));
52
53const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
54 getSearchAtom: (environmentId, query) =>
55 orchestrationEnvironment.threadSearch({
56 environmentId,
57 input: { query },
58 }),
59 labelPrefix: "mobile:thread-search",
60});
61
62export interface ComposerPathSearchTarget {
63 readonly environmentId: EnvironmentId | null;
64 readonly cwd: string | null;
65 readonly query: string | null;
66}
67
68export function useDebouncedValue<A>(value: A, delayMs: number): A {
69 const [debounced, setDebounced] = useState(value);
70
71 useEffect(() => {
72 const timer = setTimeout(() => {
73 setDebounced(value);
74 }, delayMs);
75 return () => {
76 clearTimeout(timer);
77 };
78 }, [delayMs, value]);
79
80 return debounced;
81}
82
83export function useComposerPullRequestSearch(input: {
84 environmentId: EnvironmentId | null;
85 projectId: ProjectId | null;
86 repository: string | null;
87 threadPullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
88 query: string | null;
89}) {
90 const query = useDebouncedValue(input.query, 180);
91 const linked =
92 input.projectId === null
93 ? []
94 : composerPullRequestsFromLinks(input.threadPullRequests ?? [], input.projectId);
95 const ready =
96 query === input.query &&
97 query !== null &&
98 input.environmentId !== null &&
99 input.projectId !== null &&
100 input.repository !== null;
101 const numeric = query !== null && /^\d*$/.test(query);
102 const list = useEnvironmentQuery(
103 ready
104 ? composerPullRequests.list({
105 environmentId: input.environmentId!,
106 input: {
107 projectId: input.projectId!,
108 state: "all",
109 limit: 200,
110 ...(!numeric && query ? { query } : {}),
111 },
112 })
113 : null,
114 );
115 const number = numeric && query ? Number(query) : null;
116 const hasExact = list.data?.entries.some(
117 (entry) =>
118 entry.number === number && entry.repository.toLowerCase() === input.repository?.toLowerCase(),
119 );
120 const exact = useEnvironmentQuery(
121 ready && number !== null && Number.isSafeInteger(number) && number > 0 && !hasExact
122 ? composerPullRequests.detail({
123 environmentId: input.environmentId!,
124 input: { projectId: input.projectId!, repository: input.repository!, number },
125 })
126 : null,
127 );
128 const entries = (() => {
129 if (!ready) return [];
130 if (numeric) {
131 return filterComposerPullRequestMatches({
132 entries: [...(exact.data ? [exact.data] : []), ...(list.data?.entries ?? [])],
133 linked,
134 projectId: input.projectId!,
135 repository: input.repository!,
136 query: query ?? "",
137 limit: 20,
138 });
139 }
140 const words = (query ?? "").toLowerCase().split(/\s+/).filter(Boolean);
141 const found = [...(exact.data ? [exact.data] : []), ...(list.data?.entries ?? [])].filter(
142 (entry) =>
143 entry.projectId === input.projectId &&
144 entry.repository.toLowerCase() === input.repository?.toLowerCase() &&
145 words.every((word) =>
146 `${entry.title} ${entry.headBranch} ${entry.baseBranch}`.toLowerCase().includes(word),
147 ),
148 );
149 const unique = new Map<number, (typeof found)[number]>();
150 for (const entry of found) if (!unique.has(entry.number)) unique.set(entry.number, entry);
151 return [...unique.values()]
152 .sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
153 .slice(0, 20);
154 })();
155 return {
156 entries,
157 isPending: input.query !== null && (query !== input.query || list.isPending || exact.isPending),
158 error: list.error ?? list.data?.errors[0]?.message ?? exact.error,
159 };
160}
161
162export function useThreadSearch(
163 environmentIds: ReadonlyArray<EnvironmentId>,
164 query: string,
165): {
166 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
167 readonly isPending: boolean;
168} {
169 const normalizedQuery = query.trim();
170 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
171 const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
172 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
173 const searchKey =
174 settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery);
175 const result = useAtomValue(
176 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
177 );
178 const isDebouncing = canSearch && normalizedQuery !== debouncedQuery;
179 return {
180 matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches,
181 isPending: canSearch && (isDebouncing || result.isLoading),
182 };
183}
184
185export function useBranches(input: {
186 readonly environmentId: EnvironmentId | null;
187 readonly cwd: string | null;
188 readonly query?: string | null;
189}) {
190 const query = input.query?.trim() ?? "";
191 return useEnvironmentQuery(
192 input.environmentId !== null && input.cwd !== null
193 ? vcsEnvironment.listRefs({
194 environmentId: input.environmentId,
195 input: {
196 cwd: input.cwd,
197 ...(query.length > 0 ? { query } : {}),
198 limit: VCS_REF_LIST_LIMIT,
199 },
200 })
201 : null,
202 );
203}
204
205export function usePaginatedBranches(target: VcsRefTarget) {
206 const query = target.query?.trim() ?? "";
207 const targetKey =
208 target.environmentId !== null && target.cwd !== null
209 ? JSON.stringify([target.environmentId, target.cwd, query])
210 : null;
211 const [pagination, setPagination] = useState<{
212 readonly targetKey: string | null;
213 readonly cursors: ReadonlyArray<number | undefined>;
214 }>({
215 targetKey,
216 cursors: INITIAL_BRANCH_CURSORS,
217 });
218 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
219 const pageAtoms =
220 target.environmentId !== null && target.cwd !== null
221 ? cursors.map((cursor) =>
222 vcsEnvironment.listRefs({
223 environmentId: target.environmentId!,
224 input: {
225 cwd: target.cwd!,
226 ...(query.length > 0 ? { query } : {}),
227 ...(cursor === undefined ? {} : { cursor }),
228 limit: VCS_REF_LIST_LIMIT,
229 },
230 }),
231 )
232 : [];
233 const pagesAtom = Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
234 Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
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 = () => {
275 const firstPage = pageAtoms[0];
276 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
277 if (firstPage !== undefined) {
278 appAtomRegistry.refresh(firstPage);
279 }
280 };
281 const loadNext = () => {
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 };
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 };
303}
304
305export function useComposerPathSearch(target: ComposerPathSearchTarget) {
306 const normalizedTarget = {
307 environmentId: target.environmentId,
308 cwd: target.cwd,
309 query: normalizeComposerPathSearchQuery(target.query),
310 };
311 const debouncedTarget = useDebouncedValue(normalizedTarget, COMPOSER_PATH_SEARCH_DEBOUNCE_MS);
312 const fileAccessSession = useEnvironmentQuery(
313 debouncedTarget.environmentId === null
314 ? null
315 : environmentSession.sessionStateAtom(debouncedTarget.environmentId),
316 );
317 const fileEnvironment = useEnvironmentPresentation(debouncedTarget.environmentId);
318 const fileAccess = resolveFilesystemReadAccess({
319 isCatalogReady: fileEnvironment.isReady,
320 connection: fileEnvironment.presentation?.connection ?? null,
321 session: fileAccessSession.data,
322 sessionError: fileAccessSession.error,
323 });
324 const { canReadFiles } = fileAccess;
325 const searchTarget =
326 debouncedTarget.environmentId !== null &&
327 debouncedTarget.cwd !== null &&
328 debouncedTarget.query.length > 0
329 ? {
330 environmentId: debouncedTarget.environmentId,
331 input: {
332 cwd: debouncedTarget.cwd,
333 query: debouncedTarget.query,
334 limit: COMPOSER_PATH_SEARCH_LIMIT,
335 },
336 }
337 : null;
338 const result = useEnvironmentQuery(
339 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
340 );
341 const hasTarget = searchTarget !== null;
342
343 return {
344 entries: result.data?.entries ?? [],
345 error:
346 !hasTarget || fileAccess.isPending
347 ? null
348 : canReadFiles
349 ? result.error
350 : (fileAccess.error ?? "This connection cannot search host files."),
351 isPending:
352 normalizedTarget.query !== debouncedTarget.query ||
353 (hasTarget && (fileAccess.isPending || result.isPending)),
354 refresh: result.refresh,
355 };
356}
357
358export function useCheckpointDiff(target: CheckpointDiffTarget) {
359 const targets = buildCheckpointDiffTargets(target);
360 const fullThread = useEnvironmentQuery(
361 targets.fullThread === null
362 ? null
363 : orchestrationEnvironment.fullThreadDiff(targets.fullThread),
364 );
365 const turn = useEnvironmentQuery(
366 targets.turn === null ? null : orchestrationEnvironment.turnDiff(targets.turn),
367 );
368 return targets.fullThread === null ? turn : fullThread;
369}
370
371export function useTurnItemDetail(
372 target: {
373 readonly environmentId: EnvironmentId;
374 readonly row: OrchestrationV2ProjectedTurnItem;
375 } | null,
376) {
377 return useEnvironmentQuery(
378 target === null
379 ? null
380 : orchestrationEnvironment.turnItem({
381 environmentId: target.environmentId,
382 input: {
383 threadId: target.row.sourceThreadId,
384 itemId: target.row.sourceItemId,
385 revision: turnItemDetailRevision(target.row.item),
386 },
387 }),
388 );
389}