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