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 { useFilesystemReadAccess } from "./filesystem";
29import { orchestrationEnvironment } from "./orchestration";
30import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
31import { projectContentSearch, projectEnvironment } from "./projects";
32import { useEnvironmentQuery } from "./query";
33import { vcsEnvironment } from "./vcs";
34
35const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120;
36const COMPOSER_PATH_SEARCH_LIMIT = 80;
37const PROJECT_CONTENT_SEARCH_DEBOUNCE_MS = 120;
38const PROJECT_CONTENT_SEARCH_LIMIT = 500;
39const THREAD_SEARCH_DEBOUNCE_MS = 200;
40const VCS_REF_LIST_LIMIT = 100;
41const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
42const EMPTY_PROJECT_ENTRIES: ReadonlyArray<ProjectEntry> = [];
43const EMPTY_CONTENT_MATCHES: ReadonlyArray<ProjectContentMatch> = [];
44const INITIAL_BRANCH_CURSORS = [undefined] as const;
45const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
46const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
47 matches: EMPTY_THREAD_SEARCH_MATCHES,
48 isLoading: false,
49}).pipe(Atom.withLabel("web:thread-search:empty"));
50
51const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
52 getSearchAtom: (environmentId, query) =>
53 orchestrationEnvironment.threadSearch({
54 environmentId,
55 input: { query },
56 }),
57 labelPrefix: "web:thread-search",
58});
59
60export function useDebouncedValue<A>(value: A, delayMs: number): A {
61 const [debounced, setDebounced] = useState(value);
62
63 useEffect(() => {
64 const timer = window.setTimeout(() => {
65 setDebounced(value);
66 }, delayMs);
67 return () => {
68 window.clearTimeout(timer);
69 };
70 }, [delayMs, value]);
71
72 return debounced;
73}
74
75export function useThreadSearch(
76 environmentIds: ReadonlyArray<EnvironmentId>,
77 query: string,
78): {
79 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
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 fileAccess = useFilesystemReadAccess(debouncedTarget.environmentId);
241 const { canReadFiles } = fileAccess;
242 const searchTarget =
243 debouncedTarget.environmentId !== null &&
244 debouncedTarget.cwd !== null &&
245 debouncedTarget.query !== null &&
246 (allowEmptyQuery || debouncedTarget.query.length > 0)
247 ? {
248 environmentId: debouncedTarget.environmentId,
249 input: {
250 cwd: debouncedTarget.cwd,
251 query: debouncedTarget.query,
252 limit,
253 ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
254 ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
255 },
256 }
257 : null;
258 const result = useEnvironmentQuery(
259 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
260 );
261 const hasTarget = searchTarget !== null;
262
263 return {
264 entries: result.data?.entries ?? EMPTY_PROJECT_ENTRIES,
265 error:
266 !hasTarget || fileAccess.isPending
267 ? null
268 : canReadFiles
269 ? result.error
270 : (fileAccess.error ?? "This connection cannot search host files."),
271 isPending:
272 !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) ||
273 (hasTarget && (fileAccess.isPending || result.isPending)),
274 searchedQuery: debouncedTarget.query ?? "",
275 truncated: result.data?.truncated ?? false,
276 refresh: result.refresh,
277 };
278}
279
280export function useComposerPathSearch(target: ComposerPathSearchTarget) {
281 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
282}
283
284interface ProjectContentSearchTarget {
285 readonly environmentId: EnvironmentId | null;
286 readonly cwd: string | null;
287 readonly query: string;
288 readonly caseSensitive: boolean;
289 readonly wholeWord: boolean;
290 readonly useRegex: boolean;
291}
292
293export function useProjectContentSearch(target: ProjectContentSearchTarget) {
294 const hasTarget = target.environmentId !== null && target.cwd !== null;
295 const fileAccess = useFilesystemReadAccess(target.environmentId);
296 const canReadFiles = hasTarget && fileAccess.canReadFiles;
297 const isCheckingAccess = hasTarget && fileAccess.isPending;
298 // Whitespace is significant in content queries; trimming is only used to
299 // decide whether the input is blank.
300 const query = target.query;
301 const hasQuery = query.trim().length > 0;
302 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
303 const result = useEnvironmentQuery(
304 canReadFiles &&
305 target.environmentId !== null &&
306 target.cwd !== null &&
307 hasQuery &&
308 debouncedQuery.trim().length > 0
309 ? projectContentSearch({
310 environmentId: target.environmentId,
311 input: {
312 cwd: target.cwd,
313 query: debouncedQuery,
314 limit: PROJECT_CONTENT_SEARCH_LIMIT,
315 caseSensitive: target.caseSensitive,
316 wholeWord: target.wholeWord,
317 useRegex: target.useRegex,
318 },
319 })
320 : null,
321 );
322
323 return {
324 canReadFiles,
325 isCheckingAccess,
326 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
327 error:
328 !hasTarget || isCheckingAccess
329 ? null
330 : canReadFiles
331 ? result.error
332 : (fileAccess.error ?? "This connection cannot search host files."),
333 isPending:
334 isCheckingAccess ||
335 (canReadFiles && hasQuery && (query !== debouncedQuery || result.isPending)),
336 hasQuery,
337 truncated: result.data?.truncated ?? false,
338 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
339 };
340}
341
342export function useCheckpointDiff(
343 target: CheckpointDiffTarget,
344 options?: { readonly enabled?: boolean },
345) {
346 const enabled =
347 options?.enabled !== false &&
348 target.environmentId !== null &&
349 target.threadId !== null &&
350 target.fromTurnCount !== null &&
351 target.toTurnCount !== null;
352 const fullThreadTarget =
353 enabled && target.fromTurnCount === 0
354 ? {
355 environmentId: target.environmentId!,
356 input: {
357 threadId: target.threadId!,
358 toTurnCount: target.toTurnCount!,
359 ignoreWhitespace: target.ignoreWhitespace,
360 },
361 }
362 : null;
363 const turnTarget =
364 enabled && target.fromTurnCount !== 0
365 ? {
366 environmentId: target.environmentId!,
367 input: {
368 threadId: target.threadId!,
369 fromTurnCount: target.fromTurnCount!,
370 toTurnCount: target.toTurnCount!,
371 ignoreWhitespace: target.ignoreWhitespace,
372 },
373 }
374 : null;
375 const fullThread = useEnvironmentQuery(
376 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
377 );
378 const turn = useEnvironmentQuery(
379 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
380 );
381 return fullThreadTarget === null ? turn : fullThread;
382}
383
384export function useTurnItemDetail(
385 target: {
386 readonly environmentId: EnvironmentId;
387 readonly threadId: ThreadId;
388 readonly itemId: TurnItemId;
389 readonly revision: string;
390 } | null,
391) {
392 return useEnvironmentQuery(
393 target === null
394 ? null
395 : orchestrationEnvironment.turnItem({
396 environmentId: target.environmentId,
397 input: { threadId: target.threadId, itemId: target.itemId, revision: target.revision },
398 }),
399 );
400}