Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 type CheckpointDiffTarget,
4 type ComposerPathSearchTarget,
5} from "@t3tools/client-runtime/state/threads";
6import {
7 createThreadSearchResultsAtomFamily,
8 makeThreadSearchKey,
9 type EnvironmentThreadSearchMatch,
10} from "@t3tools/client-runtime/state/thread-search";
11import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
12import type {
13 EnvironmentId,
14 OrchestrationThread,
15 ProjectContentMatch,
16 ProjectEntryKind,
17 ThreadId,
18 VcsListRefsResult,
19 VcsRef,
20} from "@t3tools/contracts";
21import * as Cause from "effect/Cause";
22import * as Option from "effect/Option";
23import { AsyncResult, Atom } from "effect/unstable/reactivity";
24import { useCallback, useEffect, useMemo, useState } from "react";
25
26import { appAtomRegistry } from "../rpc/atomRegistry";
27import { orchestrationEnvironment } from "./orchestration";
28import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
29import { projectContentSearch, projectEnvironment } from "./projects";
30import { useEnvironmentQuery } from "./query";
31import { useEnvironmentThread } from "./threads";
32import { vcsEnvironment } from "./vcs";
33
34const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120;
35const COMPOSER_PATH_SEARCH_LIMIT = 80;
36const PROJECT_CONTENT_SEARCH_DEBOUNCE_MS = 120;
37const PROJECT_CONTENT_SEARCH_LIMIT = 500;
38const THREAD_SEARCH_DEBOUNCE_MS = 200;
39const VCS_REF_LIST_LIMIT = 100;
40const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
41const EMPTY_CONTENT_MATCHES: ReadonlyArray<ProjectContentMatch> = [];
42const INITIAL_BRANCH_CURSORS = [undefined] as const;
43const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
44const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
45 matches: EMPTY_THREAD_SEARCH_MATCHES,
46 isLoading: false,
47}).pipe(Atom.withLabel("web:thread-search:empty"));
48
49const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
50 getSearchAtom: (environmentId, query) =>
51 orchestrationEnvironment.threadSearch({
52 environmentId,
53 input: { query },
54 }),
55 labelPrefix: "web:thread-search",
56});
57
58export interface ThreadDetailView {
59 readonly data: OrchestrationThread | null;
60 readonly error: string | null;
61 readonly isPending: boolean;
62 readonly isDeleted: boolean;
63}
64
65/** Shared with the pull requests page, which debounces its search the same way. */
66export function useDebouncedValue<A>(value: A, delayMs: number): A {
67 const [debounced, setDebounced] = useState(value);
68
69 useEffect(() => {
70 const timer = window.setTimeout(() => {
71 setDebounced(value);
72 }, delayMs);
73 return () => {
74 window.clearTimeout(timer);
75 };
76 }, [delayMs, value]);
77
78 return debounced;
79}
80
81export function useThreadSearch(
82 environmentIds: ReadonlyArray<EnvironmentId>,
83 query: string,
84): {
85 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
86 readonly isPending: boolean;
87} {
88 const normalizedQuery = query.trim();
89 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
90 const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
91 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
92 const searchKey = useMemo(
93 () => (settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery)),
94 [environmentIds, settledQuery],
95 );
96 const result = useAtomValue(
97 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
98 );
99 const isDebouncing = canSearch && normalizedQuery !== debouncedQuery;
100 return {
101 matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches,
102 isPending: canSearch && (isDebouncing || result.isLoading),
103 };
104}
105
106export function useThreadDetail(
107 environmentId: EnvironmentId | null,
108 threadId: ThreadId | null,
109): ThreadDetailView {
110 const state = useEnvironmentThread(environmentId, threadId);
111 return {
112 data: Option.getOrNull(state.data),
113 error: Option.getOrNull(state.error),
114 isPending: state.status === "synchronizing",
115 isDeleted: state.status === "deleted",
116 };
117}
118
119export function useBranches(target: VcsRefTarget) {
120 const query = target.query?.trim() ?? "";
121 return useEnvironmentQuery(
122 target.environmentId !== null && target.cwd !== null
123 ? vcsEnvironment.listRefs({
124 environmentId: target.environmentId,
125 input: {
126 cwd: target.cwd,
127 ...(query.length > 0 ? { query } : {}),
128 limit: VCS_REF_LIST_LIMIT,
129 },
130 })
131 : null,
132 );
133}
134
135export function usePaginatedBranches(target: VcsRefTarget) {
136 const query = target.query?.trim() ?? "";
137 const targetKey =
138 target.environmentId !== null && target.cwd !== null
139 ? JSON.stringify([target.environmentId, target.cwd, query])
140 : null;
141 const [pagination, setPagination] = useState<{
142 readonly targetKey: string | null;
143 readonly cursors: ReadonlyArray<number | undefined>;
144 }>({
145 targetKey,
146 cursors: INITIAL_BRANCH_CURSORS,
147 });
148 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
149 const pageAtoms = useMemo(
150 () =>
151 target.environmentId !== null && target.cwd !== null
152 ? cursors.map((cursor) =>
153 vcsEnvironment.listRefs({
154 environmentId: target.environmentId!,
155 input: {
156 cwd: target.cwd!,
157 ...(query.length > 0 ? { query } : {}),
158 ...(cursor === undefined ? {} : { cursor }),
159 limit: VCS_REF_LIST_LIMIT,
160 },
161 }),
162 )
163 : [],
164 [cursors, query, target.cwd, target.environmentId],
165 );
166 const pagesAtom = useMemo(
167 () =>
168 Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
169 Atom.withLabel(`web:vcs-ref-pages:${targetKey ?? "empty"}`),
170 ),
171 [pageAtoms, targetKey],
172 );
173 const results = useAtomValue(pagesAtom);
174 const values = results.flatMap((result) => {
175 const value = Option.getOrNull(AsyncResult.value(result));
176 return value === null ? [] : [value];
177 });
178 const refs = new Map<string, VcsRef>();
179 for (const value of values) {
180 for (const ref of value.refs) {
181 refs.set(ref.name, ref);
182 }
183 }
184 const first = values[0] ?? null;
185 const last = values.at(-1) ?? null;
186 const data: VcsListRefsResult | null =
187 first === null || last === null
188 ? null
189 : {
190 refs: [...refs.values()],
191 isRepo: first.isRepo,
192 hasPrimaryRemote: first.hasPrimaryRemote,
193 nextCursor: last.nextCursor,
194 totalCount: Math.max(...values.map((value) => value.totalCount)),
195 };
196 const failed = results.find((result) => result._tag === "Failure");
197 const isFetchingNextPage = isPaginatedBranchesNextPagePending(results);
198 const error =
199 failed?._tag === "Failure"
200 ? (() => {
201 const cause = Cause.squash(failed.cause);
202 return cause instanceof Error && cause.message.trim().length > 0
203 ? cause.message
204 : "Failed to load refs.";
205 })()
206 : null;
207 const refresh = useCallback(() => {
208 const firstPage = pageAtoms[0];
209 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
210 if (firstPage !== undefined) {
211 appAtomRegistry.refresh(firstPage);
212 }
213 }, [pageAtoms, targetKey]);
214 const loadNext = useCallback(() => {
215 if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {
216 return;
217 }
218 setPagination((current) => {
219 const currentCursors =
220 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
221 return currentCursors.includes(data.nextCursor!)
222 ? { targetKey, cursors: currentCursors }
223 : { targetKey, cursors: [...currentCursors, data.nextCursor!] };
224 });
225 }, [data?.nextCursor, targetKey]);
226
227 return {
228 data,
229 refs: data?.refs ?? EMPTY_REFS,
230 error,
231 isPending: results.some((result) => result.waiting),
232 isFetchingNextPage,
233 refresh,
234 loadNext,
235 };
236}
237
238type ProjectPathSearchTarget = ComposerPathSearchTarget & {
239 readonly kind?: ProjectEntryKind | undefined;
240 readonly imageOnly?: boolean | undefined;
241};
242
243export function areProjectPathSearchTargetsEqual(
244 left: ProjectPathSearchTarget,
245 right: ProjectPathSearchTarget,
246): boolean {
247 return (
248 left.environmentId === right.environmentId &&
249 left.cwd === right.cwd &&
250 left.query === right.query &&
251 left.kind === right.kind &&
252 left.imageOnly === right.imageOnly
253 );
254}
255
256export function useProjectPathSearch(
257 target: ProjectPathSearchTarget,
258 limit: number,
259 options?: { readonly allowEmptyQuery?: boolean },
260) {
261 const allowEmptyQuery = options?.allowEmptyQuery === true;
262 const normalizedTarget = useMemo(
263 () => ({
264 environmentId: target.environmentId,
265 cwd: target.cwd,
266 query: target.query == null ? null : target.query.trim(),
267 kind: target.kind,
268 imageOnly: target.imageOnly,
269 }),
270 [target.cwd, target.environmentId, target.imageOnly, target.kind, target.query],
271 );
272 const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
273 const result = useEnvironmentQuery(
274 debouncedTarget.environmentId !== null &&
275 debouncedTarget.cwd !== null &&
276 debouncedTarget.query !== null &&
277 (allowEmptyQuery || debouncedTarget.query.length > 0)
278 ? projectEnvironment.searchEntries({
279 environmentId: debouncedTarget.environmentId,
280 input: {
281 cwd: debouncedTarget.cwd,
282 query: debouncedTarget.query,
283 limit,
284 ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
285 ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
286 },
287 })
288 : null,
289 );
290
291 return {
292 entries: result.data?.entries ?? [],
293 error: result.error,
294 isPending:
295 !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) || result.isPending,
296 searchedQuery: debouncedTarget.query ?? "",
297 refresh: result.refresh,
298 };
299}
300
301export function useComposerPathSearch(target: ComposerPathSearchTarget) {
302 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
303}
304
305interface ProjectContentSearchTarget {
306 readonly environmentId: EnvironmentId | null;
307 readonly cwd: string | null;
308 readonly query: string;
309 readonly caseSensitive: boolean;
310 readonly wholeWord: boolean;
311 readonly useRegex: boolean;
312}
313
314export function useProjectContentSearch(target: ProjectContentSearchTarget) {
315 // Whitespace is significant in content queries; trimming is only used to
316 // decide whether the input is blank.
317 const query = target.query;
318 const hasQuery = query.trim().length > 0;
319 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
320 const result = useEnvironmentQuery(
321 target.environmentId !== null &&
322 target.cwd !== null &&
323 hasQuery &&
324 debouncedQuery.trim().length > 0
325 ? projectContentSearch({
326 environmentId: target.environmentId,
327 input: {
328 cwd: target.cwd,
329 query: debouncedQuery,
330 limit: PROJECT_CONTENT_SEARCH_LIMIT,
331 caseSensitive: target.caseSensitive,
332 wholeWord: target.wholeWord,
333 useRegex: target.useRegex,
334 },
335 })
336 : null,
337 );
338
339 return {
340 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
341 error: result.error,
342 isPending: hasQuery && (query !== debouncedQuery || result.isPending),
343 hasQuery,
344 truncated: result.data?.truncated ?? false,
345 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
346 };
347}
348
349export function useCheckpointDiff(
350 target: CheckpointDiffTarget,
351 options?: { readonly enabled?: boolean },
352) {
353 const enabled =
354 options?.enabled !== false &&
355 target.environmentId !== null &&
356 target.threadId !== null &&
357 target.fromTurnCount !== null &&
358 target.toTurnCount !== null;
359 const fullThreadTarget =
360 enabled && target.fromTurnCount === 0
361 ? {
362 environmentId: target.environmentId!,
363 input: {
364 threadId: target.threadId!,
365 toTurnCount: target.toTurnCount!,
366 ignoreWhitespace: target.ignoreWhitespace,
367 },
368 }
369 : null;
370 const turnTarget =
371 enabled && target.fromTurnCount !== 0
372 ? {
373 environmentId: target.environmentId!,
374 input: {
375 threadId: target.threadId!,
376 fromTurnCount: target.fromTurnCount!,
377 toTurnCount: target.toTurnCount!,
378 ignoreWhitespace: target.ignoreWhitespace,
379 },
380 }
381 : null;
382 const fullThread = useEnvironmentQuery(
383 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
384 );
385 const turn = useEnvironmentQuery(
386 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
387 );
388 return fullThreadTarget === null ? turn : fullThread;
389}