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