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

main
ts 578 lines 22.1 KB
Raw
1 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2 import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
3 import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
4 import { ProjectListEntriesError, type EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
5 import * as Cause from "effect/Cause";
6 import * as Schema from "effect/Schema";
7 import { useLayoutEffect, useRef, useState } from "react";
8 import { Atom } from "effect/reactivity";
9 import { msg } from "gt-react-native";
10
11 import { environmentCatalog } from "../../connection/catalog";
12 import { m } from "../../i18n/messages";
13 import { appAtomRegistry } from "../../state/atom-registry";
14 import { projectEnvironment } from "../../state/projects";
15 import { useDebouncedValue } from "../../state/queries";
16 import { useEnvironmentQuery } from "../../state/query";
17
18 const isProjectListEntriesError = Schema.is(ProjectListEntriesError);
19
20 function createDirectories() {
21 return {
22 target: {},
23 entries: new Map<string, ReadonlyArray<ProjectEntry>>(),
24 errors: new Map<string, string>(),
25 completeDirectories: new Set<string>(),
26 listingCompletedAt: new Map<string, number>(),
27 discoveries: new Map<string, ProjectEntry>(),
28 rootListing: null as { readonly timestamp: number } | null,
29 validatedDirectories: new Set<string>(),
30 loading: new Set<string>(),
31 expandedPaths: new Set<string>(),
32 selectedPath: null as string | null,
33 revealedSelection: { path: null as string | null, ancestors: new Set<string>() },
34 isRefreshing: false,
35 };
36 }
37
38 function boundDirectories(current: ReturnType<typeof createDirectories>, preserveVisible = true) {
39 const visible = (path: string) => {
40 const parts = path.split("/");
41 return parts.every((_, index) =>
42 current.expandedPaths.has(parts.slice(0, index + 1).join("/")),
43 );
44 };
45 const inactive = [...new Set([...current.entries.keys(), ...current.errors.keys()])].filter(
46 (path) => !preserveVisible || !visible(path),
47 );
48 const ownedPaths = [
49 ...current.entries.keys(),
50 ...current.expandedPaths,
51 current.selectedPath,
52 ].filter((path) => path !== null);
53 const discoveries = new Map(
54 [...current.discoveries].filter(([path]) =>
55 ownedPaths.some((owned) => owned === path || owned.startsWith(`${path}/`)),
56 ),
57 );
58 if (inactive.length <= 64)
59 return discoveries.size === current.discoveries.size ? current : { ...current, discoveries };
60 const evicted = new Set(inactive.slice(0, -64));
61 // Evict listing data, not the user's expansion and selection. A missing parent reloads on return.
62 return {
63 ...current,
64 discoveries,
65 entries: new Map([...current.entries].filter(([path]) => !evicted.has(path))),
66 errors: new Map([...current.errors].filter(([path]) => !evicted.has(path))),
67 completeDirectories: new Set(
68 [...current.completeDirectories].filter((path) => !evicted.has(path)),
69 ),
70 validatedDirectories: new Set(
71 [...current.validatedDirectories].filter((path) => !evicted.has(path)),
72 ),
73 listingCompletedAt: new Map(
74 [...current.listingCompletedAt].filter(([path]) => !evicted.has(path)),
75 ),
76 };
77 }
78
79 function contradictsListing(path: string, parent: string, entries: ReadonlyArray<ProjectEntry>) {
80 if (parent !== "" && !path.startsWith(`${parent}/`)) return false;
81 const child = path.slice(parent === "" ? 0 : parent.length + 1).split("/")[0];
82 const childPath = parent === "" ? child : `${parent}/${child}`;
83 const entry = entries.find((item) => item.path === childPath);
84 return !entry || (path !== childPath && entry.kind !== "directory");
85 }
86
87 function createRequests() {
88 return {
89 active: true,
90 refreshVersion: 0,
91 pending: new Map<string, AbortController>(),
92 };
93 }
94
95 function getRequests(
96 requestsByTarget: WeakMap<object, ReturnType<typeof createRequests>>,
97 target: object,
98 ) {
99 let requests = requestsByTarget.get(target);
100 if (!requests) {
101 requests = createRequests();
102 requestsByTarget.set(target, requests);
103 }
104 return requests;
105 }
106 const noSessionGeneration = Atom.make(0);
107
108 export function useFileTreeEntries(input: {
109 readonly cwd: string | null;
110 readonly environmentId: EnvironmentId | null;
111 readonly searchQuery: string;
112 }) {
113 const { cwd, environmentId } = input;
114 const searching = input.searchQuery.trim().length > 0;
115 const query = input.searchQuery.trim().slice(0, 256);
116 const debouncedQuery = useDebouncedValue(query, 200);
117 const root = useEnvironmentQuery(
118 cwd !== null && environmentId !== null
119 ? projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath: "" } })
120 : null,
121 );
122 const { refresh: refreshRoot } = root;
123 const search = useEnvironmentQuery(
124 searching && debouncedQuery.length > 0 && cwd !== null && environmentId !== null
125 ? projectEnvironment.searchEntries({
126 environmentId,
127 input: { cwd, query: debouncedQuery, limit: 200 },
128 })
129 : null,
130 );
131 const workspaceKey = JSON.stringify([environmentId, cwd]);
132 const [cache, setCache] = useState(() => ({
133 key: workspaceKey,
134 workspaces: new Map([[workspaceKey, createDirectories()]]),
135 }));
136 const savedDirectories = cache.workspaces.get(workspaceKey) ?? createDirectories();
137 // Requests belong to a visit, so returning cannot revive an old completion.
138 const directories =
139 cache.key === workspaceKey
140 ? savedDirectories
141 : {
142 ...savedDirectories,
143 target: {},
144 validatedDirectories: new Set<string>(),
145 errors: new Map<string, string>(),
146 loading: new Set<string>(),
147 isRefreshing: false,
148 };
149 if (cache.key !== workspaceKey) {
150 const workspaces = new Map(cache.workspaces);
151 const previous = workspaces.get(cache.key);
152 if (previous) {
153 workspaces.set(
154 cache.key,
155 boundDirectories(
156 {
157 ...previous,
158 errors: new Map(),
159 loading: new Set(),
160 isRefreshing: false,
161 },
162 false,
163 ),
164 );
165 }
166 workspaces.delete(workspaceKey);
167 workspaces.set(workspaceKey, directories);
168 if (workspaces.size > 8) workspaces.delete(workspaces.keys().next().value!);
169 setCache({ key: workspaceKey, workspaces });
170 }
171 const setDirectories = (
172 update: (current: ReturnType<typeof createDirectories>) => ReturnType<typeof createDirectories>,
173 ) =>
174 setCache((current) => {
175 const previous = current.workspaces.get(workspaceKey);
176 if (!previous) return current;
177 const next = boundDirectories(update(previous));
178 if (next === previous) return current;
179 return { ...current, workspaces: new Map(current.workspaces).set(workspaceKey, next) };
180 });
181 const { target } = directories;
182 const requestsByTarget = useRef(new WeakMap<object, ReturnType<typeof createRequests>>());
183 // Cancel the old target before consumers' passive effects start new directory loads.
184 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads the root and aborts the old target's directory requests before consumers start new loads
185 useLayoutEffect(() => {
186 const requests = getRequests(requestsByTarget.current, target);
187 requests.active = true;
188 refreshRoot();
189 return () => {
190 requests.active = false;
191 requests.refreshVersion++;
192 for (const controller of requests.pending.values()) controller.abort();
193 requests.pending.clear();
194 setDirectories((current) =>
195 current.target === target
196 ? { ...current, loading: new Set(), isRefreshing: false }
197 : current,
198 );
199 };
200 }, [target, setDirectories, requestsByTarget, refreshRoot]);
201 const updateDirectories = (
202 update: (current: ReturnType<typeof createDirectories>) => ReturnType<typeof createDirectories>,
203 ) => setDirectories((current) => (current.target === target ? update(current) : current));
204 const loadDirectory = (directoryPath: string, refresh = false) => {
205 const requests = getRequests(requestsByTarget.current, target);
206 if (
207 !requests.active ||
208 missingRoot ||
209 cwd === null ||
210 environmentId === null ||
211 (!refresh && directories.validatedDirectories.has(directoryPath)) ||
212 requests.pending.has(directoryPath)
213 ) {
214 return;
215 }
216 const controller = new AbortController();
217 requests.pending.set(directoryPath, controller);
218 updateDirectories((current) => {
219 const errors = new Map(current.errors);
220 errors.delete(directoryPath);
221 return { ...current, errors, loading: new Set(current.loading).add(directoryPath) };
222 });
223 const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
224 appAtomRegistry.refresh(atom);
225 return executeAtomQuery(appAtomRegistry, atom, {
226 signal: controller.signal,
227 reportFailure: false,
228 reportDefect: false,
229 }).then((result) => {
230 if (controller.signal.aborted) return;
231 requests.pending.delete(directoryPath);
232 updateDirectories((current) => {
233 const validatedDirectories = new Set(current.validatedDirectories).add(directoryPath);
234 const loading = new Set(current.loading);
235 loading.delete(directoryPath);
236 if (result._tag === "Success") {
237 const entries = new Map(current.entries);
238 entries.delete(directoryPath);
239 entries.set(
240 directoryPath,
241 result.value.entries.filter(
242 (entry) =>
243 entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
244 ),
245 );
246 const completeDirectories = new Set(current.completeDirectories);
247 if (result.value.truncated) completeDirectories.delete(directoryPath);
248 else completeDirectories.add(directoryPath);
249 return {
250 ...current,
251 entries,
252 loading,
253 completeDirectories,
254 discoveries: result.value.truncated
255 ? current.discoveries
256 : new Map(
257 [...current.discoveries].filter(
258 ([path]) => !contradictsListing(path, directoryPath, result.value.entries),
259 ),
260 ),
261 validatedDirectories,
262 listingCompletedAt: new Map(current.listingCompletedAt).set(
263 directoryPath,
264 result.timestamp,
265 ),
266 };
267 }
268 const error = Cause.squash(result.cause);
269 return {
270 ...current,
271 loading,
272 validatedDirectories,
273 errors: new Map(current.errors).set(
274 directoryPath,
275 error instanceof Error
276 ? (errorDisplayMessage(error, m) ?? error.message)
277 : m(msg("Files unavailable")),
278 ),
279 };
280 });
281 });
282 };
283 const missingRoot =
284 isProjectListEntriesError(root.failure) && root.failure.failure === "workspace_root_not_found";
285 const rootData = missingRoot ? null : root.data;
286 const rootListing = root.successResult ?? directories.rootListing;
287 if (
288 missingRoot &&
289 (directories.entries.size > 0 ||
290 directories.errors.size > 0 ||
291 directories.loading.size > 0 ||
292 directories.expandedPaths.size > 0 ||
293 directories.selectedPath !== null ||
294 directories.discoveries.size > 0)
295 ) {
296 setDirectories(() => createDirectories());
297 }
298 const { refresh: refreshSearch, data: searchData, successResult: searchResult } = search;
299 // A folder read fails at once while its environment is unreachable; read it again once a new
300 // session is up rather than leaving the error until someone refreshes.
301 const sessionGeneration =
302 environmentId === null
303 ? noSessionGeneration
304 : environmentCatalog.sessionGenerationAtom(environmentId);
305 // A listener alone does not compute the atom, so nothing would follow the connection.
306 useAtomMount(sessionGeneration);
307 useAtomSubscribe(sessionGeneration, () => {
308 for (const path of directories.errors.keys()) void loadDirectory(path, true);
309 });
310 const snapshot = (() => {
311 const merged = new Map(missingRoot ? [] : directories.discoveries);
312 if (searching && !missingRoot) {
313 for (const entry of searchData?.entries ?? []) merged.set(entry.path, entry);
314 }
315 const reachableDirectories = new Set<string>();
316 const visit = (items: ReadonlyArray<ProjectEntry>) => {
317 for (const entry of items) {
318 merged.set(entry.path, entry);
319 if (entry.kind === "directory") {
320 reachableDirectories.add(entry.path);
321 visit(directories.entries.get(entry.path) ?? []);
322 }
323 }
324 };
325 if (!missingRoot) {
326 const discoveries = new Map(directories.discoveries);
327 // Search can return only leaves; their inferred parents still own loaded children.
328 for (const entry of directories.discoveries.values()) {
329 const parts = entry.path.split("/");
330 for (let index = 1; index < parts.length; index++) {
331 const path = parts.slice(0, index).join("/");
332 if (!discoveries.has(path)) discoveries.set(path, { kind: "directory", path });
333 }
334 }
335 visit([...discoveries.values()]);
336 }
337 visit((rootData?.entries ?? []).filter((entry) => !entry.path.includes("/")));
338 return {
339 entries: [...merged.values()],
340 reachableDirectories,
341 searchResultPaths:
342 searching && !missingRoot
343 ? new Set((searchData?.entries ?? []).map((entry) => entry.path))
344 : null,
345 };
346 })();
347
348 if (rootData) {
349 const deleted = (path: string, directory = false) => {
350 const parts = path.split("/");
351 for (let index = 0; index < parts.length; index++) {
352 const parent = parts.slice(0, index).join("/");
353 const listing = index === 0 ? rootData.entries : directories.entries.get(parent);
354 const child = parts.slice(0, index + 1).join("/");
355 const complete =
356 index === 0 ? !rootData.truncated : directories.completeDirectories.has(parent);
357 const entry = listing?.find((item) => item.path === child);
358 if (complete && listing && !entry) {
359 const listingCompletedAt =
360 index === 0 && directories.rootListing !== rootListing
361 ? rootListing?.timestamp
362 : directories.listingCompletedAt.get(parent);
363 // Cached queries keep their completion time across query switches.
364 // Equal-millisecond responses cannot prove a path postdates the listing.
365 const retained =
366 !(index === 0 && directories.rootListing !== rootListing) &&
367 [...directories.discoveries.keys()].some(
368 (path) => path === child || path.startsWith(`${child}/`),
369 );
370 const discovered =
371 retained ||
372 (searching &&
373 query === debouncedQuery &&
374 searchResult !== null &&
375 searchResult.timestamp > (listingCompletedAt ?? -Infinity) &&
376 searchData?.entries.some(
377 (item) => item.path === child || item.path.startsWith(`${child}/`),
378 ));
379 if (!discovered) return true;
380 }
381 if (entry && (directory || index < parts.length - 1) && entry.kind !== "directory")
382 return true;
383 }
384 return false;
385 };
386 const reconciled = (() => {
387 const current = directories;
388 const discoveries = new Map(current.discoveries);
389 if (current.rootListing !== rootListing && !rootData.truncated) {
390 for (const path of discoveries.keys()) {
391 if (contradictsListing(path, "", rootData.entries)) discoveries.delete(path);
392 }
393 }
394 if (searching && query === debouncedQuery && searchResult !== null) {
395 const ownedPaths = [
396 ...current.entries.keys(),
397 ...current.expandedPaths,
398 current.selectedPath,
399 ];
400 for (const entry of searchData?.entries ?? []) {
401 if (
402 ownedPaths.some((path) => path === entry.path || path?.startsWith(`${entry.path}/`)) &&
403 !deleted(entry.path, entry.kind === "directory")
404 )
405 discoveries.set(entry.path, entry);
406 }
407 }
408 const entries = new Map([...current.entries].filter(([path]) => !deleted(path, true)));
409 const errors = new Map([...current.errors].filter(([path]) => !deleted(path, true)));
410 const expandedPaths = new Set(
411 [...current.expandedPaths].filter((path) => !deleted(path, true)),
412 );
413 const selectedPath =
414 current.selectedPath !== null && deleted(current.selectedPath)
415 ? null
416 : current.selectedPath;
417 if (
418 entries.size === current.entries.size &&
419 errors.size === current.errors.size &&
420 expandedPaths.size === current.expandedPaths.size &&
421 selectedPath === current.selectedPath &&
422 current.rootListing === rootListing &&
423 discoveries.size === current.discoveries.size &&
424 [...discoveries].every(([path, entry]) => current.discoveries.get(path) === entry)
425 )
426 return current;
427 const completeDirectories = new Set(
428 [...current.completeDirectories].filter((path) => entries.has(path)),
429 );
430 return {
431 ...current,
432 rootListing,
433 discoveries,
434 listingCompletedAt: new Map(
435 [...current.listingCompletedAt].filter(([path]) => path === "" || entries.has(path)),
436 ).set(
437 "",
438 current.rootListing === rootListing
439 ? (current.listingCompletedAt.get("") ?? -Infinity)
440 : (rootListing?.timestamp ?? -Infinity),
441 ),
442 entries,
443 errors,
444 expandedPaths,
445 selectedPath,
446 completeDirectories,
447 validatedDirectories: new Set(
448 [...current.validatedDirectories].filter((path) => !deleted(path, true)),
449 ),
450 };
451 })();
452 if (reconciled !== directories) setDirectories(() => reconciled);
453 }
454
455 const refresh = () => {
456 const requests = getRequests(requestsByTarget.current, target);
457 if (!requests.active) return Promise.resolve();
458 refreshRoot();
459 if (searching && !missingRoot) refreshSearch();
460 const paths = new Set(
461 [...directories.entries.keys(), ...directories.errors.keys(), ...directories.loading].filter(
462 (path) => snapshot.reachableDirectories.has(path),
463 ),
464 );
465 for (const controller of requests.pending.values()) controller.abort();
466 requests.pending.clear();
467 const version = ++requests.refreshVersion;
468 updateDirectories((current) => ({
469 ...current,
470 errors: new Map(),
471 loading: new Set(),
472 isRefreshing: true,
473 }));
474 const remaining = paths.values();
475 const worker = async () => {
476 while (requests.active && version === requests.refreshVersion) {
477 const next = remaining.next();
478 if (next.done) return;
479 await loadDirectory(next.value, true);
480 }
481 };
482 const queries =
483 cwd !== null && environmentId !== null
484 ? [
485 projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath: "" } }),
486 ...(searching && !missingRoot
487 ? [
488 projectEnvironment.searchEntries({
489 environmentId,
490 input: { cwd, query: debouncedQuery, limit: 200 },
491 }),
492 ]
493 : []),
494 ]
495 : [];
496 const work = [
497 ...queries.map((atom) =>
498 executeAtomQuery(appAtomRegistry, atom, { reportFailure: false, reportDefect: false }),
499 ),
500 ...Array.from({ length: Math.min(4, paths.size) }, () => worker()),
501 ];
502 return Promise.all(work).finally(() => {
503 if (version === requests.refreshVersion) {
504 updateDirectories((current) => ({ ...current, isRefreshing: false }));
505 }
506 });
507 };
508
509 const revealSelection = (path: string | null) => {
510 if (missingRoot) return;
511 updateDirectories((current) => {
512 const previous = current.revealedSelection;
513 const handled = previous.path === path ? previous.ancestors : new Set<string>();
514 const parts = path?.split("/").filter(Boolean) ?? [];
515 const ancestors = parts
516 .slice(1)
517 .map((_, index) => parts.slice(0, index + 1).join("/"))
518 .filter(
519 (ancestor) =>
520 !handled.has(ancestor) &&
521 snapshot.entries.some(
522 (entry) =>
523 (entry.kind === "directory" && entry.path === ancestor) ||
524 (entry.path === path && entry.path.startsWith(`${ancestor}/`)),
525 ),
526 );
527 if (previous.path === path && ancestors.length === 0) return current;
528 return {
529 ...current,
530 discoveries: new Map([
531 ...current.discoveries,
532 ...snapshot.entries
533 .filter((entry) => entry.path === path)
534 .map((entry) => [entry.path, entry] as const),
535 ]),
536 selectedPath: path,
537 revealedSelection: { path, ancestors: new Set([...handled, ...ancestors]) },
538 expandedPaths: new Set([...current.expandedPaths, ...ancestors]),
539 };
540 });
541 };
542
543 const setExpandedPaths = (update: (current: ReadonlySet<string>) => ReadonlySet<string>) =>
544 setDirectories((current) => {
545 const expandedPaths = update(current.expandedPaths);
546 return expandedPaths === current.expandedPaths
547 ? current
548 : { ...current, expandedPaths: new Set(expandedPaths) };
549 });
550
551 return {
552 revealSelection,
553 expandedPaths: directories.expandedPaths,
554 setExpandedPaths,
555 selectedPath: directories.selectedPath,
556 selectPath: (selectedPath: string) =>
557 updateDirectories((current) => ({ ...current, selectedPath })),
558 entries: snapshot.entries,
559 searchResultPaths: snapshot.searchResultPaths,
560 isRefreshing: directories.isRefreshing,
561 error:
562 root.error ??
563 (searching ? search.error : null) ??
564 [...directories.errors].find(([path]) => snapshot.reachableDirectories.has(path))?.[1] ??
565 null,
566 isPending:
567 !missingRoot &&
568 (root.isPending ||
569 directories.loading.size > 0 ||
570 (searching && (query !== debouncedQuery || search.isPending))),
571 searchTruncated: !missingRoot && searching && (search.data?.truncated ?? false),
572 loadedDirectories: new Set(directories.entries.keys()),
573 loadingDirectories: directories.loading,
574 loadDirectory: (path: string, retry = false) =>
575 loadDirectory(path, retry && directories.errors.has(path)),
576 refresh,
577 };
578 }