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

queries.ts

272 lines8.9 KB

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