Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

queries.ts

299 lines9.5 KB

1import type { VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
2import type {
3 EnvironmentId,
4 OrchestrationThread,
5 ThreadId,
6 VcsListRefsResult,
7 VcsRef,
8} from "@t3tools/contracts";
9import {
10 createThreadSearchResultsAtomFamily,
11 makeThreadSearchKey,
12 type EnvironmentThreadSearchMatch,
13} from "@t3tools/client-runtime/state/thread-search";
14import { useAtomValue } from "@effect/atom-react";
15import * as Cause from "effect/Cause";
16import * as Option from "effect/Option";
17import { AsyncResult, Atom } from "effect/unstable/reactivity";
18import { useCallback, useEffect, useMemo, useState } from "react";
19​
20import { appAtomRegistry } from "./atom-registry";
21import { orchestrationEnvironment } from "./orchestration";
22import { projectEnvironment } from "./projects";
23import { useEnvironmentQuery } from "./query";
24import { useEnvironmentThread } from "./threads";
25import { vcsEnvironment } from "./vcs";
26import {
27 buildCheckpointDiffTargets,
28 normalizeComposerPathSearchQuery,
29 type CheckpointDiffTarget,
30} from "./queryTargets";
31​
32const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
33const COMPOSER_PATH_SEARCH_LIMIT = 20;
34const THREAD_SEARCH_DEBOUNCE_MS = 200;
35const VCS_REF_LIST_LIMIT = 100;
36const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
37const INITIAL_BRANCH_CURSORS = [undefined] as const;
38const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
39const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
40 matches: EMPTY_THREAD_SEARCH_MATCHES,
41 isLoading: false,
42}).pipe(Atom.withLabel("mobile:thread-search:empty"));
43​
44const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
45 getSearchAtom: (environmentId, query) =>
46 orchestrationEnvironment.threadSearch({
47 environmentId,
48 input: { query },
49 }),
50 labelPrefix: "mobile:thread-search",
51});
52​
53export interface ThreadDetailView {
54 readonly data: OrchestrationThread | null;
55 readonly error: string | null;
56 readonly isPending: boolean;
57 readonly isDeleted: boolean;
59​
60export interface ComposerPathSearchTarget {
61 readonly environmentId: EnvironmentId | null;
62 readonly cwd: string | null;
63 readonly query: string | null;
65​
66export function useDebouncedValue<A>(value: A, delayMs: number): A {
67 const [debounced, setDebounced] = useState(value);
68​
69 useEffect(() => {
70 const timer = setTimeout(() => {
71 setDebounced(value);
72 }, delayMs);
73 return () => {
74 clearTimeout(timer);
75 };
76 }, [delayMs, value]);
77​
78 return debounced;
80​
81export function useThreadSearch(
82 environmentIds: ReadonlyArray<EnvironmentId>,
83 query: string,
84): {
85 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
86 readonly isPending: boolean;
87} {
88 const normalizedQuery = query.trim();
89 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
90 const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
91 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
92 const searchKey = useMemo(
93 () => (settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery)),
94 [environmentIds, settledQuery],
95 );
96 const result = useAtomValue(
97 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
98 );
99 const isDebouncing = canSearch && normalizedQuery !== debouncedQuery;
100 return {
101 matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches,
102 isPending: canSearch && (isDebouncing || result.isLoading),
103 };
105​
106export function useThreadDetail(
107 environmentId: EnvironmentId | null,
108 threadId: ThreadId | null,
109): ThreadDetailView {
110 const state = useEnvironmentThread(environmentId, threadId);
111 return {
112 data: Option.getOrNull(state.data),
113 error: Option.getOrNull(state.error),
114 isPending: state.status === "synchronizing",
115 isDeleted: state.status === "deleted",
116 };
118​
119export function useBranches(input: {
120 readonly environmentId: EnvironmentId | null;
121 readonly cwd: string | null;
122 readonly query?: string | null;
123}) {
124 const query = input.query?.trim() ?? "";
125 return useEnvironmentQuery(
126 input.environmentId !== null && input.cwd !== null
127 ? vcsEnvironment.listRefs({
128 environmentId: input.environmentId,
129 input: {
130 cwd: input.cwd,
131 ...(query.length > 0 ? { query } : {}),
132 limit: VCS_REF_LIST_LIMIT,
133 },
134 })
135 : null,
136 );
138​
139export function usePaginatedBranches(target: VcsRefTarget) {
140 const query = target.query?.trim() ?? "";
141 const targetKey =
142 target.environmentId !== null && target.cwd !== null
143 ? JSON.stringify([target.environmentId, target.cwd, query])
144 : null;
145 const [pagination, setPagination] = useState<{
146 readonly targetKey: string | null;
147 readonly cursors: ReadonlyArray<number | undefined>;
148 }>({
149 targetKey,
150 cursors: INITIAL_BRANCH_CURSORS,
151 });
152 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
153 const pageAtoms = useMemo(
154 () =>
155 target.environmentId !== null && target.cwd !== null
156 ? cursors.map((cursor) =>
157 vcsEnvironment.listRefs({
158 environmentId: target.environmentId!,
159 input: {
160 cwd: target.cwd!,
161 ...(query.length > 0 ? { query } : {}),
162 ...(cursor === undefined ? {} : { cursor }),
163 limit: VCS_REF_LIST_LIMIT,
164 },
165 }),
166 )
167 : [],
168 [cursors, query, target.cwd, target.environmentId],
169 );
170 const pagesAtom = useMemo(
171 () =>
172 Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
173 Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
174 ),
175 [pageAtoms, targetKey],
176 );
177 const results = useAtomValue(pagesAtom);
178 const values = results.flatMap((result) => {
179 const value = Option.getOrNull(AsyncResult.value(result));
180 return value === null ? [] : [value];
181 });
182 const refs = new Map<string, VcsRef>();
183 for (const value of values) {
184 for (const ref of value.refs) {
185 refs.set(ref.name, ref);
186 }
187 }
188 const first = values[0] ?? null;
189 const last = values.at(-1) ?? null;
190 const data: VcsListRefsResult | null =
191 first === null || last === null
192 ? null
193 : {
194 refs: [...refs.values()],
195 isRepo: first.isRepo,
196 hasPrimaryRemote: first.hasPrimaryRemote,
197 nextCursor: last.nextCursor,
198 totalCount: Math.max(...values.map((value) => value.totalCount)),
199 };
200 const lastResult = results.at(-1);
201 const isFetchingNextPage =
202 results.length > 1 &&
203 lastResult?.waiting === true &&
204 Option.isNone(AsyncResult.value(lastResult));
205 const failed = results.find((result) => result._tag === "Failure");
206 const error =
207 failed?._tag === "Failure"
208 ? (() => {
209 const cause = Cause.squash(failed.cause);
210 return cause instanceof Error && cause.message.trim().length > 0
211 ? cause.message
212 : "Failed to load refs.";
213 })()
214 : null;
215 const refresh = useCallback(() => {
216 const firstPage = pageAtoms[0];
217 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
218 if (firstPage !== undefined) {
219 appAtomRegistry.refresh(firstPage);
220 }
221 }, [pageAtoms, targetKey]);
222 const loadNext = useCallback(() => {
223 if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {
224 return;
225 }
226 setPagination((current) => {
227 const currentCursors =
228 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
229 return currentCursors.includes(data.nextCursor!)
230 ? { targetKey, cursors: currentCursors }
231 : { targetKey, cursors: [...currentCursors, data.nextCursor!] };
232 });
233 }, [data?.nextCursor, targetKey]);
234​
235 return {
236 data,
237 refs: data?.refs ?? EMPTY_REFS,
238 error,
239 isPending: results.some((result) => result.waiting),
240 isFetchingNextPage,
241 refresh,
242 loadNext,
243 };
245​
246export function useComposerPathSearch(target: ComposerPathSearchTarget) {
247 const normalizedTarget = useMemo(
248 () => ({
249 environmentId: target.environmentId,
250 cwd: target.cwd,
251 query: normalizeComposerPathSearchQuery(target.query),
252 }),
253 [target.cwd, target.environmentId, target.query],
254 );
255 const debouncedTarget = useDebouncedValue(normalizedTarget, COMPOSER_PATH_SEARCH_DEBOUNCE_MS);
256 const result = useEnvironmentQuery(
257 debouncedTarget.environmentId !== null &&
258 debouncedTarget.cwd !== null &&
259 debouncedTarget.query.length > 0
260 ? projectEnvironment.searchEntries({
261 environmentId: debouncedTarget.environmentId,
262 input: {
263 cwd: debouncedTarget.cwd,
264 query: debouncedTarget.query,
265 limit: COMPOSER_PATH_SEARCH_LIMIT,
266 },
267 })
268 : null,
269 );
270​
271 return {
272 entries: result.data?.entries ?? [],
273 error: result.error,
274 isPending: normalizedTarget.query !== debouncedTarget.query || result.isPending,
275 refresh: result.refresh,
276 };
278​
279export function useCheckpointDiff(target: CheckpointDiffTarget) {
280 const targets = useMemo(
281 () => buildCheckpointDiffTargets(target),
282 [
283 target.environmentId,
284 target.fromTurnCount,
285 target.ignoreWhitespace,
286 target.threadId,
287 target.toTurnCount,
288 ],
289 );
290 const fullThread = useEnvironmentQuery(
291 targets.fullThread === null
292 ? null
293 : orchestrationEnvironment.fullThreadDiff(targets.fullThread),
294 );
295 const turn = useEnvironmentQuery(
296 targets.turn === null ? null : orchestrationEnvironment.turnDiff(targets.turn),
297 );
298 return targets.fullThread === null ? turn : fullThread;