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