@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 506 lines 18.4 KB
Raw
1 import {
2 legacyThreadPullRequestKey,
3 threadPullRequestKeyOf,
4 } from "@t3tools/client-runtime/thread-pull-requests";
5 import {
6 composerPullRequestsFromLinks,
7 filterComposerPullRequestMatches,
8 withLinkedComposerPullRequestsFirst,
9 } from "@t3tools/shared/composerPullRequestMatches";
10 import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
11 import { environmentSession } from "./session";
12 import { useEnvironmentPresentation } from "./presentation";
13 import type { VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
14 import type {
15 EnvironmentId,
16 OrchestrationV2ProjectedTurnItem,
17 ProjectId,
18 ThreadPullRequestLink,
19 VcsListRefsResult,
20 VcsRef,
21 } from "@t3tools/contracts";
22 import {
23 createThreadSearchResultsAtomFamily,
24 makeThreadSearchKey,
25 visibleThreadSearch,
26 type EnvironmentThreadSearchMatch,
27 type SettledThreadSearch,
28 type ThreadSearchResultsState,
29 type ThreadSearchScope,
30 } from "@t3tools/client-runtime/state/thread-search";
31 import { THREAD_SEARCH_QUERY_MAX_LENGTH } from "@t3tools/contracts";
32 import { messageSearchTokens } from "@t3tools/shared/paletteSearch";
33 import { useAtomValue } from "@effect/atom-react";
34 import * as Cause from "effect/Cause";
35 import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
36 import * as Option from "effect/Option";
37 import { AsyncResult, Atom } from "effect/reactivity";
38 import { useEffect, useMemo, useState } from "react";
39
40 import { appAtomRegistry } from "./atom-registry";
41 import { orchestrationEnvironment } from "./orchestration";
42 import { olderSettledThreads, threadFamilies } from "./threads";
43 import { projectEnvironment } from "./projects";
44 import { useEnvironmentQuery } from "./query";
45 import { msg, useMessages } from "gt-react-native";
46 import { vcsEnvironment } from "./vcs";
47 import { composerPullRequests } from "./pull-requests";
48 import {
49 buildCheckpointDiffTargets,
50 normalizeComposerPathSearchQuery,
51 type CheckpointDiffTarget,
52 } from "./queryTargets";
53
54 const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
55 const COMPOSER_PATH_SEARCH_LIMIT = 20;
56 const THREAD_SEARCH_DEBOUNCE_MS = 120;
57 const VCS_REF_LIST_LIMIT = 100;
58 const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
59 const INITIAL_BRANCH_CURSORS = [undefined] as const;
60 const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
61 const EMPTY_THREAD_SEARCH_ATOM = Atom.make<ThreadSearchResultsState>({
62 matches: EMPTY_THREAD_SEARCH_MATCHES,
63 isLoading: false,
64 failed: false,
65 rows: [],
66 }).pipe(Atom.withLabel("mobile:thread-search:empty"));
67
68 const olderSettledBeforeAtom = Atom.family((environmentId: EnvironmentId) =>
69 Atom.make((get) => get(olderSettledThreads.olderSettledAtom(environmentId))?.before ?? null).pipe(
70 Atom.withLabel(`mobile:older-settled-before:${environmentId}`),
71 ),
72 );
73 // Whether any of these environments leaves older settled threads out, so short queries matter.
74 const anyOlderSettledAtom = Atom.family((environmentIdsKey: string) =>
75 Atom.make((get) =>
76 (JSON.parse(environmentIdsKey) as ReadonlyArray<EnvironmentId>).some(
77 (environmentId) => get(olderSettledBeforeAtom(environmentId)) !== null,
78 ),
79 ).pipe(Atom.withLabel(`mobile:any-older-settled:${environmentIdsKey}`)),
80 );
81 const threadSearch = createThreadSearchResultsAtomFamily({
82 getSearchAtom: (environmentId, input) =>
83 input.olderSettledBefore === undefined
84 ? orchestrationEnvironment.threadSearch({ environmentId, input })
85 : olderSettledThreads.searchAtom(environmentId, input),
86 olderSettledBefore: olderSettledBeforeAtom,
87 labelPrefix: "mobile:thread-search",
88 });
89
90 export interface ComposerPathSearchTarget {
91 readonly environmentId: EnvironmentId | null;
92 readonly cwd: string | null;
93 readonly query: string | null;
94 }
95
96 export function useDebouncedValue<A>(value: A, delayMs: number): A {
97 const [debounced, setDebounced] = useState(value);
98
99 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- timer that publishes the value after the delay and clears on change
100 useEffect(() => {
101 const timer = setTimeout(() => {
102 setDebounced(value);
103 }, delayMs);
104 return () => {
105 clearTimeout(timer);
106 };
107 }, [delayMs, value]);
108
109 return debounced;
110 }
111
112 export function useComposerPullRequestSearch(input: {
113 environmentId: EnvironmentId | null;
114 projectId: ProjectId | null;
115 repository: string | null;
116 threadPullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
117 query: string | null;
118 }) {
119 const query = useDebouncedValue(input.query, 180);
120 const linked =
121 input.projectId === null
122 ? []
123 : composerPullRequestsFromLinks(input.threadPullRequests ?? [], input.projectId);
124 const ready =
125 query === input.query &&
126 query !== null &&
127 input.environmentId !== null &&
128 input.projectId !== null &&
129 input.repository !== null;
130 const numeric = query !== null && /^\d*$/.test(query);
131 const list = useEnvironmentQuery(
132 ready
133 ? composerPullRequests.list({
134 environmentId: input.environmentId!,
135 input: {
136 projectId: input.projectId!,
137 state: "all",
138 limit: 200,
139 ...(!numeric && query ? { query } : {}),
140 },
141 })
142 : null,
143 );
144 const number = numeric && query ? Number(query) : null;
145 const hasExact = list.data?.entries.some(
146 (entry) =>
147 entry.number === number && entry.repository.toLowerCase() === input.repository?.toLowerCase(),
148 );
149 const exact = useEnvironmentQuery(
150 ready && number !== null && Number.isSafeInteger(number) && number > 0 && !hasExact
151 ? composerPullRequests.detail({
152 environmentId: input.environmentId!,
153 input: { projectId: input.projectId!, repository: input.repository!, number },
154 })
155 : null,
156 );
157 // Only the host: the URL's full repository path would not match the project's selector.
158 const exactEntry = exact.data
159 ? { ...exact.data, host: legacyThreadPullRequestKey(exact.data).host }
160 : null;
161 const entries = (() => {
162 if (input.query === null || input.projectId === null || input.repository === null) return [];
163 if (/^\d*$/.test(input.query)) {
164 return filterComposerPullRequestMatches({
165 keyOf: threadPullRequestKeyOf,
166 entries: ready ? [...(exactEntry ? [exactEntry] : []), ...(list.data?.entries ?? [])] : [],
167 linked,
168 projectId: input.projectId,
169 repository: input.repository,
170 query: input.query,
171 limit: 20,
172 });
173 }
174 if (!ready) {
175 return withLinkedComposerPullRequestsFirst({
176 keyOf: threadPullRequestKeyOf,
177 matches: [],
178 linked,
179 query: input.query,
180 limit: 20,
181 });
182 }
183 const words = (query ?? "").toLowerCase().split(/\s+/).filter(Boolean);
184 const found = [...(exactEntry ? [exactEntry] : []), ...(list.data?.entries ?? [])].filter(
185 (entry) =>
186 entry.projectId === input.projectId &&
187 entry.repository.toLowerCase() === input.repository?.toLowerCase() &&
188 words.every((word) =>
189 `${entry.title} ${entry.headBranch} ${entry.baseBranch}`.toLowerCase().includes(word),
190 ),
191 );
192 const unique = new Map<string, (typeof found)[number]>();
193 for (const entry of found) {
194 const key = threadPullRequestKeyOf(entry);
195 if (!unique.has(key)) unique.set(key, entry);
196 }
197 return withLinkedComposerPullRequestsFirst({
198 keyOf: threadPullRequestKeyOf,
199 matches: [...unique.values()].sort((left, right) =>
200 right.updatedAt.localeCompare(left.updatedAt),
201 ),
202 linked,
203 query: query ?? "",
204 limit: 20,
205 });
206 })();
207 return {
208 entries,
209 isPending: input.query !== null && (query !== input.query || list.isPending || exact.isPending),
210 error: list.error ?? list.data?.errors[0]?.message ?? exact.error,
211 };
212 }
213
214 /**
215 * Server matches for a thread search: message hits, and on environments that leave older settled
216 * threads out of the shell, the rows of the best older matches, mounted into the thread list while
217 * they show so the caller's own ranking finds them.
218 */
219 export function useThreadSearch(
220 environmentIds: ReadonlyArray<EnvironmentId>,
221 query: string,
222 scope: ThreadSearchScope = {},
223 ): {
224 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
225 /** The query `matches` are for, which lags the typed one while a search runs. */
226 readonly query: string;
227 readonly isPending: boolean;
228 /** No environment could run the search for the current query, so an empty result is not "no matches". */
229 readonly failed: boolean;
230 } {
231 // A pasted wall of text searches by its start rather than failing the request.
232 const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim();
233 const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
234 const anyOlderSettled = useAtomValue(anyOlderSettledAtom(JSON.stringify(environmentIds)));
235 // Messages need a word of three or more letters; older settled titles match from two.
236 const canSearch =
237 environmentIds.length > 0 &&
238 ((scope.titlesOnly !== true && messageSearchTokens(normalizedQuery).long.length > 0) ||
239 (anyOlderSettled && normalizedQuery.length >= 2));
240 const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
241 const searchKeyOf = (searchQuery: string) =>
242 makeThreadSearchKey(environmentIds, searchQuery, scope);
243 const searchKey = settledQuery === null ? null : searchKeyOf(settledQuery);
244 const result = useAtomValue(
245 searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearch.results(searchKey),
246 );
247 const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading);
248 const failed = settledQuery !== null && !result.isLoading && result.failed;
249 // What fast environments returned shows without waiting for a slow one;
250 // callers keep shown rows in place with `nextShownOrder`.
251 const ready =
252 settledQuery !== null &&
253 (!result.isLoading || result.matches.length > 0 || result.rows.length > 0)
254 ? { query: settledQuery, matches: result.matches }
255 : null;
256 // Kept from earlier renders: React's pattern for information from previous renders.
257 const [previous, setPrevious] = useState<SettledThreadSearch | null>(null);
258 if (ready !== null && previous?.matches !== ready.matches) setPrevious(ready);
259 const visible = canSearch
260 ? visibleThreadSearch(normalizedQuery, ready, previous)
261 : { query: "", matches: EMPTY_THREAD_SEARCH_MATCHES };
262 // The shown results' rows stay mounted until newer results replace them.
263 const shownKey = visible.query === "" ? null : searchKeyOf(visible.query);
264 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mounts the shown search results' rows into the shared thread registry until newer results replace them
265 useEffect(() => {
266 if (shownKey === null) return;
267 const environments = (JSON.parse(shownKey) as [ReadonlyArray<EnvironmentId>])[0];
268 const releases = environments.map((environmentId) =>
269 threadFamilies.mountRows(
270 appAtomRegistry,
271 environmentId,
272 `search:${shownKey}`,
273 threadSearch.rows(shownKey, environmentId),
274 ),
275 );
276 return () => {
277 for (const release of releases) release();
278 };
279 }, [shownKey]);
280 return {
281 matches: visible.matches,
282 query: visible.query,
283 isPending,
284 failed,
285 };
286 }
287
288 export function useBranches(input: {
289 readonly environmentId: EnvironmentId | null;
290 readonly cwd: string | null;
291 readonly query?: string | null;
292 }) {
293 const query = input.query?.trim() ?? "";
294 return useEnvironmentQuery(
295 input.environmentId !== null && input.cwd !== null
296 ? vcsEnvironment.listRefs({
297 environmentId: input.environmentId,
298 input: {
299 cwd: input.cwd,
300 ...(query.length > 0 ? { query } : {}),
301 limit: VCS_REF_LIST_LIMIT,
302 },
303 })
304 : null,
305 );
306 }
307
308 export function usePaginatedBranches(target: VcsRefTarget) {
309 const resolve = useMessages();
310 const query = target.query?.trim() ?? "";
311 const targetKey =
312 target.environmentId !== null && target.cwd !== null
313 ? JSON.stringify([target.environmentId, target.cwd, query])
314 : null;
315 const [pagination, setPagination] = useState<{
316 readonly targetKey: string | null;
317 readonly cursors: ReadonlyArray<number | undefined>;
318 }>({
319 targetKey,
320 cursors: INITIAL_BRANCH_CURSORS,
321 });
322 const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
323 const pageAtoms = useMemo(
324 () =>
325 target.environmentId !== null && target.cwd !== null
326 ? cursors.map((cursor) =>
327 vcsEnvironment.listRefs({
328 environmentId: target.environmentId!,
329 input: {
330 cwd: target.cwd!,
331 ...(query.length > 0 ? { query } : {}),
332 ...(cursor === undefined ? {} : { cursor }),
333 limit: VCS_REF_LIST_LIMIT,
334 },
335 }),
336 )
337 : [],
338 [target.environmentId, target.cwd, query, cursors],
339 );
340 const pagesAtom = useMemo(
341 () =>
342 Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
343 Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
344 ),
345 [pageAtoms, targetKey],
346 );
347 const results = useAtomValue(pagesAtom);
348 const values = results.flatMap((result) => {
349 const value = AsyncResult.getOrElse(result, () => null);
350 return value === null ? [] : [value];
351 });
352 const refs = new Map<string, VcsRef>();
353 for (const value of values) {
354 for (const ref of value.refs) {
355 refs.set(ref.name, ref);
356 }
357 }
358 const first = values[0] ?? null;
359 const last = values.at(-1) ?? null;
360 const data: VcsListRefsResult | null =
361 first === null || last === null
362 ? null
363 : {
364 refs: [...refs.values()],
365 isRepo: first.isRepo,
366 hasPrimaryRemote: first.hasPrimaryRemote,
367 nextCursor: last.nextCursor,
368 totalCount: Math.max(...values.map((value) => value.totalCount)),
369 };
370 const lastResult = results.at(-1);
371 const isFetchingNextPage =
372 results.length > 1 &&
373 lastResult?.waiting === true &&
374 Option.isNone(AsyncResult.value(lastResult));
375 const failed = results.find((result) => result._tag === "Failure");
376 const error =
377 failed?._tag === "Failure"
378 ? (() => {
379 const cause = Cause.squash(failed.cause);
380 return cause instanceof Error && cause.message.trim().length > 0
381 ? cause.message
382 : resolve(msg("Failed to load refs."));
383 })()
384 : null;
385 const refresh = () => {
386 const firstPage = pageAtoms[0];
387 setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
388 if (firstPage !== undefined) {
389 appAtomRegistry.refresh(firstPage);
390 }
391 };
392 const loadNext = () => {
393 if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {
394 return;
395 }
396 setPagination((current) => {
397 const currentCursors =
398 current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
399 return currentCursors.includes(data.nextCursor!)
400 ? { targetKey, cursors: currentCursors }
401 : { targetKey, cursors: [...currentCursors, data.nextCursor!] };
402 });
403 };
404
405 return {
406 data,
407 refs: data?.refs ?? EMPTY_REFS,
408 error,
409 isPending: results.some((result) => result.waiting),
410 isFetchingNextPage,
411 refresh,
412 loadNext,
413 };
414 }
415
416 export function useComposerPathSearch(target: ComposerPathSearchTarget) {
417 const resolve = useMessages();
418 const query = normalizeComposerPathSearchQuery(target.query);
419 const normalizedTarget = { environmentId: target.environmentId, cwd: target.cwd, query };
420 const debouncedTarget = useDebouncedValue(normalizedTarget, COMPOSER_PATH_SEARCH_DEBOUNCE_MS);
421 const fileAccessSession = useEnvironmentQuery(
422 debouncedTarget.environmentId === null
423 ? null
424 : environmentSession.sessionStateAtom(debouncedTarget.environmentId),
425 );
426 const fileEnvironment = useEnvironmentPresentation(debouncedTarget.environmentId);
427 const fileAccess = resolveFilesystemReadAccess(
428 {
429 isCatalogReady: fileEnvironment.isReady,
430 connection: fileEnvironment.presentation?.connection ?? null,
431 session: fileAccessSession.data,
432 sessionError: fileAccessSession.error,
433 },
434 resolve,
435 );
436 const { canReadFiles } = fileAccess;
437 const searchTarget =
438 debouncedTarget.environmentId !== null &&
439 debouncedTarget.cwd !== null &&
440 debouncedTarget.query !== null
441 ? {
442 environmentId: debouncedTarget.environmentId,
443 input: {
444 cwd: debouncedTarget.cwd,
445 query: debouncedTarget.query.slice(0, 256).replace(/[\uD800-\uDBFF]$/, ""),
446 limit: COMPOSER_PATH_SEARCH_LIMIT,
447 },
448 }
449 : null;
450 const result = useEnvironmentQuery(
451 canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
452 );
453 const hasTarget = searchTarget !== null;
454 const isSameCheckout =
455 normalizedTarget.environmentId === debouncedTarget.environmentId &&
456 normalizedTarget.cwd === debouncedTarget.cwd;
457
458 return {
459 // Entries from another checkout must not be offered while the new one is debounced.
460 entries: isSameCheckout ? (result.data?.entries ?? []) : [],
461 error:
462 !hasTarget || fileAccess.isPending
463 ? null
464 : canReadFiles
465 ? result.error
466 : (fileAccess.error ?? resolve(msg("This connection cannot search host files."))),
467 isPending:
468 !isSameCheckout ||
469 normalizedTarget.query !== debouncedTarget.query ||
470 (hasTarget && (fileAccess.isPending || result.isPending)),
471 refresh: result.refresh,
472 };
473 }
474
475 export function useCheckpointDiff(target: CheckpointDiffTarget) {
476 const targets = buildCheckpointDiffTargets(target);
477 const fullThread = useEnvironmentQuery(
478 targets.fullThread === null
479 ? null
480 : orchestrationEnvironment.fullThreadDiff(targets.fullThread),
481 );
482 const turn = useEnvironmentQuery(
483 targets.turn === null ? null : orchestrationEnvironment.turnDiff(targets.turn),
484 );
485 return targets.fullThread === null ? turn : fullThread;
486 }
487
488 export function useTurnItemDetail(
489 target: {
490 readonly environmentId: EnvironmentId;
491 readonly row: OrchestrationV2ProjectedTurnItem;
492 } | null,
493 ) {
494 return useEnvironmentQuery(
495 target === null
496 ? null
497 : orchestrationEnvironment.turnItem({
498 environmentId: target.environmentId,
499 input: {
500 threadId: target.row.sourceThreadId,
501 itemId: target.row.sourceItemId,
502 revision: turnItemDetailRevision(target.row.item),
503 },
504 }),
505 );
506 }