@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 194 lines 8.04 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
3 import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
4 import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
5 import * as Cause from "effect/Cause";
6 import { msg } from "gt-react";
7 import { useEffect, useRef, useState } from "react";
8
9 import { environmentCatalog } from "~/connection/catalog";
10 import { m } from "~/i18n/messages";
11 import { appAtomRegistry } from "~/rpc/atomRegistry";
12 import { projectEnvironment } from "~/state/projects";
13
14 export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
15 const [directories, setDirectories] = useState(new Map<string, readonly ProjectEntry[]>());
16 const [errors, setErrors] = useState(new Map<string, string>());
17 const [pending, setPending] = useState(1);
18 const [loadingDirectories, setLoadingDirectories] = useState<ReadonlySet<string>>(
19 () => new Set([""]),
20 );
21 // Source of truth for `directories`, so a listing can purge folders it no longer holds.
22 const listings = useRef(new Map<string, readonly ProjectEntry[]>());
23 const requests = useRef(new Map<string, Promise<void>>());
24 const detachedRequests = useRef(new Map<string, Promise<void>>());
25 const followUpRefreshes = useRef(new Map<string, Promise<void>>());
26 const loaded = useRef(new Set<string>());
27 const requested = useRef(new Set<string>());
28 const active = useRef(true);
29 const running = useRef(0);
30 const waiting = useRef<Array<() => void>>([]);
31
32 const startRequest = (directoryPath: string, refresh: boolean): Promise<void> => {
33 loaded.current.add(directoryPath);
34 requested.current.add(directoryPath);
35 const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
36 const detached = detachedRequests.current.get(directoryPath);
37 const request = (async () => {
38 // A shared query still waiting would join the removed folder's read.
39 if (detached) await detached;
40 if (running.current >= 4) await new Promise<void>((resolve) => waiting.current.push(resolve));
41 else running.current++;
42 const result = active.current
43 ? await executeAtomQuery(appAtomRegistry, atom, {
44 refresh: true,
45 reportFailure: false,
46 reportDefect: false,
47 })
48 : undefined;
49 const next = waiting.current.shift();
50 if (next) next();
51 else running.current--;
52 return result;
53 })()
54 .then((result) => {
55 // A request is dropped from `requests` when its folder disappears, so its read is stale.
56 if (!active.current || !result || requests.current.get(directoryPath) !== request) return;
57 if (result._tag === "Success") {
58 const children = result.value.entries.filter(
59 (entry) =>
60 entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
61 );
62 const next = new Map(listings.current).set(directoryPath, children);
63 const childDirectories = new Set(
64 children.filter((entry) => entry.kind === "directory").map((entry) => entry.path),
65 );
66 const prefix = directoryPath === "" ? "" : `${directoryPath}/`;
67 const removed = [...requested.current].filter((path) => {
68 if (path === directoryPath || !path.startsWith(prefix)) return false;
69 const slash = path.indexOf("/", prefix.length);
70 return !childDirectories.has(slash === -1 ? path : path.slice(0, slash));
71 });
72 for (const path of removed) {
73 next.delete(path);
74 loaded.current.delete(path);
75 requested.current.delete(path);
76 const detachedRequest = requests.current.get(path);
77 if (detachedRequest) detachedRequests.current.set(path, detachedRequest);
78 requests.current.delete(path);
79 followUpRefreshes.current.delete(path);
80 }
81 listings.current = next;
82 setDirectories(next);
83 if (removed.length > 0)
84 setLoadingDirectories((previous) => {
85 const remaining = new Set(previous);
86 for (const path of removed) remaining.delete(path);
87 return remaining;
88 });
89 setErrors((previous) => {
90 const remaining = new Map(previous);
91 for (const path of [directoryPath, ...removed]) remaining.delete(path);
92 return remaining;
93 });
94 } else {
95 loaded.current.delete(directoryPath);
96 const cause = Cause.squash(result.cause);
97 setErrors((previous) =>
98 new Map(previous).set(
99 directoryPath,
100 thrownErrorMessage(cause, m) ?? m(msg("Unable to load folder.")),
101 ),
102 );
103 }
104 })
105 .finally(() => {
106 if (detachedRequests.current.get(directoryPath) === request)
107 detachedRequests.current.delete(directoryPath);
108 const current = requests.current.get(directoryPath) === request;
109 if (current) requests.current.delete(directoryPath);
110 if (!active.current) return;
111 setPending((count) => count - 1);
112 if (!refresh && current)
113 setLoadingDirectories((previous) => {
114 const next = new Set(previous);
115 next.delete(directoryPath);
116 return next;
117 });
118 });
119 requests.current.set(directoryPath, request);
120 return request;
121 };
122
123 const load = function loadDirectory(directoryPath: string, refresh = false): Promise<void> {
124 const existing = requests.current.get(directoryPath);
125 if (existing) {
126 if (!refresh) return existing;
127 let followUp = followUpRefreshes.current.get(directoryPath);
128 if (!followUp) {
129 followUp = existing.then(() => {
130 if (followUpRefreshes.current.get(directoryPath) !== followUp) return;
131 followUpRefreshes.current.delete(directoryPath);
132 if (active.current && requested.current.has(directoryPath))
133 return loadDirectory(directoryPath, true);
134 });
135 followUpRefreshes.current.set(directoryPath, followUp);
136 }
137 return followUp;
138 }
139 if (!refresh && loaded.current.has(directoryPath)) return Promise.resolve();
140 setPending((count) => count + 1);
141 if (!refresh) setLoadingDirectories((previous) => new Set(previous).add(directoryPath));
142 return startRequest(directoryPath, refresh);
143 };
144
145 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the root directory read on mount and marks the hook inactive so late reads are ignored
146 useEffect(() => {
147 active.current = true;
148 if (!requests.current.has("") && !loaded.current.has("")) void startRequest("", false);
149 return () => {
150 active.current = false;
151 };
152 }, [startRequest]);
153
154 // A folder read fails at once while its environment is unreachable; read it again once a new
155 // session is up rather than leaving the error until someone retries by hand.
156 const sessionGeneration = environmentCatalog.sessionGenerationAtom(environmentId);
157 // A listener alone does not compute the atom, so nothing would follow the connection.
158 useAtomMount(sessionGeneration);
159 useAtomSubscribe(sessionGeneration, () => {
160 for (const path of errors.keys()) void load(path);
161 });
162
163 const entries: ProjectEntry[] = [];
164 const visit = (path: string) => {
165 for (const entry of directories.get(path) ?? []) {
166 entries.push(entry);
167 if (entry.kind === "directory") visit(entry.path);
168 }
169 };
170 visit("");
171
172 const reachableDirectories = new Set([
173 "",
174 ...entries.filter((entry) => entry.kind === "directory").map((entry) => entry.path),
175 ]);
176
177 const refresh = () => {
178 const paths = [...requested.current].filter((path) => reachableDirectories.has(path));
179 for (const path of paths) {
180 if (!active.current) break;
181 void load(path, true);
182 }
183 };
184
185 return {
186 entries,
187 load,
188 refresh,
189 isPending: pending > 0,
190 loadingDirectories,
191 ready: directories.has(""),
192 error: [...errors].find(([path]) => reachableDirectories.has(path))?.[1] ?? null,
193 };
194 }