@devries-cameron20 / t3code-1 / commits / 689763a603
Fork 0

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

fix(mobile): isolate file tree state by workspace (#24270)

Julius Marminge committed Oct 26, 2026 at 22:05 UTC 689763a603a72f38c451f1b9409e187216932386
7 files changed +1222 -111
apps/mobile/src/features/files/FileTreeBrowser.tsx
+20 -30
@@ -32,15 +32,6 @@ function cachedFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<Fil
32 return tree;
33 }
34
35 -function ancestorPaths(path: string): ReadonlyArray<string> {
36 - const parts = path.split("/").filter(Boolean);
37 - const ancestors: string[] = [];
38 - for (let index = 1; index < parts.length; index += 1) {
39 - ancestors.push(parts.slice(0, index).join("/"));
40 - }
41 - return ancestors;
42 -}
43 -
35 const FileTreeRow = function FileTreeRow(props: {
36 readonly item: VisibleFileTreeNode;
37 readonly selected: boolean;
@@ -107,6 +98,11 @@ const FileTreeRow = function FileTreeRow(props: {
98 };
99
100 export function FileTreeBrowser(props: {
101 + readonly revealSelection: (path: string | null) => void;
102 + readonly expandedPaths: ReadonlySet<string>;
103 + readonly setExpandedPaths: (
104 + update: (current: ReadonlySet<string>) => ReadonlySet<string>,
105 + ) => void;
106 readonly entries: ReadonlyArray<ProjectEntry>;
107 readonly error: string | null;
108 readonly isPending: boolean;
@@ -116,12 +112,12 @@ export function FileTreeBrowser(props: {
112 readonly searchTruncated: boolean;
113 readonly selectedPath: string | null;
114 readonly loadingDirectories: ReadonlySet<string>;
119 - readonly onLoadDirectory: (path: string) => void;
115 + readonly onLoadDirectory: (path: string, retry?: boolean) => void;
116 readonly onPreviewFile?: (path: string) => void;
117 readonly onRefresh: () => void;
118 readonly onSelectFile: (path: string) => void;
119 }) {
124 - const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
120 + const { expandedPaths, setExpandedPaths } = props;
121 const [pendingSelection, setPendingSelection] = useState<{
122 readonly path: string;
123 readonly selectedPathAtPress: string | null;
@@ -149,27 +145,21 @@ export function FileTreeBrowser(props: {
145 searchResultPaths: props.searchResultPaths,
146 });
147
148 + const { revealSelection } = props;
149 useEffect(() => {
153 - if (!controlledSelectedPath) {
154 - return;
155 - }
156 - // oxlint-disable-next-line react/set-state-in-effect -- An externally selected file expands its ancestor folders; the user can collapse them afterwards.
157 - setExpandedPaths((current) => {
158 - const ancestors = ancestorPaths(controlledSelectedPath);
159 - if (ancestors.every((ancestor) => current.has(ancestor))) {
160 - return current;
161 - }
162 - const next = new Set(current);
163 - for (const ancestor of ancestors) {
164 - next.add(ancestor);
165 - }
166 - return next;
167 - });
168 - }, [controlledSelectedPath]);
150 + revealSelection(controlledSelectedPath);
151 + }, [controlledSelectedPath, revealSelection]);
152
153 useEffect(() => {
171 - for (const path of expandedPaths) onLoadDirectory(path);
172 - }, [expandedPaths, onLoadDirectory]);
154 + const visit = (nodes: ReadonlyArray<FileTreeNode>) => {
155 + for (const node of nodes) {
156 + if (node.kind !== "directory" || !expandedPaths.has(node.path)) continue;
157 + onLoadDirectory(node.path);
158 + visit(node.children);
159 + }
160 + };
161 + visit(tree);
162 + }, [tree, expandedPaths, onLoadDirectory]);
163
164 useEffect(
165 () => () => {
@@ -181,7 +171,7 @@ export function FileTreeBrowser(props: {
171 );
172
173 const toggleDirectory = (path: string, expand: boolean) => {
184 - if (expand) onLoadDirectory(path);
174 + if (expand) onLoadDirectory(path, true);
175 setExpandedPaths((current) => {
176 const next = new Set(current);
177 if (next.has(path)) {
apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
+21 -6
@@ -452,7 +452,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
452 const { canReadFiles } = fileAccess;
453 const entriesQuery = useFileTreeEntries({
454 environmentId,
455 - cwd: !canReadFiles || hasFileInspector ? null : cwd,
455 + cwd: canReadFiles && !hasFileInspector ? cwd : null,
456 searchQuery,
457 });
458 const handleReturnToThread = () => {
@@ -565,6 +565,9 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
565 <ScreenContent insetHorizontal={layout.usesSplitView}>
566 <FileTreeBrowser
567 key={JSON.stringify([environmentId, cwd])}
568 + revealSelection={entriesQuery.revealSelection}
569 + expandedPaths={entriesQuery.expandedPaths}
570 + setExpandedPaths={entriesQuery.setExpandedPaths}
571 entries={entriesQuery.entries}
572 loadingDirectories={entriesQuery.loadingDirectories}
573 onLoadDirectory={entriesQuery.loadDirectory}
@@ -574,10 +577,13 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
577 searchQuery={searchQuery}
578 searchResultPaths={entriesQuery.searchResultPaths}
579 searchTruncated={entriesQuery.searchTruncated}
577 - selectedPath={null}
580 + selectedPath={entriesQuery.selectedPath}
581 onPreviewFile={handlePreviewFile}
582 onRefresh={entriesQuery.refresh}
580 - onSelectFile={handleSelectFile}
583 + onSelectFile={(path) => {
584 + entriesQuery.selectPath(path);
585 + handleSelectFile(path);
586 + }}
587 />
588 <FilesToolbarBottomFade />
589 </ScreenContent>
@@ -767,7 +773,10 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
773 headerInset={headerInset}
774 projectName={directoryPath ?? projectName}
775 selectedPath={directoryPath === null ? relativePath : null}
770 - onSelectFile={handleSelectFile}
776 + onSelectFile={(path) => {
777 + if (directoryPath !== null) entriesQuery.selectPath(path);
778 + handleSelectFile(path);
779 + }}
780 />
781 ) : undefined;
782 const safeAreaInsets = useSafeAreaInsets();
@@ -945,6 +954,9 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
954 <ScreenContent>
955 <FileTreeBrowser
956 key={JSON.stringify([environmentId, directoryPath])}
957 + revealSelection={entriesQuery.revealSelection}
958 + expandedPaths={entriesQuery.expandedPaths}
959 + setExpandedPaths={entriesQuery.setExpandedPaths}
960 entries={entriesQuery.entries}
961 loadingDirectories={entriesQuery.loadingDirectories}
962 onLoadDirectory={entriesQuery.loadDirectory}
@@ -954,9 +966,12 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
966 searchQuery={searchQuery}
967 searchResultPaths={entriesQuery.searchResultPaths}
968 searchTruncated={entriesQuery.searchTruncated}
957 - selectedPath={null}
969 + selectedPath={entriesQuery.selectedPath}
970 onRefresh={entriesQuery.refresh}
959 - onSelectFile={handleSelectFile}
971 + onSelectFile={(path) => {
972 + entriesQuery.selectPath(path);
973 + handleSelectFile(path);
974 + }}
975 />
976 <FilesToolbarBottomFade />
977 </ScreenContent>
apps/mobile/src/features/files/thread-file-navigator-pane.tsx
+8 -2
@@ -87,6 +87,9 @@ export function ThreadFileNavigatorPane(props: {
87 const fileTree = (
88 <FileTreeBrowser
89 key={JSON.stringify([props.environmentId, props.cwd])}
90 + revealSelection={entriesQuery.revealSelection}
91 + expandedPaths={entriesQuery.expandedPaths}
92 + setExpandedPaths={entriesQuery.setExpandedPaths}
93 entries={entriesQuery.entries}
94 loadingDirectories={entriesQuery.loadingDirectories}
95 onLoadDirectory={entriesQuery.loadDirectory}
@@ -102,10 +105,13 @@ export function ThreadFileNavigatorPane(props: {
105 searchQuery={searchQuery}
106 searchResultPaths={entriesQuery.searchResultPaths}
107 searchTruncated={entriesQuery.searchTruncated}
105 - selectedPath={props.selectedPath}
108 + selectedPath={props.selectedPath ?? entriesQuery.selectedPath}
109 onPreviewFile={handlePreviewFile}
110 onRefresh={entriesQuery.refresh}
108 - onSelectFile={props.onSelectFile}
111 + onSelectFile={(path) => {
112 + entriesQuery.selectPath(path);
113 + props.onSelectFile(path);
114 + }}
115 />
116 );
117
apps/mobile/src/features/files/useFileTreeEntries.test.tsx new
+721
@@ -0,0 +1,721 @@
1 +import {
2 + EnvironmentId,
3 + ProjectListEntriesError,
4 + type ProjectEntry,
5 + type ProjectListEntriesResult,
6 +} from "@t3tools/contracts";
7 +import * as Cause from "effect/Cause";
8 +import * as Option from "effect/Option";
9 +import { AsyncResult } from "effect/reactivity";
10 +import { act, useLayoutEffect, type ReactNode } from "react";
11 +import { createRoot } from "react-dom/client";
12 +import { describe, expect, it, vi } from "vite-plus/test";
13 +
14 +type Query = {
15 + readonly environmentId: EnvironmentId;
16 + readonly input: {
17 + readonly cwd: string;
18 + readonly query?: string;
19 + readonly directoryPath?: string;
20 + };
21 +};
22 +type Result =
23 + | {
24 + readonly _tag: "Success";
25 + readonly value: ProjectListEntriesResult;
26 + readonly timestamp: number;
27 + }
28 + | { readonly _tag: "Failure"; readonly cause: Cause.Cause<Error> };
29 +type QueryState = {
30 + success: AsyncResult.Success<ProjectListEntriesResult, Error> | null;
31 + data: ProjectListEntriesResult;
32 + error: string | null;
33 + failure: ProjectListEntriesError | null;
34 + isPending: boolean;
35 + refresh: () => void;
36 +};
37 +
38 +const rootEntries: ProjectEntry[] = [{ kind: "directory", path: "src" }];
39 +const firstTarget = { cwd: "/first", environmentId: EnvironmentId.make("first") };
40 +
41 +const mocks = vi.hoisted(() => {
42 + const createState = () => ({
43 + requests: [] as {
44 + readonly query: Query;
45 + readonly signal?: AbortSignal;
46 + readonly resolve: (result: Result) => void;
47 + }[],
48 + responseTimestamp: 0,
49 + reconnect: () => {},
50 + rootQuery: null as unknown as QueryState,
51 + searchQuery: null as unknown as QueryState,
52 + results: new WeakMap<
53 + object,
54 + {
55 + data: ProjectListEntriesResult;
56 + error: string | null;
57 + pending: boolean;
58 + result: AsyncResult.AsyncResult<ProjectListEntriesResult, Error>;
59 + }
60 + >(),
61 + });
62 + return { createState, state: createState() };
63 +});
64 +
65 +vi.mock("@t3tools/client-runtime/state/runtime", () => ({
66 + executeAtomQuery: (_registry: unknown, query: Query, options: { signal?: AbortSignal }) =>
67 + new Promise<Result>((resolve) =>
68 + mocks.state.requests.push({ query, signal: options.signal, resolve }),
69 + ),
70 +}));
71 +vi.mock("../../state/atom-registry", () => ({ appAtomRegistry: { refresh: () => {} } }));
72 +vi.mock("../../state/projects", () => ({
73 + projectEnvironment: {
74 + listEntries: (query: Query) => query,
75 + searchEntries: (query: Query) => query,
76 + },
77 +}));
78 +vi.mock("../../connection/catalog", () => ({
79 + environmentCatalog: { sessionGenerationAtom: () => ({}) },
80 +}));
81 +vi.mock("../../state/queries", () => ({ useDebouncedValue: (value: string) => value }));
82 +vi.mock("@effect/atom-react", () => ({
83 + useAtomValue: (atom: Partial<Query>) => {
84 + const state = mocks.state;
85 + const query = atom.input?.query === undefined ? state.rootQuery : state.searchQuery;
86 + if (query.success) return query.success;
87 + const cached = state.results.get(query);
88 + if (
89 + cached &&
90 + cached.data === query.data &&
91 + cached.error === query.error &&
92 + cached.pending === query.isPending
93 + ) {
94 + return cached.result;
95 + }
96 + const result = query.error
97 + ? AsyncResult.fail(query.failure ?? new Error(query.error), {
98 + previousSuccess: Option.some(AsyncResult.success(query.data)),
99 + })
100 + : AsyncResult.success(query.data, {
101 + waiting: query.isPending,
102 + timestamp: ++state.responseTimestamp,
103 + });
104 + state.results.set(query, {
105 + data: query.data,
106 + error: query.error,
107 + pending: query.isPending,
108 + result,
109 + });
110 + return result;
111 + },
112 + useAtomRefresh: () => mocks.state.rootQuery.refresh,
113 + useAtomMount: () => {},
114 + useAtomSubscribe: (_atom: unknown, callback: () => void) => {
115 + mocks.state.reconnect = callback;
116 + },
117 +}));
118 +
119 +const { Children, Nothing } = vi.hoisted(() => ({
120 + Children: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
121 + Nothing: () => null,
122 +}));
123 +vi.mock("react-native", () => ({
124 + Platform: { OS: "ios" },
125 + View: Children,
126 + RefreshControl: Nothing,
127 + Pressable: ({
128 + children,
129 + onPress,
130 + accessibilityLabel,
131 + }: {
132 + children?: ReactNode;
133 + onPress: () => void;
134 + accessibilityLabel?: string;
135 + }) => (
136 + <button aria-label={accessibilityLabel} onClick={onPress}>
137 + {children}
138 + </button>
139 + ),
140 +}));
141 +vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0 }) }));
142 +vi.mock("../../native/NativeScrollViewMarker", () => ({ NativeScrollView: Nothing }));
143 +vi.mock("../../native/native-layout-metrics", () => ({ useNativeColumnLayoutMetrics: () => null }));
144 +vi.mock("@legendapp/list/react-native", () => ({
145 + LegendList: <T,>(props: {
146 + data: ReadonlyArray<T>;
147 + keyExtractor: (item: T) => string;
148 + renderItem: (info: { item: T }) => ReactNode;
149 + ListHeaderComponent?: ReactNode;
150 + ListEmptyComponent?: ReactNode;
151 + }) => (
152 + <div>
153 + {props.ListHeaderComponent}
154 + {props.data.length === 0
155 + ? props.ListEmptyComponent
156 + : props.data.map((item) => (
157 + <div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
158 + ))}
159 + </div>
160 + ),
161 +}));
162 +vi.mock("../../components/ui/Button", () => ({
163 + Button: ({
164 + label,
165 + onPress,
166 + disabled,
167 + }: {
168 + label: string;
169 + onPress: () => void;
170 + disabled?: boolean;
171 + }) => (
172 + <button aria-label={label} disabled={disabled} onClick={onPress}>
173 + {label}
174 + </button>
175 + ),
176 +}));
177 +vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: Nothing }));
178 +vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: Nothing }));
179 +vi.mock("../../components/ui/AppText", () => ({ AppText: Children }));
180 +vi.mock("../../components/PierreEntryIcon", () => ({ PierreEntryIcon: Nothing }));
181 +vi.mock("../../lib/cn", () => ({ cn: () => "" }));
182 +
183 +import { FileTreeBrowser } from "./FileTreeBrowser";
184 +import { useFileTreeEntries } from "./useFileTreeEntries";
185 +
186 +type Hook = typeof useFileTreeEntries;
187 +type Input = Parameters<Hook>[0];
188 +
189 +function setup(withBrowser = false) {
190 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
191 + const state = mocks.createState();
192 + mocks.state = state;
193 + const rootQuery: QueryState = {
194 + success: null,
195 + data: { entries: rootEntries, truncated: false },
196 + error: null,
197 + failure: null,
198 + isPending: false,
199 + refresh: vi.fn(),
200 + };
201 + state.rootQuery = rootQuery;
202 + const searchQuery: QueryState = { ...rootQuery, data: { entries: [], truncated: false } };
203 + state.searchQuery = searchQuery;
204 + const { requests } = state;
205 + const container = document.body.appendChild(document.createElement("div"));
206 + const root = createRoot(container);
207 + let current: ReturnType<Hook>;
208 + let renders = 0;
209 + let controlledSelection: string | undefined;
210 + function Probe(input: Input) {
211 + if (++renders > 100 && withBrowser) throw new Error("File tree did not settle");
212 + const result = useFileTreeEntries(input);
213 + useLayoutEffect(() => {
214 + current = result;
215 + });
216 + return withBrowser ? (
217 + <FileTreeBrowser
218 + key={JSON.stringify([input.environmentId, input.cwd])}
219 + {...result}
220 + selectedPath={controlledSelection ?? result.selectedPath}
221 + searchQuery=""
222 + onLoadDirectory={result.loadDirectory}
223 + onRefresh={result.refresh}
224 + onSelectFile={result.selectPath}
225 + />
226 + ) : null;
227 + }
228 + const unmount = () => {
229 + act(() => root.unmount());
230 + container.remove();
231 + };
232 + return {
233 + requests,
234 + rootQuery,
235 + searchQuery,
236 + get searchSuccess() {
237 + const result = searchQuery.success ?? state.results.get(searchQuery)?.result;
238 + if (result?._tag !== "Success") throw new Error("Search has not succeeded");
239 + return result;
240 + },
241 + get responseTimestamp() {
242 + return state.responseTimestamp;
243 + },
244 + controlSelection(path: string) {
245 + controlledSelection = path;
246 + },
247 + updateView(expanded: string[], selected: string) {
248 + renders = 0;
249 + act(() => {
250 + current.setExpandedPaths(() => new Set(expanded));
251 + current.selectPath(selected);
252 + });
253 + },
254 + unmount,
255 + get current() {
256 + return current;
257 + },
258 + get rows() {
259 + return [...container.querySelectorAll("button")].map((button) =>
260 + button.getAttribute("aria-label"),
261 + );
262 + },
263 + press(label: string) {
264 + renders = 0;
265 + const button = container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
266 + if (!button) throw new Error(`No row labelled ${label}`);
267 + act(() => button.click());
268 + },
269 + render(target: Partial<Input> = {}) {
270 + renders = 0;
271 + const probe = <Probe {...firstTarget} searchQuery="" {...target} />;
272 + act(() => root.render(probe));
273 + },
274 + load(path = "src", refresh = false) {
275 + renders = 0;
276 + act(() => {
277 + void current.loadDirectory(path, refresh);
278 + });
279 + },
280 + async succeed(index: number, entries: ProjectEntry[] = []) {
281 + renders = 0;
282 + await act(async () => {
283 + requests[index]!.resolve({
284 + _tag: "Success",
285 + value: { entries, truncated: false },
286 + timestamp: ++state.responseTimestamp,
287 + });
288 + });
289 + },
290 + async fail(index: number, message = "Directory unavailable") {
291 + renders = 0;
292 + await act(async () => {
293 + requests[index]!.resolve({ _tag: "Failure", cause: Cause.fail(new Error(message)) });
294 + });
295 + },
296 + [Symbol.dispose]: unmount,
297 + };
298 +}
299 +
300 +describe("file tree workspace state", () => {
301 + it("retries failed folders once on reconnect", async () => {
302 + using screen = setup();
303 + screen.render();
304 + screen.load();
305 + await screen.fail(0);
306 + act(() => mocks.state.reconnect());
307 + expect(screen.requests).toHaveLength(2);
308 + act(() => mocks.state.reconnect());
309 + expect(screen.requests).toHaveLength(2);
310 + await screen.succeed(1);
311 + act(() => mocks.state.reconnect());
312 + expect(screen.requests).toHaveLength(2);
313 + });
314 +
315 + it("publishes immutable loading and loaded snapshots", async () => {
316 + using screen = setup();
317 + screen.render();
318 + const initial = screen.current;
319 + screen.load();
320 + const loading = screen.current;
321 + expect(loading.isPending).toBe(true);
322 + expect([...loading.loadingDirectories]).toEqual(["src"]);
323 + expect([...initial.loadingDirectories]).toEqual([]);
324 + await screen.succeed(0, [{ kind: "file", path: "src/first.ts" }]);
325 + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/first.ts"]);
326 + expect([...screen.current.loadedDirectories]).toEqual(["src"]);
327 + expect(screen.current.isPending).toBe(false);
328 + expect([...screen.current.loadingDirectories]).toEqual([]);
329 + expect(loading.entries.map((entry) => entry.path)).toEqual(["src"]);
330 + expect([...loading.loadedDirectories]).toEqual([]);
331 + expect([...loading.loadingDirectories]).toEqual(["src"]);
332 + });
333 +
334 + it.each([{ cwd: "/second" }, { environmentId: EnvironmentId.make("second") }])(
335 + "isolates directory state and restores it on return from %j",
336 + async (target) => {
337 + using screen = setup();
338 + screen.render();
339 + screen.load();
340 + await screen.succeed(0, [{ kind: "file", path: "src/first.ts" }]);
341 +
342 + screen.updateView(["src"], "src/first.ts");
343 + const firstView = screen.current;
344 + screen.render(target);
345 + expect([...screen.current.expandedPaths]).toEqual([]);
346 + expect(screen.current.selectedPath).toBeNull();
347 + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]);
348 + expect([...screen.current.loadedDirectories]).toEqual([]);
349 + expect([...screen.current.loadingDirectories]).toEqual([]);
350 + screen.load();
351 + expect(screen.requests[1]!.query).toEqual({
352 + environmentId: target.environmentId ?? firstTarget.environmentId,
353 + input: { cwd: target.cwd ?? firstTarget.cwd, directoryPath: "src" },
354 + });
355 + await screen.succeed(1, [{ kind: "file", path: "src/second.ts" }]);
356 +
357 + screen.updateView([], "src/second.ts");
358 + expect([...firstView.expandedPaths]).toEqual(["src"]);
359 + expect(firstView.selectedPath).toBe("src/first.ts");
360 + screen.render();
361 + expect([...screen.current.expandedPaths]).toEqual(["src"]);
362 + expect(screen.current.selectedPath).toBe("src/first.ts");
363 + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/first.ts"]);
364 + expect([...screen.current.loadedDirectories]).toEqual(["src"]);
365 + screen.load();
366 + expect(screen.requests).toHaveLength(3);
367 + await screen.succeed(2, [{ kind: "file", path: "src/first.ts" }]);
368 +
369 + screen.render(target);
370 + expect([...screen.current.expandedPaths]).toEqual([]);
371 + expect(screen.current.selectedPath).toBe("src/second.ts");
372 + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/second.ts"]);
373 + expect([...screen.current.loadedDirectories]).toEqual(["src"]);
374 + },
375 + );
376 +
377 + it("ignores stale successes and failures after leaving and returning to a workspace", async () => {
378 + using screen = setup();
379 + screen.render();
380 + screen.load();
381 + screen.load("src/other");
382 + screen.render({ cwd: "/second" });
383 + screen.render();
384 + screen.load();
385 +
386 + await screen.succeed(0, [{ kind: "file", path: "src/stale.ts" }]);
387 + await screen.fail(1, "Stale error");
388 + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]);
389 + expect(screen.current.error).toBeNull();
390 + expect([...screen.current.loadingDirectories]).toEqual(["src"]);
391 + expect(screen.current.isPending).toBe(true);
392 +
393 + await screen.succeed(2, [{ kind: "file", path: "src/current.ts" }]);
394 + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/current.ts"]);
395 + expect(screen.current.error).toBeNull();
396 + expect(screen.current.isPending).toBe(false);
397 + expect([...screen.current.loadingDirectories]).toEqual([]);
398 + });
399 +
400 + it("retains recent listings and expansion when leaving a large workspace", async () => {
401 + using screen = setup();
402 + screen.render();
403 + const paths = Array.from({ length: 70 }, (_, index) => `src/directory-${index}`);
404 + screen.load();
405 + await screen.succeed(
406 + 0,
407 + paths.map((path) => ({ kind: "directory", path })),
408 + );
409 + for (const path of paths) {
410 + screen.load(path);
411 + await screen.succeed(screen.requests.length - 1, [{ kind: "file", path: `${path}/file.ts` }]);
412 + }
413 + screen.updateView(["src", ...paths], `${paths[69]}/file.ts`);
414 + screen.render({ cwd: "/other" });
415 + screen.render();
416 + expect(screen.current.loadedDirectories.size).toBe(64);
417 + expect(screen.current.loadedDirectories.has(paths[69]!)).toBe(true);
418 + expect(screen.current.expandedPaths.size).toBe(71);
419 + expect(screen.current.selectedPath).toBe(`${paths[69]}/file.ts`);
420 + for (let index = 1; index <= 8; index++) screen.render({ cwd: `/workspace-${index}` });
421 + screen.render();
422 + expect(screen.current.loadedDirectories.size).toBe(0);
423 + expect(screen.current.expandedPaths.size).toBe(0);
424 + expect(screen.current.selectedPath).toBeNull();
425 + });
426 +
427 + it("retries a failed folder only when the user expands it again", async () => {
428 + using screen = setup(true);
429 + screen.render();
430 + expect(screen.rows).toEqual(["src"]);
431 + expect(screen.requests).toHaveLength(0);
432 +
433 + screen.press("src");
434 + expect(screen.requests).toHaveLength(1);
435 + await screen.fail(0);
436 + expect(screen.current.error).toBe("Directory unavailable");
437 + // Re-rendering and the browser's passive expansion effect never retry a failed listing.
438 + screen.render();
439 + screen.render();
440 + expect(screen.requests).toHaveLength(1);
441 + expect(screen.rows).toEqual(["src"]);
442 +
443 + screen.press("src");
444 + expect([...screen.current.expandedPaths]).toEqual([]);
445 + expect(screen.requests).toHaveLength(1);
446 + screen.press("src");
447 + expect([...screen.current.expandedPaths]).toEqual(["src"]);
448 + expect(screen.requests).toHaveLength(2);
449 + await screen.succeed(1, [{ kind: "file", path: "src/file.ts" }]);
450 + expect(screen.current.error).toBeNull();
451 + expect(screen.rows).toEqual(["src", "src/file.ts"]);
452 +
453 + // A loaded folder serves from cache on collapse and expand.
454 + screen.press("src");
455 + screen.press("src");
456 + expect(screen.rows).toEqual(["src", "src/file.ts"]);
457 + expect(screen.requests).toHaveLength(2);
458 + });
459 +
460 + it("reveals a controlled leaf-only search result after search clears", () => {
461 + using screen = setup(true);
462 + screen.render();
463 + screen.searchQuery.data = {
464 + entries: [{ kind: "file", path: "src/new/file.ts" }],
465 + truncated: false,
466 + };
467 + screen.controlSelection("src/new/file.ts");
468 + screen.render({ searchQuery: "file" });
469 + expect([...screen.current.expandedPaths]).toEqual(["src", "src/new"]);
470 + screen.render();
471 + expect(screen.current.entries.map((entry) => entry.path)).toContain("src/new/file.ts");
472 + });
473 +
474 + it.each(["collapse", "delete"])("settles controlled selection after %s", async (action) => {
475 + using screen = setup(true);
476 + screen.render();
477 + screen.updateView([], "src/nested/file.ts");
478 + await screen.succeed(0, [{ kind: "directory", path: "src/nested" }]);
479 + expect([...screen.current.expandedPaths]).toEqual(["src", "src/nested"]);
480 + if (action === "collapse") {
481 + screen.updateView([], "src/nested/file.ts");
482 + expect([...screen.current.expandedPaths]).toEqual([]);
483 + screen.render({ cwd: "/second" });
484 + screen.render();
485 + expect([...screen.current.expandedPaths]).toEqual([]);
486 + }
487 + screen.rootQuery.data = { entries: [], truncated: false };
488 + screen.render();
489 + expect([...screen.current.expandedPaths]).toEqual([]);
490 + expect(screen.current.selectedPath).toBeNull();
491 + if (action === "delete") {
492 + screen.controlSelection("src/nested/file.ts");
493 + screen.searchQuery.data = {
494 + entries: [
495 + { kind: "directory", path: "src" },
496 + { kind: "directory", path: "src/nested" },
497 + { kind: "file", path: "src/nested/file.ts" },
498 + ],
499 + truncated: false,
500 + };
501 + screen.rootQuery.failure = new ProjectListEntriesError({
502 + cwd: "/first",
503 + failure: "workspace_root_not_found",
504 + });
505 + screen.rootQuery.error = screen.rootQuery.failure.message;
506 + const requestCount = screen.requests.length;
507 + for (const error of [null, "Search unavailable"]) {
508 + screen.searchQuery.error = error;
509 + screen.render({ searchQuery: "nested" });
510 + expect(screen.current.entries).toEqual([]);
511 + expect([...screen.current.expandedPaths]).toEqual([]);
512 + expect([...screen.current.loadedDirectories]).toEqual([]);
513 + expect(screen.current.isPending).toBe(false);
514 + expect(screen.requests).toHaveLength(requestCount);
515 + }
516 + }
517 + });
518 +
519 + it.each(["return", "missing root"])(
520 + "revalidates retained children after %s without clearing for transient errors",
521 + async (scenario) => {
522 + using screen = setup();
523 + screen.render();
524 + screen.load();
525 + await screen.succeed(0, [{ kind: "file", path: "src/old.ts" }]);
526 + screen.updateView(["src"], "src/old.ts");
527 + screen.render({ cwd: "/second" });
528 + screen.render();
529 + screen.rootQuery.error = "Connection unavailable";
530 + screen.render();
531 + expect(screen.current.selectedPath).toBe("src/old.ts");
532 + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/old.ts"]);
533 + if (scenario === "missing root") {
534 + screen.rootQuery.failure = new ProjectListEntriesError({
535 + cwd: "/first",
536 + failure: "workspace_root_not_found",
537 + });
538 + screen.rootQuery.error = screen.rootQuery.failure.message;
539 + expect(screen.rootQuery.error).toBe("Failed to list workspace entries in '/first'.");
540 + screen.render();
541 + expect(screen.current.selectedPath).toBeNull();
542 + expect([...screen.current.expandedPaths]).toEqual([]);
543 + expect([...screen.current.loadedDirectories]).toEqual([]);
544 + }
545 + screen.rootQuery.error = null;
546 + screen.rootQuery.failure = null;
547 + screen.render();
548 + if (scenario === "missing root") {
549 + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]);
550 + expect(screen.current.selectedPath).toBeNull();
551 + }
552 + screen.load();
553 + expect(screen.requests).toHaveLength(2);
554 + await screen.succeed(1, []);
555 + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]);
556 + expect(screen.current.selectedPath).toBeNull();
557 + },
558 + );
559 +
560 + it.each(["new", "src/new"])(
561 + "keeps search discovery %s until its parent listing revalidates it",
562 + async (path) => {
563 + using screen = setup();
564 + screen.render();
565 + screen.load();
566 + await screen.succeed(0, []);
567 + screen.searchQuery.data = {
568 + entries: [{ kind: "file", path: `${path}/file.ts` }],
569 + truncated: false,
570 + };
571 + screen.render({ searchQuery: "new" });
572 + const expanded = path.includes("/") ? ["src", path] : [path];
573 + screen.updateView(expanded, `${path}/file.ts`);
574 + expect(screen.current.selectedPath).toBe(`${path}/file.ts`);
575 + expect([...screen.current.expandedPaths]).toEqual(expanded);
576 + screen.load(path);
577 + await screen.succeed(1, [
578 + { kind: "file", path: `${path}/file.ts` },
579 + { kind: "file", path: `${path}/other.ts` },
580 + ]);
581 + expect([...screen.current.loadedDirectories]).toEqual(["src", path]);
582 +
583 + const cachedSearch = screen.searchSuccess;
584 + for (const searchQuery of ["", "other"]) {
585 + screen.searchQuery.data = { entries: [], truncated: false };
586 + screen.render({ searchQuery });
587 + expect(screen.current.selectedPath).toBe(`${path}/file.ts`);
588 + expect([...screen.current.expandedPaths]).toEqual(expanded);
589 + expect([...screen.current.loadedDirectories]).toEqual(["src", path]);
590 + expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/file.ts` });
591 + expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/other.ts` });
592 + }
593 +
594 + screen.render();
595 + for (const target of [{ cwd: "/second" }, { environmentId: EnvironmentId.make("second") }]) {
596 + screen.render(target);
597 + screen.render();
598 + expect(screen.current.selectedPath).toBe(`${path}/file.ts`);
599 + expect([...screen.current.expandedPaths]).toEqual(expanded);
600 + expect([...screen.current.loadedDirectories]).toEqual(["src", path]);
601 + expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/other.ts` });
602 + }
603 +
604 + screen.searchQuery.data = {
605 + entries: [{ kind: "file", path: `${path}/file.ts` }],
606 + truncated: false,
607 + };
608 + screen.render({ searchQuery: "new" });
609 + for (const equalContents of [false, true]) {
610 + // A later parent listing wins over retained discovery evidence.
611 + if (path.includes("/")) {
612 + // Refresh re-lists the root and every reachable folder; the empty parent prunes the child.
613 + const refreshed = screen.requests.length;
614 + act(() => {
615 + void screen.current.refresh();
616 + });
617 + expect(screen.requests.slice(refreshed).map((request) => request.query.input)).toEqual([
618 + { cwd: "/first", directoryPath: "" },
619 + { cwd: "/first", query: "new", limit: 200 },
620 + { cwd: "/first", directoryPath: "src" },
621 + { cwd: "/first", directoryPath: path },
622 + ]);
623 + // The parent settles last so its listing carries the newest response timestamp.
624 + for (const index of [refreshed, refreshed + 1, refreshed + 3, refreshed + 2]) {
625 + await screen.succeed(index, []);
626 + }
627 + } else {
628 + const cachedData = screen.rootQuery.data;
629 + screen.rootQuery.isPending = true;
630 + screen.render({ searchQuery: "new" });
631 + expect(screen.current.selectedPath).toBe(`${path}/file.ts`);
632 + screen.rootQuery.isPending = false;
633 + expect(screen.rootQuery.data).toBe(cachedData);
634 + screen.render({ searchQuery: "new" });
635 + }
636 + expect(screen.current.selectedPath).toBeNull();
637 + expect([...screen.current.expandedPaths]).toEqual(path.includes("/") ? ["src"] : []);
638 + expect([...screen.current.loadedDirectories]).toEqual(["src"]);
639 +
640 + // Cover an older cache and the timestamp's ambiguous same-millisecond boundary.
641 + for (const success of [
642 + cachedSearch,
643 + AsyncResult.success(cachedSearch.value, { timestamp: screen.responseTimestamp }),
644 + ]) {
645 + screen.searchQuery.data = { entries: [], truncated: false };
646 + screen.render({ searchQuery: "other" });
647 + screen.searchQuery.success = success;
648 + screen.searchQuery.data = success.value;
649 + screen.render({ searchQuery: "new" });
650 + screen.updateView(expanded, `${path}/file.ts`);
651 + const requestCount = screen.requests.length;
652 + screen.load(path);
653 + expect(screen.requests).toHaveLength(requestCount + 1);
654 + await screen.fail(requestCount);
655 + screen.searchQuery.success = null;
656 + screen.render();
657 + expect(screen.current.selectedPath).toBeNull();
658 + expect([...screen.current.expandedPaths]).toEqual(path.includes("/") ? ["src"] : []);
659 + expect([...screen.current.loadedDirectories]).toEqual(["src"]);
660 + expect(
661 + screen.current.entries.some(
662 + (entry) => entry.path === path || entry.path.startsWith(`${path}/`),
663 + ),
664 + ).toBe(false);
665 + }
666 +
667 + const cachedSearchData = screen.searchQuery.data;
668 + screen.searchQuery.isPending = true;
669 + screen.render({ searchQuery: "new" });
670 + expect(screen.current.selectedPath).toBeNull();
671 + expect([...screen.current.loadedDirectories]).toEqual(["src"]);
672 + screen.searchQuery.isPending = false;
673 + if (!equalContents) {
674 + screen.searchQuery.data = {
675 + ...cachedSearchData,
676 + entries: [...cachedSearchData.entries, { kind: "file", path: `${path}/added.ts` }],
677 + };
678 + }
679 + expect(screen.searchQuery.data === cachedSearchData).toBe(equalContents);
680 + screen.render({ searchQuery: "new" });
681 + screen.updateView(expanded, `${path}/file.ts`);
682 + screen.load(path);
683 + await screen.succeed(screen.requests.length - 1, [
684 + { kind: "file", path: `${path}/file.ts` },
685 + { kind: "file", path: `${path}/recreated.ts` },
686 + ]);
687 + expect(screen.current.selectedPath).toBe(`${path}/file.ts`);
688 + expect([...screen.current.expandedPaths]).toEqual(expanded);
689 + expect([...screen.current.loadedDirectories]).toEqual(["src", path]);
690 + expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/file.ts` });
691 + expect(screen.current.entries).toContainEqual({
692 + kind: "file",
693 + path: `${path}/recreated.ts`,
694 + });
695 + }
696 + },
697 + );
698 +
699 + it("prunes deleted directory contents, expansion and selection after a fresh parent listing", async () => {
700 + using screen = setup();
701 + screen.render();
702 + screen.load();
703 + await screen.succeed(0, [{ kind: "directory", path: "src/nested" }]);
704 + screen.load("src/nested");
705 + await screen.succeed(1, [{ kind: "file", path: "src/nested/file.ts" }]);
706 + screen.updateView(["src", "src/nested"], "src/nested/file.ts");
707 + screen.rootQuery.data = { entries: [], truncated: true };
708 + screen.render();
709 + expect([...screen.current.loadedDirectories]).toEqual(["src", "src/nested"]);
710 + expect(screen.current.selectedPath).toBe("src/nested/file.ts");
711 + screen.rootQuery.data = { entries: [], truncated: false };
712 + screen.render();
713 + expect(screen.current.entries).toEqual([]);
714 + expect([...screen.current.loadedDirectories]).toEqual([]);
715 + expect([...screen.current.expandedPaths]).toEqual([]);
716 + expect(screen.current.selectedPath).toBeNull();
717 + screen.rootQuery.data = { entries: rootEntries, truncated: false };
718 + screen.render();
719 + expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]);
720 + });
721 +});
apps/mobile/src/features/files/useFileTreeEntries.ts
+446 -73
@@ -1,9 +1,9 @@
1 import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
2 import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
3 -import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
3 +import { ProjectListEntriesError, type EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
4 import * as Cause from "effect/Cause";
5 +import { useCallback, useLayoutEffect, useRef, useState } from "react";
6 import { Atom } from "effect/reactivity";
6 -import { useEffect, useReducer, useRef, useState } from "react";
7
8 import { environmentCatalog } from "../../connection/catalog";
9 import { appAtomRegistry } from "../../state/atom-registry";
@@ -11,6 +11,92 @@ import { projectEnvironment } from "../../state/projects";
11 import { useDebouncedValue } from "../../state/queries";
12 import { useEnvironmentQuery } from "../../state/query";
13
14 +function createDirectories() {
15 + return {
16 + target: {},
17 + entries: new Map<string, ReadonlyArray<ProjectEntry>>(),
18 + errors: new Map<string, string>(),
19 + completeDirectories: new Set<string>(),
20 + listingCompletedAt: new Map<string, number>(),
21 + discoveries: new Map<string, ProjectEntry>(),
22 + rootListing: null as { readonly timestamp: number } | null,
23 + validatedDirectories: new Set<string>(),
24 + loading: new Set<string>(),
25 + expandedPaths: new Set<string>(),
26 + selectedPath: null as string | null,
27 + revealedSelection: { path: null as string | null, ancestors: new Set<string>() },
28 + isRefreshing: false,
29 + };
30 +}
31 +
32 +function boundDirectories(current: ReturnType<typeof createDirectories>, preserveVisible = true) {
33 + const visible = (path: string) => {
34 + const parts = path.split("/");
35 + return parts.every((_, index) =>
36 + current.expandedPaths.has(parts.slice(0, index + 1).join("/")),
37 + );
38 + };
39 + const inactive = [...new Set([...current.entries.keys(), ...current.errors.keys()])].filter(
40 + (path) => !preserveVisible || !visible(path),
41 + );
42 + const ownedPaths = [
43 + ...current.entries.keys(),
44 + ...current.expandedPaths,
45 + current.selectedPath,
46 + ].filter((path) => path !== null);
47 + const discoveries = new Map(
48 + [...current.discoveries].filter(([path]) =>
49 + ownedPaths.some((owned) => owned === path || owned.startsWith(`${path}/`)),
50 + ),
51 + );
52 + if (inactive.length <= 64)
53 + return discoveries.size === current.discoveries.size ? current : { ...current, discoveries };
54 + const evicted = new Set(inactive.slice(0, -64));
55 + // Evict listing data, not the user's expansion and selection. A missing parent reloads on return.
56 + return {
57 + ...current,
58 + discoveries,
59 + entries: new Map([...current.entries].filter(([path]) => !evicted.has(path))),
60 + errors: new Map([...current.errors].filter(([path]) => !evicted.has(path))),
61 + completeDirectories: new Set(
62 + [...current.completeDirectories].filter((path) => !evicted.has(path)),
63 + ),
64 + validatedDirectories: new Set(
65 + [...current.validatedDirectories].filter((path) => !evicted.has(path)),
66 + ),
67 + listingCompletedAt: new Map(
68 + [...current.listingCompletedAt].filter(([path]) => !evicted.has(path)),
69 + ),
70 + };
71 +}
72 +
73 +function contradictsListing(path: string, parent: string, entries: ReadonlyArray<ProjectEntry>) {
74 + if (parent !== "" && !path.startsWith(`${parent}/`)) return false;
75 + const child = path.slice(parent === "" ? 0 : parent.length + 1).split("/")[0];
76 + const childPath = parent === "" ? child : `${parent}/${child}`;
77 + const entry = entries.find((item) => item.path === childPath);
78 + return !entry || (path !== childPath && entry.kind !== "directory");
79 +}
80 +
81 +function createRequests() {
82 + return {
83 + active: true,
84 + refreshVersion: 0,
85 + pending: new Map<string, AbortController>(),
86 + };
87 +}
88 +
89 +function getRequests(
90 + requestsByTarget: WeakMap<object, ReturnType<typeof createRequests>>,
91 + target: object,
92 +) {
93 + let requests = requestsByTarget.get(target);
94 + if (!requests) {
95 + requests = createRequests();
96 + requestsByTarget.set(target, requests);
97 + }
98 + return requests;
99 +}
100 const noSessionGeneration = Atom.make(0);
101
102 export function useFileTreeEntries(input: {
@@ -27,6 +113,7 @@ export function useFileTreeEntries(input: {
113 ? projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath: "" } })
114 : null,
115 );
116 + const { refresh: refreshRoot } = root;
117 const search = useEnvironmentQuery(
118 searching && debouncedQuery.length > 0 && cwd !== null && environmentId !== null
119 ? projectEnvironment.searchEntries({
@@ -35,42 +122,102 @@ export function useFileTreeEntries(input: {
122 })
123 : null,
124 );
38 - const [, render] = useReducer((value: number) => value + 1, 0);
39 - const [entriesRevision, entriesChanged] = useReducer((value: number) => value + 1, 0);
40 - const refreshVersion = useRef(0);
41 - const directories = {
42 - cwd,
43 - environmentId,
44 - entries: new Map<string, ReadonlyArray<ProjectEntry>>(),
45 - requested: new Set<string>(),
46 - pending: new Map<string, AbortController>(),
47 - errors: new Map<string, string>(),
48 - };
49 - const [refreshingDirectories, setRefreshingDirectories] = useState<typeof directories | null>(
50 - null,
51 - );
52 - useEffect(
53 - () => () => {
54 - refreshVersion.current++;
55 - for (const controller of directories.pending.values()) controller.abort();
56 - directories.pending.clear();
57 - },
58 - [directories],
125 + const workspaceKey = JSON.stringify([environmentId, cwd]);
126 + const [cache, setCache] = useState(() => ({
127 + key: workspaceKey,
128 + workspaces: new Map([[workspaceKey, createDirectories()]]),
129 + }));
130 + const savedDirectories = cache.workspaces.get(workspaceKey) ?? createDirectories();
131 + // Requests belong to a visit, so returning cannot revive an old completion.
132 + const directories =
133 + cache.key === workspaceKey
134 + ? savedDirectories
135 + : {
136 + ...savedDirectories,
137 + target: {},
138 + validatedDirectories: new Set<string>(),
139 + errors: new Map<string, string>(),
140 + loading: new Set<string>(),
141 + isRefreshing: false,
142 + };
143 + if (cache.key !== workspaceKey) {
144 + const workspaces = new Map(cache.workspaces);
145 + const previous = workspaces.get(cache.key);
146 + if (previous) {
147 + workspaces.set(
148 + cache.key,
149 + boundDirectories(
150 + {
151 + ...previous,
152 + errors: new Map(),
153 + loading: new Set(),
154 + isRefreshing: false,
155 + },
156 + false,
157 + ),
158 + );
159 + }
160 + workspaces.delete(workspaceKey);
161 + workspaces.set(workspaceKey, directories);
162 + if (workspaces.size > 8) workspaces.delete(workspaces.keys().next().value!);
163 + setCache({ key: workspaceKey, workspaces });
164 + }
165 + const setDirectories = useCallback(
166 + (
167 + update: (
168 + current: ReturnType<typeof createDirectories>,
169 + ) => ReturnType<typeof createDirectories>,
170 + ) =>
171 + setCache((current) => {
172 + const previous = current.workspaces.get(workspaceKey);
173 + if (!previous) return current;
174 + const next = boundDirectories(update(previous));
175 + if (next === previous) return current;
176 + return { ...current, workspaces: new Map(current.workspaces).set(workspaceKey, next) };
177 + }),
178 + [workspaceKey],
179 );
180 + const { target } = directories;
181 + const requestsByTarget = useRef(new WeakMap<object, ReturnType<typeof createRequests>>());
182 + // Cancel the old target before consumers' passive effects start new directory loads.
183 + useLayoutEffect(() => {
184 + const requests = getRequests(requestsByTarget.current, target);
185 + requests.active = true;
186 + refreshRoot();
187 + return () => {
188 + requests.active = false;
189 + requests.refreshVersion++;
190 + for (const controller of requests.pending.values()) controller.abort();
191 + requests.pending.clear();
192 + setDirectories((current) =>
193 + current.target === target
194 + ? { ...current, loading: new Set(), isRefreshing: false }
195 + : current,
196 + );
197 + };
198 + }, [target, setDirectories, requestsByTarget, refreshRoot]);
199 + const updateDirectories = (
200 + update: (current: ReturnType<typeof createDirectories>) => ReturnType<typeof createDirectories>,
201 + ) => setDirectories((current) => (current.target === target ? update(current) : current));
202 const loadDirectory = (directoryPath: string, refresh = false) => {
203 + const requests = getRequests(requestsByTarget.current, target);
204 if (
205 + !requests.active ||
206 + missingRoot ||
207 cwd === null ||
208 environmentId === null ||
64 - (!refresh && directories.entries.has(directoryPath)) ||
65 - directories.pending.has(directoryPath)
209 + (!refresh && directories.validatedDirectories.has(directoryPath)) ||
210 + requests.pending.has(directoryPath)
211 ) {
212 return;
213 }
214 const controller = new AbortController();
70 - directories.requested.add(directoryPath);
71 - directories.pending.set(directoryPath, controller);
72 - directories.errors.delete(directoryPath);
73 - render();
215 + requests.pending.set(directoryPath, controller);
216 + updateDirectories((current) => {
217 + const errors = new Map(current.errors);
218 + errors.delete(directoryPath);
219 + return { ...current, errors, loading: new Set(current.loading).add(directoryPath) };
220 + });
221 const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
222 appAtomRegistry.refresh(atom);
223 return executeAtomQuery(appAtomRegistry, atom, {
@@ -79,26 +226,73 @@ export function useFileTreeEntries(input: {
226 reportDefect: false,
227 }).then((result) => {
228 if (controller.signal.aborted) return;
82 - directories.pending.delete(directoryPath);
83 - if (result._tag === "Success") {
84 - directories.entries.set(
85 - directoryPath,
86 - result.value.entries.filter(
87 - (entry) =>
88 - entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
89 - ),
90 - );
91 - entriesChanged();
92 - } else {
229 + requests.pending.delete(directoryPath);
230 + updateDirectories((current) => {
231 + const validatedDirectories = new Set(current.validatedDirectories).add(directoryPath);
232 + const loading = new Set(current.loading);
233 + loading.delete(directoryPath);
234 + if (result._tag === "Success") {
235 + const entries = new Map(current.entries);
236 + entries.delete(directoryPath);
237 + entries.set(
238 + directoryPath,
239 + result.value.entries.filter(
240 + (entry) =>
241 + entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
242 + ),
243 + );
244 + const completeDirectories = new Set(current.completeDirectories);
245 + if (result.value.truncated) completeDirectories.delete(directoryPath);
246 + else completeDirectories.add(directoryPath);
247 + return {
248 + ...current,
249 + entries,
250 + loading,
251 + completeDirectories,
252 + discoveries: result.value.truncated
253 + ? current.discoveries
254 + : new Map(
255 + [...current.discoveries].filter(
256 + ([path]) => !contradictsListing(path, directoryPath, result.value.entries),
257 + ),
258 + ),
259 + validatedDirectories,
260 + listingCompletedAt: new Map(current.listingCompletedAt).set(
261 + directoryPath,
262 + result.timestamp,
263 + ),
264 + };
265 + }
266 const error = Cause.squash(result.cause);
94 - directories.errors.set(
95 - directoryPath,
96 - error instanceof Error ? error.message : "Files unavailable",
97 - );
98 - }
99 - render();
267 + return {
268 + ...current,
269 + loading,
270 + validatedDirectories,
271 + errors: new Map(current.errors).set(
272 + directoryPath,
273 + error instanceof Error ? error.message : "Files unavailable",
274 + ),
275 + };
276 + });
277 });
278 };
279 + const missingRoot =
280 + root.failure instanceof ProjectListEntriesError &&
281 + root.failure.failure === "workspace_root_not_found";
282 + const rootData = missingRoot ? null : root.data;
283 + const rootListing = root.successResult ?? directories.rootListing;
284 + if (
285 + missingRoot &&
286 + (directories.entries.size > 0 ||
287 + directories.errors.size > 0 ||
288 + directories.loading.size > 0 ||
289 + directories.expandedPaths.size > 0 ||
290 + directories.selectedPath !== null ||
291 + directories.discoveries.size > 0)
292 + ) {
293 + setDirectories(() => createDirectories());
294 + }
295 + const { refresh: refreshSearch, data: searchData, successResult: searchResult } = search;
296 // A folder read fails at once while its environment is unreachable; read it again once a new
297 // session is up rather than leaving the error until someone refreshes.
298 const sessionGeneration =
@@ -108,13 +302,11 @@ export function useFileTreeEntries(input: {
302 // A listener alone does not compute the atom, so nothing would follow the connection.
303 useAtomMount(sessionGeneration);
304 useAtomSubscribe(sessionGeneration, () => {
111 - for (const path of directories.errors.keys()) void loadDirectory(path);
305 + for (const path of directories.errors.keys()) void loadDirectory(path, true);
306 });
113 - const { refresh: refreshRoot, data: rootData } = root;
114 - const { refresh: refreshSearch, data: searchData } = search;
307 const snapshot = (() => {
116 - const merged = new Map<string, ProjectEntry>();
117 - if (searching) {
308 + const merged = new Map(missingRoot ? [] : directories.discoveries);
309 + if (searching && !missingRoot) {
310 for (const entry of searchData?.entries ?? []) merged.set(entry.path, entry);
311 }
312 const reachableDirectories = new Set<string>();
@@ -127,31 +319,158 @@ export function useFileTreeEntries(input: {
319 }
320 }
321 };
322 + if (!missingRoot) {
323 + const discoveries = new Map(directories.discoveries);
324 + // Search can return only leaves; their inferred parents still own loaded children.
325 + for (const entry of directories.discoveries.values()) {
326 + const parts = entry.path.split("/");
327 + for (let index = 1; index < parts.length; index++) {
328 + const path = parts.slice(0, index).join("/");
329 + if (!discoveries.has(path)) discoveries.set(path, { kind: "directory", path });
330 + }
331 + }
332 + visit([...discoveries.values()]);
333 + }
334 visit((rootData?.entries ?? []).filter((entry) => !entry.path.includes("/")));
335 return {
132 - revision: entriesRevision,
336 entries: [...merged.values()],
337 reachableDirectories,
135 - searchResultPaths: searching
136 - ? new Set((searchData?.entries ?? []).map((entry) => entry.path))
137 - : null,
338 + searchResultPaths:
339 + searching && !missingRoot
340 + ? new Set((searchData?.entries ?? []).map((entry) => entry.path))
341 + : null,
342 };
343 })();
344
345 + if (rootData) {
346 + const deleted = (path: string, directory = false) => {
347 + const parts = path.split("/");
348 + for (let index = 0; index < parts.length; index++) {
349 + const parent = parts.slice(0, index).join("/");
350 + const listing = index === 0 ? rootData.entries : directories.entries.get(parent);
351 + const child = parts.slice(0, index + 1).join("/");
352 + const complete =
353 + index === 0 ? !rootData.truncated : directories.completeDirectories.has(parent);
354 + const entry = listing?.find((item) => item.path === child);
355 + if (complete && listing && !entry) {
356 + const listingCompletedAt =
357 + index === 0 && directories.rootListing !== rootListing
358 + ? rootListing?.timestamp
359 + : directories.listingCompletedAt.get(parent);
360 + // Cached queries keep their completion time across query switches.
361 + // Equal-millisecond responses cannot prove a path postdates the listing.
362 + const retained =
363 + !(index === 0 && directories.rootListing !== rootListing) &&
364 + [...directories.discoveries.keys()].some(
365 + (path) => path === child || path.startsWith(`${child}/`),
366 + );
367 + const discovered =
368 + retained ||
369 + (searching &&
370 + query === debouncedQuery &&
371 + searchResult !== null &&
372 + searchResult.timestamp > (listingCompletedAt ?? -Infinity) &&
373 + searchData?.entries.some(
374 + (item) => item.path === child || item.path.startsWith(`${child}/`),
375 + ));
376 + if (!discovered) return true;
377 + }
378 + if (entry && (directory || index < parts.length - 1) && entry.kind !== "directory")
379 + return true;
380 + }
381 + return false;
382 + };
383 + const reconciled = (() => {
384 + const current = directories;
385 + const discoveries = new Map(current.discoveries);
386 + if (current.rootListing !== rootListing && !rootData.truncated) {
387 + for (const path of discoveries.keys()) {
388 + if (contradictsListing(path, "", rootData.entries)) discoveries.delete(path);
389 + }
390 + }
391 + if (searching && query === debouncedQuery && searchResult !== null) {
392 + const ownedPaths = [
393 + ...current.entries.keys(),
394 + ...current.expandedPaths,
395 + current.selectedPath,
396 + ];
397 + for (const entry of searchData?.entries ?? []) {
398 + if (
399 + ownedPaths.some((path) => path === entry.path || path?.startsWith(`${entry.path}/`)) &&
400 + !deleted(entry.path, entry.kind === "directory")
401 + )
402 + discoveries.set(entry.path, entry);
403 + }
404 + }
405 + const entries = new Map([...current.entries].filter(([path]) => !deleted(path, true)));
406 + const errors = new Map([...current.errors].filter(([path]) => !deleted(path, true)));
407 + const expandedPaths = new Set(
408 + [...current.expandedPaths].filter((path) => !deleted(path, true)),
409 + );
410 + const selectedPath =
411 + current.selectedPath !== null && deleted(current.selectedPath)
412 + ? null
413 + : current.selectedPath;
414 + if (
415 + entries.size === current.entries.size &&
416 + errors.size === current.errors.size &&
417 + expandedPaths.size === current.expandedPaths.size &&
418 + selectedPath === current.selectedPath &&
419 + current.rootListing === rootListing &&
420 + discoveries.size === current.discoveries.size &&
421 + [...discoveries].every(([path, entry]) => current.discoveries.get(path) === entry)
422 + )
423 + return current;
424 + const completeDirectories = new Set(
425 + [...current.completeDirectories].filter((path) => entries.has(path)),
426 + );
427 + return {
428 + ...current,
429 + rootListing,
430 + discoveries,
431 + listingCompletedAt: new Map(
432 + [...current.listingCompletedAt].filter(([path]) => path === "" || entries.has(path)),
433 + ).set(
434 + "",
435 + current.rootListing === rootListing
436 + ? (current.listingCompletedAt.get("") ?? -Infinity)
437 + : (rootListing?.timestamp ?? -Infinity),
438 + ),
439 + entries,
440 + errors,
441 + expandedPaths,
442 + selectedPath,
443 + completeDirectories,
444 + validatedDirectories: new Set(
445 + [...current.validatedDirectories].filter((path) => !deleted(path, true)),
446 + ),
447 + };
448 + })();
449 + if (reconciled !== directories) setDirectories(() => reconciled);
450 + }
451 +
452 const refresh = () => {
453 + const requests = getRequests(requestsByTarget.current, target);
454 + if (!requests.active) return Promise.resolve();
455 refreshRoot();
143 - if (searching) refreshSearch();
456 + if (searching && !missingRoot) refreshSearch();
457 const paths = new Set(
145 - [...directories.requested].filter((path) => snapshot.reachableDirectories.has(path)),
458 + [...directories.entries.keys(), ...directories.errors.keys(), ...directories.loading].filter(
459 + (path) => snapshot.reachableDirectories.has(path),
460 + ),
461 );
147 - for (const controller of directories.pending.values()) controller.abort();
148 - directories.pending.clear();
149 - directories.errors.clear();
150 - const version = ++refreshVersion.current;
151 - setRefreshingDirectories(directories);
462 + for (const controller of requests.pending.values()) controller.abort();
463 + requests.pending.clear();
464 + const version = ++requests.refreshVersion;
465 + updateDirectories((current) => ({
466 + ...current,
467 + errors: new Map(),
468 + loading: new Set(),
469 + isRefreshing: true,
470 + }));
471 const remaining = paths.values();
472 const worker = async () => {
154 - while (version === refreshVersion.current) {
473 + while (requests.active && version === requests.refreshVersion) {
474 const next = remaining.next();
475 if (next.done) return;
476 await loadDirectory(next.value, true);
@@ -161,7 +480,7 @@ export function useFileTreeEntries(input: {
480 cwd !== null && environmentId !== null
481 ? [
482 projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath: "" } }),
164 - ...(searching
483 + ...(searching && !missingRoot
484 ? [
485 projectEnvironment.searchEntries({
486 environmentId,
@@ -177,29 +496,83 @@ export function useFileTreeEntries(input: {
496 ),
497 ...Array.from({ length: Math.min(4, paths.size) }, () => worker()),
498 ];
180 - render();
499 return Promise.all(work).finally(() => {
182 - if (version === refreshVersion.current) setRefreshingDirectories(null);
500 + if (version === requests.refreshVersion) {
501 + updateDirectories((current) => ({ ...current, isRefreshing: false }));
502 + }
503 });
504 };
505
506 + const revealSelection = (path: string | null) => {
507 + if (missingRoot) return;
508 + updateDirectories((current) => {
509 + const previous = current.revealedSelection;
510 + const handled = previous.path === path ? previous.ancestors : new Set<string>();
511 + const parts = path?.split("/").filter(Boolean) ?? [];
512 + const ancestors = parts
513 + .slice(1)
514 + .map((_, index) => parts.slice(0, index + 1).join("/"))
515 + .filter(
516 + (ancestor) =>
517 + !handled.has(ancestor) &&
518 + snapshot.entries.some(
519 + (entry) =>
520 + (entry.kind === "directory" && entry.path === ancestor) ||
521 + (entry.path === path && entry.path.startsWith(`${ancestor}/`)),
522 + ),
523 + );
524 + if (previous.path === path && ancestors.length === 0) return current;
525 + return {
526 + ...current,
527 + discoveries: new Map([
528 + ...current.discoveries,
529 + ...snapshot.entries
530 + .filter((entry) => entry.path === path)
531 + .map((entry) => [entry.path, entry] as const),
532 + ]),
533 + selectedPath: path,
534 + revealedSelection: { path, ancestors: new Set([...handled, ...ancestors]) },
535 + expandedPaths: new Set([...current.expandedPaths, ...ancestors]),
536 + };
537 + });
538 + };
539 +
540 + const setExpandedPaths = useCallback(
541 + (update: (current: ReadonlySet<string>) => ReadonlySet<string>) =>
542 + setDirectories((current) => {
543 + const expandedPaths = update(current.expandedPaths);
544 + return expandedPaths === current.expandedPaths
545 + ? current
546 + : { ...current, expandedPaths: new Set(expandedPaths) };
547 + }),
548 + [setDirectories],
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,
189 - isRefreshing: refreshingDirectories === directories,
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:
196 - root.isPending ||
197 - directories.pending.size > 0 ||
198 - (searching && (query !== debouncedQuery || search.isPending)),
199 - searchTruncated: searching && (search.data?.truncated ?? false),
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()),
201 - loadingDirectories: new Set(directories.pending.keys()),
202 - loadDirectory,
573 + loadingDirectories: directories.loading,
574 + loadDirectory: (path: string, retry = false) =>
575 + loadDirectory(path, retry && directories.errors.has(path)),
576 refresh,
577 };
578 }
apps/mobile/src/state/query.ts
+5
@@ -9,7 +9,9 @@ const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(fals
9
10 export interface EnvironmentQueryView<A> {
11 readonly data: A | null;
12 + readonly successResult: AsyncResult.Success<A, unknown> | null;
13 readonly error: string | null;
14 + readonly failure: unknown;
15 readonly isPending: boolean;
16 readonly isSuccess: boolean;
17 readonly refresh: () => void;
@@ -30,6 +32,9 @@ export function useEnvironmentQuery<A, E>(
32 const refresh = useAtomRefresh(selectedAtom);
33 return {
34 data: Option.getOrNull(AsyncResult.value(result)),
35 + // Data may be structurally shared; only a settled success proves a new response.
36 + successResult: result._tag === "Success" && !result.waiting ? result : null,
37 + failure: result._tag === "Failure" ? Cause.squash(result.cause) : null,
38 error: result._tag === "Failure" ? formatError(result.cause) : null,
39 isPending: atom !== null && result.waiting,
40 isSuccess: result._tag === "Success",
apps/mobile/vite.config.ts
+1
@@ -4,6 +4,7 @@ import { defineConfig, normalizePath } from "vite-plus";
4 import "vite-plus/test/config";
5
6 const reactTests = [
7 + "src/features/files/useFileTreeEntries.test.tsx",
8 "src/features/projects/AddProjectScreen.test.ts",
9 "src/lib/useMediaVideoPlayback.test.tsx",
10 "src/features/pull-requests/usePullRequestEnvironmentFallback.test.tsx",