Open History to see the last commit
1import {
2 legacyThreadPullRequestKey,
3 threadPullRequestKeyOf,
4} from "@t3tools/client-runtime/thread-pull-requests";
5import {
6 composerPullRequestsFromLinks,
7 filterComposerPullRequestMatches,
8 withLinkedComposerPullRequestsFirst,
9} from "@t3tools/shared/composerPullRequestMatches";
10import { foldPullRequestCompletionSearch } from "@t3tools/shared/pullRequestComposerTrigger";
11import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
12import { environmentSession } from "./session";
13import { useEnvironmentPresentation } from "./presentation";
14import { mergeBranchRefPages, type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
15import type {
16 EnvironmentId,
17 OrchestrationV2ProjectedTurnItem,
18 ProjectId,
19 ThreadPullRequestLink,
20 VcsListRefsInput,
21 VcsListRefsResult,
22 VcsRef,
23} from "@t3tools/contracts";
24import {
25 createThreadSearchResultsAtomFamily,
26 makeThreadSearchKey,
27 visibleThreadSearch,
28 type EnvironmentThreadSearchMatch,
29 type SettledThreadSearch,
30 type ThreadSearchResultsState,
31 type ThreadSearchScope,
32} from "@t3tools/client-runtime/state/thread-search";
33import { THREAD_SEARCH_QUERY_MAX_LENGTH, trimAsciiWhitespace } from "@t3tools/contracts";
34import { messageSearchTokens } from "@t3tools/shared/paletteSearch";
35import { useAtomValue } from "@effect/atom-react";
36import * as Cause from "effect/Cause";
37import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
38import * as Option from "effect/Option";
39import { AsyncResult, Atom } from "effect/reactivity";
40import { useEffect, useMemo, useState } from "react";
41
42import { appAtomRegistry } from "./atom-registry";
43import { orchestrationEnvironment } from "./orchestration";
44import { olderSettledThreads, threadFamilies } from "./threads";
45import { projectEnvironment } from "./projects";
46import { useEnvironmentQuery } from "./query";
47import { msg, useMessages } from "gt-react-native";
48import { vcsEnvironment } from "./vcs";
49import { composerPullRequests } from "./pull-requests";
50import {
51 buildCheckpointDiffTargets,
52 normalizeComposerPathSearchQuery,
53 type CheckpointDiffTarget,
54} from "./queryTargets";
55
56const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
57const COMPOSER_PATH_SEARCH_LIMIT = 20;
58const THREAD_SEARCH_DEBOUNCE_MS = 120;
59const VCS_REF_LIST_LIMIT = 100;
60const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
61const INITIAL_BRANCH_CURSORS = [undefined] as const;
62const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
63const EMPTY_THREAD_SEARCH_ATOM = Atom.make<ThreadSearchResultsState>({
64 matches: EMPTY_THREAD_SEARCH_MATCHES,
65 isLoading: false,
66 failed: false,
67 rows: [],
68}).pipe(Atom.withLabel("mobile:thread-search:empty"));
69
70const olderSettledBeforeAtom = Atom.family((environmentId: EnvironmentId) =>
71 Atom.make((get) => get(olderSettledThreads.olderSettledAtom(environmentId))?.before ?? null).pipe(
72 Atom.withLabel(`mobile:older-settled-before:${environmentId}`),
73 ),
74);
75// Whether any of these environments leaves older settled threads out, so short queries matter.
76const anyOlderSettledAtom = Atom.family((environmentIdsKey: string) =>
77 Atom.make((get) =>
78 (JSON.parse(environmentIdsKey) as ReadonlyArray<EnvironmentId>).some(
79 (environmentId) => get(olderSettledBeforeAtom(environmentId)) !== null,
80 ),
81 ).pipe(Atom.withLabel(`mobile:any-older-settled:${environmentIdsKey}`)),
82);
83const threadSearch = createThreadSearchResultsAtomFamily({
84 getSearchAtom: (environmentId, input) =>
85 input.olderSettledBefore === undefined
86 ? orchestrationEnvironment.threadSearch({ environmentId, input })
87 : olderSettledThreads.searchAtom(environmentId, input),
88 olderSettledBefore: olderSettledBeforeAtom,
89 labelPrefix: "mobile:thread-search",
90});
91
92export interface ComposerPathSearchTarget {
93 readonly environmentId: EnvironmentId | null;
94 readonly cwd: string | null;
95 readonly query: string | null;
96}
97
98export function useDebouncedValue<A>(value: A, delayMs: number): A {
99 const [debounced, setDebounced] = useState(value);
100
101 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- timer that publishes the value after the delay and clears on change
102 useEffect(() => {
103 const timer = setTimeout(() => {
104 setDebounced(value);
105 }, delayMs);
106 return () => {
107 clearTimeout(timer);
108 };
109 }, [delayMs, value]);
110
111 return debounced;
112}
113
114export function useComposerPullRequestSearch(input: {
115 environmentId: EnvironmentId | null;
116 projectId: ProjectId | null;
117 repository: string | null;
118 threadPullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
119 query: string | null;
120}) {
121 const query = useDebouncedValue(input.query, 180);
122 const linked =
123 input.projectId === null
124 ? []
125 : composerPullRequestsFromLinks(input.threadPullRequests ?? [], input.projectId);
126 const ready =
127 query === input.query &&
128 query !== null &&
129 input.environmentId !== null &&
130 input.projectId !== null &&
131 input.repository !== null;
132 const numeric = query !== null && /^\d*$/.test(query);
133 const list = useEnvironmentQuery(
134 ready
135 ? composerPullRequests.list({
136 environmentId: input.environmentId!,
137 input: {
138 projectId: input.projectId!,
139 state: "all",
140 limit: 200,
141 ...(!numeric && query ? { query } : {}),
142 },
143 })
144 : null,
145 );
146 const number = numeric && query ? Number(query) : null;
147 const hasExact = list.data?.entries.some(
148 (entry) =>
149 entry.number === number && entry.repository.toLowerCase() === input.repository?.toLowerCase(),
150 );
151 const exact = useEnvironmentQuery(
152 ready && number !== null && Number.isSafeInteger(number) && number > 0 && !hasExact
153 ? composerPullRequests.detail({
154 environmentId: input.environmentId!,
155 input: { projectId: input.projectId!, repository: input.repository!, number },
156 })
157 : null,
158 );
159 // Only the host: the URL's full repository path would not match the project's selector.
160 const exactEntry = exact.data
161 ? { ...exact.data, host: legacyThreadPullRequestKey(exact.data).host }
162 : null;
163 const entries = (() => {
164 if (input.query === null || input.projectId === null || input.repository === null) return [];
165 if (/^\d*$/.test(input.query)) {
166 return filterComposerPullRequestMatches({
167 keyOf: threadPullRequestKeyOf,
168 entries: ready ? [...(exactEntry ? [exactEntry] : []), ...(list.data?.entries ?? [])] : [],
169 linked,
170 projectId: input.projectId,
171 repository: input.repository,
172 query: input.query,
173 limit: 20,
174 });
175 }
176 if (!ready) {
177 return withLinkedComposerPullRequestsFirst({
178 keyOf: threadPullRequestKeyOf,
179 matches: [],
180 linked,
181 query: input.query,
182 limit: 20,
183 });
184 }
185 const words = foldPullRequestCompletionSearch(query ?? "")
186 .split(/\s+/)
187 .filter(Boolean);
188 const found = [...(exactEntry ? [exactEntry] : []), ...(list.data?.entries ?? [])].filter(
189 (entry) =>
190 entry.projectId === input.projectId &&
191 entry.repository.toLowerCase() === input.repository?.toLowerCase() &&
192 words.every((word) =>
193 foldPullRequestCompletionSearch(
194 `${entry.title} ${entry.headBranch} ${entry.baseBranch}`,
195 ).includes(word),
196 ),
197 );
198 const unique = new Map<string, (typeof found)[number]>();
199 for (const entry of found) {
200 const key = threadPullRequestKeyOf(entry);
201 if (!unique.has(key)) unique.set(key, entry);
202 }
203 return withLinkedComposerPullRequestsFirst({
204 keyOf: threadPullRequestKeyOf,
205 matches: [...unique.values()].sort((left, right) =>
206 right.updatedAt.localeCompare(left.updatedAt),
207 ),
208 linked,
209 query: query ?? "",
210 limit: 20,
211 });
212 })();
213 return {
214 entries,
215 isPending: input.query !== null && (query !== input.query || list.isPending || exact.isPending),
216 error: list.error ?? list.data?.errors[0]?.message ?? exact.error,
217 };
218}
219
220/**
221 * Server matches for a thread search: message hits, and on environments that leave older settled
222 * threads out of the shell, the rows of the best older matches, mounted into the thread list while
223 * they show so the caller's own ranking finds them.
224 */
225export function useThreadSearch(
226 environmentIds: ReadonlyArray<EnvironmentId>,
227 query: string,
228 scope: ThreadSearchScope = {},
229): {
230 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
231 /** The query `matches` are for, which lags the typed one while a search runs. */
232 readonly query: string;
233 readonly isPending: boolean;
234 /** No environment could run the search for the current query, so an empty result is not "no matches". */
235 readonly failed: boolean;
236} {
237 // A pasted wall of text searches by its start rather than failing the request.
238 const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim();
239 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
240 const anyOlderSettled = useAtomValue(anyOlderSettledAtom(JSON.stringify(environmentIds)));
241 // Messages need a word of three or more letters; older settled titles match from two.
242 const canSearch =
243 environmentIds.length > 0 &&
244 ((scope.titlesOnly !== true && messageSearchTokens(normalizedQuery).long.length > 0) ||
245 (anyOlderSettled && normalizedQuery.length >= 2));
246 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
247 const searchKeyOf = (searchQuery: string) =>
248 makeThreadSearchKey(environmentIds, searchQuery, scope);
249 const searchKey = settledQuery === null ? null : searchKeyOf(settledQuery);
250 const result = useAtomValue(
251 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearch.results(searchKey),
252 );
253 const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading);
254 const failed = settledQuery !== null && !result.isLoading && result.failed;
255 // What fast environments returned shows without waiting for a slow one;
256 // callers keep shown rows in place with `nextShownOrder`.
257 const ready =
258 settledQuery !== null &&
259 (!result.isLoading || result.matches.length > 0 || result.rows.length > 0)
260 ? { query: settledQuery, matches: result.matches }
261 : null;
262 // Kept from earlier renders: React's pattern for information from previous renders.
263 const [previous, setPrevious] = useState<SettledThreadSearch | null>(null);
264 if (ready !== null && previous?.matches !== ready.matches) setPrevious(ready);
265 const visible = canSearch
266 ? visibleThreadSearch(normalizedQuery, ready, previous)
267 : { query: "", matches: EMPTY_THREAD_SEARCH_MATCHES };
268 // The shown results' rows stay mounted until newer results replace them.
269 const shownKey = visible.query === "" ? null : searchKeyOf(visible.query);
270 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mounts the shown search results' rows into the shared thread registry until newer results replace them
271 useEffect(() => {
272 if (shownKey === null) return;
273 const environments = (JSON.parse(shownKey) as [ReadonlyArray<EnvironmentId>])[0];
274 const releases = environments.map((environmentId) =>
275 threadFamilies.mountRows(
276 appAtomRegistry,
277 environmentId,
278 `search:${shownKey}`,
279 threadSearch.rows(shownKey, environmentId),
280 ),
281 );
282 return () => {
283 for (const release of releases) release();
284 };
285 }, [shownKey]);
286 return {
287 matches: visible.matches,
288 query: visible.query,
289 isPending,
290 failed,
291 };
292}
293
294export function useBranches(input: {
295 readonly environmentId: EnvironmentId | null;
296 readonly cwd: string | null;
297 readonly query?: string | null;
298}) {
299 const query = trimAsciiWhitespace(input.query ?? "");
300 return useEnvironmentQuery(
301 input.environmentId !== null && input.cwd !== null
302 ? vcsEnvironment.listRefs({
303 environmentId: input.environmentId,
304 input: {
305 cwd: input.cwd,
306 ...(query.length > 0 ? { query } : {}),
307 limit: VCS_REF_LIST_LIMIT,
308 },
309 })
310 : null,
311 );
312}
313
314export function usePaginatedBranches(
315 target: VcsRefTarget & { readonly refKind?: VcsListRefsInput["refKind"] },
316) {
317 const resolve = useMessages();
318 const query = trimAsciiWhitespace(target.query ?? "");
319 const { refKind } = target;
320 const targetKey =
321 target.environmentId !== null && target.cwd !== null
322 ? JSON.stringify([target.environmentId, target.cwd, query, refKind])
323 : null;
324 const [pagination, setPagination] = useState<{
325 readonly targetKey: string | null;
326 readonly cursors: ReadonlyArray<number | undefined>;
327 }>({
328 targetKey,
329 cursors: INITIAL_BRANCH_CURSORS,
330 });
331 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
332 const pageAtoms = useMemo(
333 () =>
334 target.environmentId !== null && target.cwd !== null
335 ? cursors.map((cursor) =>
336 vcsEnvironment.listRefs({
337 environmentId: target.environmentId!,
338 input: {
339 cwd: target.cwd!,
340 ...(query.length > 0 ? { query } : {}),
341 ...(cursor === undefined ? {} : { cursor }),
342 ...(refKind === undefined ? {} : { refKind }),
343 limit: VCS_REF_LIST_LIMIT,
344 },
345 }),
346 )
347 : [],
348 [target.environmentId, target.cwd, query, refKind, cursors],
349 );
350 const pagesAtom = useMemo(
351 () =>
352 Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
353 Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
354 ),
355 [pageAtoms, targetKey],
356 );
357 const results = useAtomValue(pagesAtom);
358 const values = results.flatMap((result) => {
359 const value = AsyncResult.getOrElse(result, () => null);
360 return value === null ? [] : [value];
361 });
362 const first = values[0] ?? null;
363 const last = values.at(-1) ?? null;
364 const data: VcsListRefsResult | null =
365 first === null || last === null
366 ? null
367 : {
368 refs: mergeBranchRefPages(values),
369 isRepo: first.isRepo,
370 hasPrimaryRemote: first.hasPrimaryRemote,
371 nextCursor: last.nextCursor,
372 totalCount: Math.max(...values.map((value) => value.totalCount)),
373 };
374 const failed = results.find((result) => result._tag === "Failure");
375 const isPending = results.some((result) => result.waiting);
376 // A new search keeps showing the last refs from the same checkout until its first page arrives.
377 const sourceKey = targetKey === null ? null : JSON.stringify([target.environmentId, target.cwd]);
378 const [settled, setSettled] = useState<{
379 readonly sourceKey: string;
380 readonly results: typeof results;
381 readonly data: VcsListRefsResult;
382 } | null>(null);
383 if (data !== null && sourceKey !== null && settled?.results !== results) {
384 setSettled({ sourceKey, results, data });
385 }
386 const shownData =
387 data === null && isPending && failed === undefined && settled?.sourceKey === sourceKey
388 ? settled.data
389 : data;
390 const lastResult = results.at(-1);
391 const isFetchingNextPage =
392 results.length > 1 &&
393 lastResult?.waiting === true &&
394 Option.isNone(AsyncResult.value(lastResult));
395 const error =
396 failed?._tag === "Failure"
397 ? (() => {
398 const cause = Cause.squash(failed.cause);
399 return cause instanceof Error && cause.message.trim().length > 0
400 ? cause.message
401 : resolve(msg("Failed to load refs."));
402 })()
403 : null;
404 const refresh = () => {
405 const firstPage = pageAtoms[0];
406 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
407 if (firstPage !== undefined) {
408 appAtomRegistry.refresh(firstPage);
409 }
410 };
411 const loadNext = () => {
412 if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {
413 return;
414 }
415 setPagination((current) => {
416 const currentCursors =
417 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
418 return currentCursors.includes(data.nextCursor!)
419 ? { targetKey, cursors: currentCursors }
420 : { targetKey, cursors: [...currentCursors, data.nextCursor!] };
421 });
422 };
423
424 return {
425 data: shownData,
426 refs: shownData?.refs ?? EMPTY_REFS,
427 error,
428 isPending,
429 isFetchingNextPage,
430 refresh,
431 loadNext,
432 };
433}
434
435export function useComposerPathSearch(target: ComposerPathSearchTarget) {
436 const resolve = useMessages();
437 const query = normalizeComposerPathSearchQuery(target.query);
438 const normalizedTarget = { environmentId: target.environmentId, cwd: target.cwd, query };
439 const debouncedTarget = useDebouncedValue(normalizedTarget, COMPOSER_PATH_SEARCH_DEBOUNCE_MS);
440 const fileAccessSession = useEnvironmentQuery(
441 debouncedTarget.environmentId === null
442 ? null
443 : environmentSession.sessionStateAtom(debouncedTarget.environmentId),
444 );
445 const fileEnvironment = useEnvironmentPresentation(debouncedTarget.environmentId);
446 const fileAccess = resolveFilesystemReadAccess(
447 {
448 isCatalogReady: fileEnvironment.isReady,
449 connection: fileEnvironment.presentation?.connection ?? null,
450 session: fileAccessSession.data,
451 sessionError: fileAccessSession.error,
452 },
453 resolve,
454 );
455 const { canReadFiles } = fileAccess;
456 const searchTarget =
457 debouncedTarget.environmentId !== null &&
458 debouncedTarget.cwd !== null &&
459 debouncedTarget.query !== null
460 ? {
461 environmentId: debouncedTarget.environmentId,
462 input: {
463 cwd: debouncedTarget.cwd,
464 query: debouncedTarget.query.slice(0, 256).replace(/[\uD800-\uDBFF]$/, ""),
465 limit: COMPOSER_PATH_SEARCH_LIMIT,
466 },
467 }
468 : null;
469 const result = useEnvironmentQuery(
470 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
471 );
472 const hasTarget = searchTarget !== null;
473 const isSameCheckout =
474 normalizedTarget.environmentId === debouncedTarget.environmentId &&
475 normalizedTarget.cwd === debouncedTarget.cwd;
476 // A new query keeps showing the last entries from the same checkout until its answer arrives.
477 const sourceKey =
478 searchTarget === null
479 ? null
480 : JSON.stringify([searchTarget.environmentId, searchTarget.input.cwd]);
481 const [settled, setSettled] = useState<{
482 readonly sourceKey: string;
483 readonly data: NonNullable<typeof result.data>;
484 } | null>(null);
485 if (result.data !== null && sourceKey !== null && settled?.data !== result.data) {
486 setSettled({ sourceKey, data: result.data });
487 }
488 const shownData =
489 result.data === null && result.isPending && !result.error && settled?.sourceKey === sourceKey
490 ? settled.data
491 : result.data;
492
493 return {
494 // Entries from another checkout must not be offered while the new one is debounced.
495 entries: isSameCheckout ? (shownData?.entries ?? []) : [],
496 error:
497 !hasTarget || fileAccess.isPending
498 ? null
499 : canReadFiles
500 ? result.error
501 : (fileAccess.error ?? resolve(msg("This connection cannot search host files."))),
502 isPending:
503 !isSameCheckout ||
504 normalizedTarget.query !== debouncedTarget.query ||
505 (hasTarget && (fileAccess.isPending || result.isPending)),
506 refresh: result.refresh,
507 };
508}
509
510export function useCheckpointDiff(target: CheckpointDiffTarget) {
511 const targets = buildCheckpointDiffTargets(target);
512 const fullThread = useEnvironmentQuery(
513 targets.fullThread === null
514 ? null
515 : orchestrationEnvironment.fullThreadDiff(targets.fullThread),
516 );
517 const turn = useEnvironmentQuery(
518 targets.turn === null ? null : orchestrationEnvironment.turnDiff(targets.turn),
519 );
520 return targets.fullThread === null ? turn : fullThread;
521}
522
523export function useTurnItemDetail(
524 target: {
525 readonly environmentId: EnvironmentId;
526 readonly row: OrchestrationV2ProjectedTurnItem;
527 } | null,
528) {
529 return useEnvironmentQuery(
530 target === null
531 ? null
532 : orchestrationEnvironment.turnItem({
533 environmentId: target.environmentId,
534 input: {
535 threadId: target.row.sourceThreadId,
536 itemId: target.row.sourceItemId,
537 revision: turnItemDetailRevision(target.row.item),
538 },
539 }),
540 );
541}