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 { useEffect, 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 =
88 settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery);
89 const result = useAtomValue(
90 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
91 );
92 const isDebouncing = canSearch && normalizedQuery !== debouncedQuery;
93 return {
94 matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches,
95 query: settledQuery ?? "",
96 isPending: canSearch && (isDebouncing || result.isLoading),
97 };
98}
99
100function vcsRefPageAtom(targetKey: string, cursor: number | undefined) {
101 const [environmentId, cwd, query] = JSON.parse(targetKey) as [EnvironmentId, string, string];
102 return vcsEnvironment.listRefs({
103 environmentId,
104 input: {
105 cwd,
106 ...(query.length > 0 ? { query } : {}),
107 ...(cursor === undefined ? {} : { cursor }),
108 limit: VCS_REF_LIST_LIMIT,
109 },
110 });
111}
112
113const EMPTY_VCS_REF_PAGES_ATOM = Atom.make<
114 ReadonlyArray<Atom.Type<ReturnType<typeof vcsRefPageAtom>>>
115>([]).pipe(Atom.withLabel("web:vcs-ref-pages:empty"));
116
117// Keyed by target and cursors so every render of the same pages reads the same atom.
118const vcsRefPagesAtom = Atom.family((pagesKey: string) => {
119 const [targetKey, cursors] = JSON.parse(pagesKey) as [string, Array<number | null>];
120 const pageAtoms = cursors.map((cursor) => vcsRefPageAtom(targetKey, cursor ?? undefined));
121 return Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
122 Atom.withLabel(`web:vcs-ref-pages:${pagesKey}`),
123 );
124});
125
126export function usePaginatedBranches(target: VcsRefTarget) {
127 // Starts unkeyed: a key mismatch already resolves to the initial cursors, and seeding
128 // the key here would make every derivation below straddle this hook call.
129 const [pagination, setPagination] = useState<{
130 readonly targetKey: string | null;
131 readonly cursors: ReadonlyArray<number | undefined>;
132 }>({
133 targetKey: null,
134 cursors: INITIAL_BRANCH_CURSORS,
135 });
136 const { environmentId, cwd } = target;
137 const query = target.query?.trim() ?? "";
138 const targetKey =
139 environmentId !== null && cwd !== null ? JSON.stringify([environmentId, cwd, query]) : null;
140 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
141 const pagesKey = targetKey === null ? null : JSON.stringify([targetKey, cursors]);
142 const results = useAtomValue(
143 pagesKey === null ? EMPTY_VCS_REF_PAGES_ATOM : vcsRefPagesAtom(pagesKey),
144 );
145 const values = results.flatMap((result) => {
146 const value = Option.getOrNull(AsyncResult.value(result));
147 return value === null ? [] : [value];
148 });
149 const refs = new Map<string, VcsRef>();
150 for (const value of values) {
151 for (const ref of value.refs) {
152 refs.set(ref.name, ref);
153 }
154 }
155 const first = values[0] ?? null;
156 const last = values.at(-1) ?? null;
157 const data: VcsListRefsResult | null =
158 first === null || last === null
159 ? null
160 : {
161 refs: [...refs.values()],
162 isRepo: first.isRepo,
163 hasPrimaryRemote: first.hasPrimaryRemote,
164 nextCursor: last.nextCursor,
165 totalCount: Math.max(...values.map((value) => value.totalCount)),
166 };
167 const failed = results.find((result) => result._tag === "Failure");
168 const isFetchingNextPage = isPaginatedBranchesNextPagePending(results);
169 const error =
170 failed?._tag === "Failure"
171 ? (() => {
172 const cause = Cause.squash(failed.cause);
173 return cause instanceof Error && cause.message.trim().length > 0
174 ? cause.message
175 : "Failed to load refs.";
176 })()
177 : null;
178 const refresh = () => {
179 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
180 if (targetKey !== null) {
181 appAtomRegistry.refresh(vcsRefPageAtom(targetKey, undefined));
182 }
183 };
184 const nextCursor = data?.nextCursor;
185 const loadNext = () => {
186 if (targetKey === null || nextCursor === null || nextCursor === undefined) {
187 return;
188 }
189 setPagination((current) => {
190 const currentCursors =
191 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
192 return currentCursors.includes(nextCursor)
193 ? { targetKey, cursors: currentCursors }
194 : { targetKey, cursors: [...currentCursors, nextCursor] };
195 });
196 };
197
198 return {
199 data,
200 refs: data?.refs ?? EMPTY_REFS,
201 error,
202 isPending: results.some((result) => result.waiting),
203 isFetchingNextPage,
204 refresh,
205 loadNext,
206 };
207}
208
209type ProjectPathSearchTarget = ComposerPathSearchTarget & {
210 readonly kind?: ProjectEntryKind | undefined;
211 readonly imageOnly?: boolean | undefined;
212};
213
214export function areProjectPathSearchTargetsEqual(
215 left: ProjectPathSearchTarget,
216 right: ProjectPathSearchTarget,
217): boolean {
218 return (
219 left.environmentId === right.environmentId &&
220 left.cwd === right.cwd &&
221 left.query === right.query &&
222 left.kind === right.kind &&
223 left.imageOnly === right.imageOnly
224 );
225}
226
227export function useProjectPathSearch(
228 target: ProjectPathSearchTarget,
229 limit: number,
230 options?: { readonly allowEmptyQuery?: boolean },
231) {
232 const allowEmptyQuery = options?.allowEmptyQuery === true;
233 const normalizedTarget = {
234 environmentId: target.environmentId,
235 cwd: target.cwd,
236 query: target.query == null ? null : target.query.trim(),
237 kind: target.kind,
238 imageOnly: target.imageOnly,
239 };
240 const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
241 const fileAccess = useFilesystemReadAccess(debouncedTarget.environmentId);
242 const { canReadFiles } = fileAccess;
243 const searchTarget =
244 debouncedTarget.environmentId !== null &&
245 debouncedTarget.cwd !== null &&
246 debouncedTarget.query !== null &&
247 (allowEmptyQuery || debouncedTarget.query.length > 0)
248 ? {
249 environmentId: debouncedTarget.environmentId,
250 input: {
251 cwd: debouncedTarget.cwd,
252 query: debouncedTarget.query,
253 limit,
254 ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
255 ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
256 },
257 }
258 : null;
259 const result = useEnvironmentQuery(
260 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
261 );
262 const hasTarget = searchTarget !== null;
263
264 return {
265 entries: result.data?.entries ?? EMPTY_PROJECT_ENTRIES,
266 error:
267 !hasTarget || fileAccess.isPending
268 ? null
269 : canReadFiles
270 ? result.error
271 : (fileAccess.error ?? "This connection cannot search host files."),
272 isPending:
273 !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) ||
274 (hasTarget && (fileAccess.isPending || result.isPending)),
275 searchedQuery: debouncedTarget.query ?? "",
276 truncated: result.data?.truncated ?? false,
277 refresh: result.refresh,
278 };
279}
280
281export function useComposerPathSearch(target: ComposerPathSearchTarget) {
282 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
283}
284
285interface ProjectContentSearchTarget {
286 readonly environmentId: EnvironmentId | null;
287 readonly cwd: string | null;
288 readonly query: string;
289 readonly caseSensitive: boolean;
290 readonly wholeWord: boolean;
291 readonly useRegex: boolean;
292}
293
294export function useProjectContentSearch(target: ProjectContentSearchTarget) {
295 const hasTarget = target.environmentId !== null && target.cwd !== null;
296 const fileAccess = useFilesystemReadAccess(target.environmentId);
297 const canReadFiles = hasTarget && fileAccess.canReadFiles;
298 const isCheckingAccess = hasTarget && fileAccess.isPending;
299 // Whitespace is significant in content queries; trimming is only used to
300 // decide whether the input is blank.
301 const query = target.query;
302 const hasQuery = query.trim().length > 0;
303 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
304 const result = useEnvironmentQuery(
305 canReadFiles &&
306 target.environmentId !== null &&
307 target.cwd !== null &&
308 hasQuery &&
309 debouncedQuery.trim().length > 0
310 ? projectContentSearch({
311 environmentId: target.environmentId,
312 input: {
313 cwd: target.cwd,
314 query: debouncedQuery,
315 limit: PROJECT_CONTENT_SEARCH_LIMIT,
316 caseSensitive: target.caseSensitive,
317 wholeWord: target.wholeWord,
318 useRegex: target.useRegex,
319 },
320 })
321 : null,
322 );
323
324 return {
325 canReadFiles,
326 isCheckingAccess,
327 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
328 error:
329 !hasTarget || isCheckingAccess
330 ? null
331 : canReadFiles
332 ? result.error
333 : (fileAccess.error ?? "This connection cannot search host files."),
334 isPending:
335 isCheckingAccess ||
336 (canReadFiles && hasQuery && (query !== debouncedQuery || result.isPending)),
337 hasQuery,
338 truncated: result.data?.truncated ?? false,
339 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
340 };
341}
342
343export function useCheckpointDiff(
344 target: CheckpointDiffTarget,
345 options?: { readonly enabled?: boolean },
346) {
347 const enabled =
348 options?.enabled !== false &&
349 target.environmentId !== null &&
350 target.threadId !== null &&
351 target.fromTurnCount !== null &&
352 target.toTurnCount !== null;
353 const fullThreadTarget =
354 enabled && target.fromTurnCount === 0
355 ? {
356 environmentId: target.environmentId!,
357 input: {
358 threadId: target.threadId!,
359 toTurnCount: target.toTurnCount!,
360 ignoreWhitespace: target.ignoreWhitespace,
361 },
362 }
363 : null;
364 const turnTarget =
365 enabled && target.fromTurnCount !== 0
366 ? {
367 environmentId: target.environmentId!,
368 input: {
369 threadId: target.threadId!,
370 fromTurnCount: target.fromTurnCount!,
371 toTurnCount: target.toTurnCount!,
372 ignoreWhitespace: target.ignoreWhitespace,
373 },
374 }
375 : null;
376 const fullThread = useEnvironmentQuery(
377 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
378 );
379 const turn = useEnvironmentQuery(
380 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
381 );
382 return fullThreadTarget === null ? turn : fullThread;
383}
384
385export function useTurnItemDetail(
386 target: {
387 readonly environmentId: EnvironmentId;
388 readonly threadId: ThreadId;
389 readonly itemId: TurnItemId;
390 readonly revision: string;
391 } | null,
392) {
393 return useEnvironmentQuery(
394 target === null
395 ? null
396 : orchestrationEnvironment.turnItem({
397 environmentId: target.environmentId,
398 input: { threadId: target.threadId, itemId: target.itemId, revision: target.revision },
399 }),
400 );
401}