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

queries.ts

260 lines8.2 KB

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