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 visibleThreadSearch,
10 type EnvironmentThreadSearchMatch,
11 type SettledThreadSearch,
12} from "@t3tools/client-runtime/state/thread-search";
13import { THREAD_SEARCH_QUERY_MAX_LENGTH } from "@t3tools/contracts";
14import { messageSearchTokens } from "@t3tools/shared/paletteSearch";
15import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
16import type {
17 EnvironmentId,
18 OrchestrationV2GetTurnItemResult,
19 ProjectContentMatch,
20 ProjectEntry,
21 ProjectEntryKind,
22 ThreadId,
23 TurnItemId,
24 VcsListRefsResult,
25 VcsRef,
26} from "@t3tools/contracts";
27import * as Cause from "effect/Cause";
28import * as Option from "effect/Option";
29import { AsyncResult, Atom } from "effect/reactivity";
30import { useEffect, useState } from "react";
31
32import { appAtomRegistry } from "../rpc/atomRegistry";
33import { useFilesystemReadAccess } from "./filesystem";
34import { orchestrationEnvironment } from "./orchestration";
35import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
36import { projectContentSearch, projectEnvironment } from "./projects";
37import { useEnvironmentQuery } from "./query";
38import { vcsEnvironment } from "./vcs";
39
40const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120;
41const COMPOSER_PATH_SEARCH_LIMIT = 80;
42const PROJECT_CONTENT_SEARCH_DEBOUNCE_MS = 120;
43const PROJECT_CONTENT_SEARCH_LIMIT = 500;
44const THREAD_SEARCH_DEBOUNCE_MS = 120;
45const VCS_REF_LIST_LIMIT = 100;
46const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
47const EMPTY_PROJECT_ENTRIES: ReadonlyArray<ProjectEntry> = [];
48const EMPTY_CONTENT_MATCHES: ReadonlyArray<ProjectContentMatch> = [];
49const INITIAL_BRANCH_CURSORS = [undefined] as const;
50const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
51const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
52 matches: EMPTY_THREAD_SEARCH_MATCHES,
53 isLoading: false,
54}).pipe(Atom.withLabel("web:thread-search:empty"));
55
56const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
57 getSearchAtom: (environmentId, query) =>
58 orchestrationEnvironment.threadSearch({
59 environmentId,
60 input: { query },
61 }),
62 labelPrefix: "web:thread-search",
63});
64
65export function useDebouncedValue<A>(value: A, delayMs: number): A {
66 const [debounced, setDebounced] = useState(value);
67
68 useEffect(() => {
69 const timer = window.setTimeout(() => {
70 setDebounced(value);
71 }, delayMs);
72 return () => {
73 window.clearTimeout(timer);
74 };
75 }, [delayMs, value]);
76
77 return debounced;
78}
79
80export function useThreadSearch(
81 environmentIds: ReadonlyArray<EnvironmentId>,
82 query: string,
83): {
84 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
85 readonly query: string;
86 readonly isPending: boolean;
87} {
88 // A pasted wall of text searches by its start rather than failing the request.
89 const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim();
90 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
91 // The server needs a word of three or more letters; shorter queries would always come back empty.
92 const canSearch =
93 environmentIds.length > 0 && messageSearchTokens(normalizedQuery).long.length > 0;
94 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
95 const searchKey =
96 settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery);
97 const result = useAtomValue(
98 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
99 );
100 const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading);
101 // What fast environments returned shows without waiting for a slow one;
102 // callers keep shown rows in place with `nextShownOrder`.
103 const ready =
104 settledQuery !== null && (!result.isLoading || result.matches.length > 0)
105 ? { query: settledQuery, matches: result.matches }
106 : null;
107 // Kept from earlier renders: React's pattern for information from previous renders.
108 const [previous, setPrevious] = useState<SettledThreadSearch | null>(null);
109 if (ready !== null && previous?.matches !== ready.matches) setPrevious(ready);
110 const visible = canSearch
111 ? visibleThreadSearch(normalizedQuery, ready, previous)
112 : { query: "", matches: EMPTY_THREAD_SEARCH_MATCHES };
113 return {
114 matches: visible.matches,
115 query: visible.query,
116 isPending,
117 };
118}
119
120function vcsRefPageAtom(targetKey: string, cursor: number | undefined) {
121 const [environmentId, cwd, query] = JSON.parse(targetKey) as [EnvironmentId, string, string];
122 return vcsEnvironment.listRefs({
123 environmentId,
124 input: {
125 cwd,
126 ...(query.length > 0 ? { query } : {}),
127 ...(cursor === undefined ? {} : { cursor }),
128 limit: VCS_REF_LIST_LIMIT,
129 },
130 });
131}
132
133const EMPTY_VCS_REF_PAGES_ATOM = Atom.make<
134 ReadonlyArray<Atom.Type<ReturnType<typeof vcsRefPageAtom>>>
135>([]).pipe(Atom.withLabel("web:vcs-ref-pages:empty"));
136
137const vcsRefPagesAtom = Atom.family((pagesKey: string) => {
138 const [targetKey, cursors] = JSON.parse(pagesKey) as [string, Array<number | null>];
139 const pageAtoms = cursors.map((cursor) => vcsRefPageAtom(targetKey, cursor ?? undefined));
140 return Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
141 Atom.withLabel(`web:vcs-ref-pages:${pagesKey}`),
142 );
143});
144
145export function usePaginatedBranches(target: VcsRefTarget) {
146 // Leave unkeyed; mismatches already reset cursors, and a seeded key would break caching across the hook.
147 const [pagination, setPagination] = useState<{
148 readonly targetKey: string | null;
149 readonly cursors: ReadonlyArray<number | undefined>;
150 }>({
151 targetKey: null,
152 cursors: INITIAL_BRANCH_CURSORS,
153 });
154 const { environmentId, cwd } = target;
155 const query = target.query?.trim() ?? "";
156 const targetKey =
157 environmentId !== null && cwd !== null ? JSON.stringify([environmentId, cwd, query]) : null;
158 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
159 const pagesKey = targetKey === null ? null : JSON.stringify([targetKey, cursors]);
160 const results = useAtomValue(
161 pagesKey === null ? EMPTY_VCS_REF_PAGES_ATOM : vcsRefPagesAtom(pagesKey),
162 );
163 const values = results.flatMap((result) => {
164 const value = Option.getOrNull(AsyncResult.value(result));
165 return value === null ? [] : [value];
166 });
167 const refs = new Map<string, VcsRef>();
168 for (const value of values) {
169 for (const ref of value.refs) {
170 refs.set(ref.name, ref);
171 }
172 }
173 const first = values[0] ?? null;
174 const last = values.at(-1) ?? null;
175 const data: VcsListRefsResult | null =
176 first === null || last === null
177 ? null
178 : {
179 refs: [...refs.values()],
180 isRepo: first.isRepo,
181 hasPrimaryRemote: first.hasPrimaryRemote,
182 nextCursor: last.nextCursor,
183 totalCount: Math.max(...values.map((value) => value.totalCount)),
184 };
185 const failed = results.find((result) => result._tag === "Failure");
186 const isFetchingNextPage = isPaginatedBranchesNextPagePending(results);
187 const error =
188 failed?._tag === "Failure"
189 ? (() => {
190 const cause = Cause.squash(failed.cause);
191 return cause instanceof Error && cause.message.trim().length > 0
192 ? cause.message
193 : "Failed to load refs.";
194 })()
195 : null;
196 const refresh = () => {
197 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
198 if (targetKey !== null) {
199 appAtomRegistry.refresh(vcsRefPageAtom(targetKey, undefined));
200 }
201 };
202 const nextCursor = data?.nextCursor;
203 const loadNext = () => {
204 if (targetKey === null || nextCursor === null || nextCursor === undefined) {
205 return;
206 }
207 setPagination((current) => {
208 const currentCursors =
209 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
210 return currentCursors.includes(nextCursor)
211 ? { targetKey, cursors: currentCursors }
212 : { targetKey, cursors: [...currentCursors, nextCursor] };
213 });
214 };
215
216 return {
217 data,
218 refs: data?.refs ?? EMPTY_REFS,
219 error,
220 isPending: results.some((result) => result.waiting),
221 isFetchingNextPage,
222 refresh,
223 loadNext,
224 };
225}
226
227type ProjectPathSearchTarget = ComposerPathSearchTarget & {
228 readonly kind?: ProjectEntryKind | undefined;
229 readonly imageOnly?: boolean | undefined;
230};
231
232function areProjectPathSearchTargetsEqual(
233 left: ProjectPathSearchTarget,
234 right: ProjectPathSearchTarget,
235): boolean {
236 return (
237 left.environmentId === right.environmentId &&
238 left.cwd === right.cwd &&
239 left.query === right.query &&
240 left.kind === right.kind &&
241 left.imageOnly === right.imageOnly
242 );
243}
244
245export function useProjectPathSearch(
246 target: ProjectPathSearchTarget,
247 limit: number,
248 options?: { readonly allowEmptyQuery?: boolean },
249) {
250 const allowEmptyQuery = options?.allowEmptyQuery === true;
251 const normalizedTarget = {
252 environmentId: target.environmentId,
253 cwd: target.cwd,
254 query: target.query == null ? null : target.query.trim(),
255 kind: target.kind,
256 imageOnly: target.imageOnly,
257 };
258 const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
259 const fileAccess = useFilesystemReadAccess(debouncedTarget.environmentId);
260 const { canReadFiles } = fileAccess;
261 const searchTarget =
262 debouncedTarget.environmentId !== null &&
263 debouncedTarget.cwd !== null &&
264 debouncedTarget.query !== null &&
265 (allowEmptyQuery || debouncedTarget.query.length > 0)
266 ? {
267 environmentId: debouncedTarget.environmentId,
268 input: {
269 cwd: debouncedTarget.cwd,
270 query: debouncedTarget.query,
271 limit,
272 ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
273 ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
274 },
275 }
276 : null;
277 const result = useEnvironmentQuery(
278 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
279 );
280 const hasTarget = searchTarget !== null;
281
282 return {
283 entries: result.data?.entries ?? EMPTY_PROJECT_ENTRIES,
284 error:
285 !hasTarget || fileAccess.isPending
286 ? null
287 : canReadFiles
288 ? result.error
289 : (fileAccess.error ?? "This connection cannot search host files."),
290 isPending:
291 !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) ||
292 (hasTarget && (fileAccess.isPending || result.isPending)),
293 searchedTarget: debouncedTarget,
294 searchedQuery: debouncedTarget.query ?? "",
295 truncated: result.data?.truncated ?? false,
296 refresh: result.refresh,
297 };
298}
299
300export function useComposerPathSearch(target: ComposerPathSearchTarget) {
301 return useProjectPathSearch(target, COMPOSER_PATH_SEARCH_LIMIT);
302}
303
304interface ProjectContentSearchTarget {
305 readonly environmentId: EnvironmentId | null;
306 readonly cwd: string | null;
307 readonly query: string;
308 readonly caseSensitive: boolean;
309 readonly wholeWord: boolean;
310 readonly useRegex: boolean;
311}
312
313export function useProjectContentSearch(target: ProjectContentSearchTarget) {
314 const hasTarget = target.environmentId !== null && target.cwd !== null;
315 const fileAccess = useFilesystemReadAccess(target.environmentId);
316 const canReadFiles = hasTarget && fileAccess.canReadFiles;
317 const isCheckingAccess = hasTarget && fileAccess.isPending;
318 // Preserve query whitespace; trim only to detect blank input.
319 const query = target.query;
320 const hasQuery = query.trim().length > 0;
321 const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
322 const result = useEnvironmentQuery(
323 canReadFiles &&
324 target.environmentId !== null &&
325 target.cwd !== null &&
326 hasQuery &&
327 debouncedQuery.trim().length > 0
328 ? projectContentSearch({
329 environmentId: target.environmentId,
330 input: {
331 cwd: target.cwd,
332 query: debouncedQuery,
333 limit: PROJECT_CONTENT_SEARCH_LIMIT,
334 caseSensitive: target.caseSensitive,
335 wholeWord: target.wholeWord,
336 useRegex: target.useRegex,
337 },
338 })
339 : null,
340 );
341
342 return {
343 canReadFiles,
344 isCheckingAccess,
345 matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
346 error:
347 !hasTarget || isCheckingAccess
348 ? null
349 : canReadFiles
350 ? result.error
351 : (fileAccess.error ?? "This connection cannot search host files."),
352 isPending:
353 isCheckingAccess ||
354 (canReadFiles && hasQuery && (query !== debouncedQuery || result.isPending)),
355 hasQuery,
356 truncated: result.data?.truncated ?? false,
357 invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
358 };
359}
360
361export function useCheckpointDiff(
362 target: CheckpointDiffTarget,
363 options?: { readonly enabled?: boolean },
364) {
365 const enabled =
366 options?.enabled !== false &&
367 target.environmentId !== null &&
368 target.threadId !== null &&
369 target.fromTurnCount !== null &&
370 target.toTurnCount !== null;
371 const fullThreadTarget =
372 enabled && target.fromTurnCount === 0
373 ? {
374 environmentId: target.environmentId!,
375 input: {
376 threadId: target.threadId!,
377 toTurnCount: target.toTurnCount!,
378 ignoreWhitespace: target.ignoreWhitespace,
379 },
380 }
381 : null;
382 const turnTarget =
383 enabled && target.fromTurnCount !== 0
384 ? {
385 environmentId: target.environmentId!,
386 input: {
387 threadId: target.threadId!,
388 fromTurnCount: target.fromTurnCount!,
389 toTurnCount: target.toTurnCount!,
390 ignoreWhitespace: target.ignoreWhitespace,
391 },
392 }
393 : null;
394 const fullThread = useEnvironmentQuery(
395 fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget),
396 );
397 const turn = useEnvironmentQuery(
398 turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget),
399 );
400 return fullThreadTarget === null ? turn : fullThread;
401}
402
403/** Reads one item's detail from somewhere other than the environment, as the guest page does. */
404export type TurnItemDetailSource = (input: {
405 readonly threadId: ThreadId;
406 readonly itemId: TurnItemId;
407 readonly revision: string;
408}) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2GetTurnItemResult, unknown>>;
409
410export function useTurnItemDetail(
411 target: {
412 readonly environmentId: EnvironmentId;
413 readonly threadId: ThreadId;
414 readonly itemId: TurnItemId;
415 readonly revision: string;
416 } | null,
417 source?: TurnItemDetailSource,
418) {
419 const input =
420 target === null
421 ? null
422 : { threadId: target.threadId, itemId: target.itemId, revision: target.revision };
423 return useEnvironmentQuery<OrchestrationV2GetTurnItemResult, unknown>(
424 target === null || input === null
425 ? null
426 : source
427 ? source(input)
428 : orchestrationEnvironment.turnItem({ environmentId: target.environmentId, input }),
429 );
430}