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 searchedTarget: debouncedTarget,
276 searchedQuery: debouncedTarget.query ?? "",
277 truncated: result.data?.truncated ?? false,
278 refresh: result.refresh,
279 };
280}
281
282export function useComposerPathSearch(target: ComposerPathSearchTarget) {
283 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
284}
285
286interface ProjectContentSearchTarget {
287 readonly environmentId: EnvironmentId | null;
288 readonly cwd: string | null;
289 readonly query: string;
290 readonly caseSensitive: boolean;
291 readonly wholeWord: boolean;
292 readonly useRegex: boolean;
293}
294
295export function useProjectContentSearch(target: ProjectContentSearchTarget) {
296 const hasTarget = target.environmentId !== null && target.cwd !== null;
297 const fileAccess = useFilesystemReadAccess(target.environmentId);
298 const canReadFiles = hasTarget && fileAccess.canReadFiles;
299 const isCheckingAccess = hasTarget && fileAccess.isPending;
300 // Whitespace is significant in content queries; trimming is only used to
301 // decide whether the input is blank.
302 const query = target.query;
303 const hasQuery = query.trim().length > 0;
304 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
305 const result = useEnvironmentQuery(
306 canReadFiles &&
307 target.environmentId !== null &&
308 target.cwd !== null &&
309 hasQuery &&
310 debouncedQuery.trim().length > 0
311 ? projectContentSearch({
312 environmentId: target.environmentId,
313 input: {
314 cwd: target.cwd,
315 query: debouncedQuery,
316 limit: PROJECT_CONTENT_SEARCH_LIMIT,
317 caseSensitive: target.caseSensitive,
318 wholeWord: target.wholeWord,
319 useRegex: target.useRegex,
320 },
321 })
322 : null,
323 );
324
325 return {
326 canReadFiles,
327 isCheckingAccess,
328 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
329 error:
330 !hasTarget || isCheckingAccess
331 ? null
332 : canReadFiles
333 ? result.error
334 : (fileAccess.error ?? "This connection cannot search host files."),
335 isPending:
336 isCheckingAccess ||
337 (canReadFiles && hasQuery && (query !== debouncedQuery || result.isPending)),
338 hasQuery,
339 truncated: result.data?.truncated ?? false,
340 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
341 };
342}
343
344export function useCheckpointDiff(
345 target: CheckpointDiffTarget,
346 options?: { readonly enabled?: boolean },
347) {
348 const enabled =
349 options?.enabled !== false &&
350 target.environmentId !== null &&
351 target.threadId !== null &&
352 target.fromTurnCount !== null &&
353 target.toTurnCount !== null;
354 const fullThreadTarget =
355 enabled && target.fromTurnCount === 0
356 ? {
357 environmentId: target.environmentId!,
358 input: {
359 threadId: target.threadId!,
360 toTurnCount: target.toTurnCount!,
361 ignoreWhitespace: target.ignoreWhitespace,
362 },
363 }
364 : null;
365 const turnTarget =
366 enabled && target.fromTurnCount !== 0
367 ? {
368 environmentId: target.environmentId!,
369 input: {
370 threadId: target.threadId!,
371 fromTurnCount: target.fromTurnCount!,
372 toTurnCount: target.toTurnCount!,
373 ignoreWhitespace: target.ignoreWhitespace,
374 },
375 }
376 : null;
377 const fullThread = useEnvironmentQuery(
378 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
379 );
380 const turn = useEnvironmentQuery(
381 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
382 );
383 return fullThreadTarget === null ? turn : fullThread;
384}
385
386export function useTurnItemDetail(
387 target: {
388 readonly environmentId: EnvironmentId;
389 readonly threadId: ThreadId;
390 readonly itemId: TurnItemId;
391 readonly revision: string;
392 } | null,
393) {
394 return useEnvironmentQuery(
395 target === null
396 ? null
397 : orchestrationEnvironment.turnItem({
398 environmentId: target.environmentId,
399 input: { threadId: target.threadId, itemId: target.itemId, revision: target.revision },
400 }),
401 );
402}