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