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