Skip to content
TypeScript

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

Julius Marminge689763a603a7
diff --git a/apps/mobile/src/features/files/FileTreeBrowser.tsx b/apps/mobile/src/features/files/FileTreeBrowser.tsx
index c08f21ad498..93e238822c4 100644
--- a/apps/mobile/src/features/files/FileTreeBrowser.tsx
+++ b/apps/mobile/src/features/files/FileTreeBrowser.tsx
@@ -32,15 +32,6 @@ function cachedFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<Fil
return tree;
}
-function ancestorPaths(path: string): ReadonlyArray<string> {
- const parts = path.split("/").filter(Boolean);
- const ancestors: string[] = [];
- for (let index = 1; index < parts.length; index += 1) {
- ancestors.push(parts.slice(0, index).join("/"));
- }
- return ancestors;
-}
-
const FileTreeRow = function FileTreeRow(props: {
readonly item: VisibleFileTreeNode;
readonly selected: boolean;
@@ -107,6 +98,11 @@ const FileTreeRow = function FileTreeRow(props: {
};
export function FileTreeBrowser(props: {
+ readonly revealSelection: (path: string | null) => void;
+ readonly expandedPaths: ReadonlySet<string>;
+ readonly setExpandedPaths: (
+ update: (current: ReadonlySet<string>) => ReadonlySet<string>,
+ ) => void;
readonly entries: ReadonlyArray<ProjectEntry>;
readonly error: string | null;
readonly isPending: boolean;
@@ -116,12 +112,12 @@ export function FileTreeBrowser(props: {
readonly searchTruncated: boolean;
readonly selectedPath: string | null;
readonly loadingDirectories: ReadonlySet<string>;
- readonly onLoadDirectory: (path: string) => void;
+ readonly onLoadDirectory: (path: string, retry?: boolean) => void;
readonly onPreviewFile?: (path: string) => void;
readonly onRefresh: () => void;
readonly onSelectFile: (path: string) => void;
}) {
- const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
+ const { expandedPaths, setExpandedPaths } = props;
const [pendingSelection, setPendingSelection] = useState<{
readonly path: string;
readonly selectedPathAtPress: string | null;
@@ -149,27 +145,21 @@ export function FileTreeBrowser(props: {
searchResultPaths: props.searchResultPaths,
});
+ const { revealSelection } = props;
useEffect(() => {
- if (!controlledSelectedPath) {
- return;
- }
- // oxlint-disable-next-line react/set-state-in-effect -- An externally selected file expands its ancestor folders; the user can collapse them afterwards.
- setExpandedPaths((current) => {
- const ancestors = ancestorPaths(controlledSelectedPath);
- if (ancestors.every((ancestor) => current.has(ancestor))) {
- return current;
- }
- const next = new Set(current);
- for (const ancestor of ancestors) {
- next.add(ancestor);
- }
- return next;
- });
- }, [controlledSelectedPath]);
+ revealSelection(controlledSelectedPath);
+ }, [controlledSelectedPath, revealSelection]);
useEffect(() => {
- for (const path of expandedPaths) onLoadDirectory(path);
- }, [expandedPaths, onLoadDirectory]);
+ const visit = (nodes: ReadonlyArray<FileTreeNode>) => {
+ for (const node of nodes) {
+ if (node.kind !== "directory" || !expandedPaths.has(node.path)) continue;
+ onLoadDirectory(node.path);
+ visit(node.children);
+ }
+ };
+ visit(tree);
+ }, [tree, expandedPaths, onLoadDirectory]);
useEffect(
() => () => {
@@ -181,7 +171,7 @@ export function FileTreeBrowser(props: {
);
const toggleDirectory = (path: string, expand: boolean) => {
- if (expand) onLoadDirectory(path);
+ if (expand) onLoadDirectory(path, true);
setExpandedPaths((current) => {
const next = new Set(current);
if (next.has(path)) {
diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
index 3f2255a56b1..e1b4ac2a26d 100644
--- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
+++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
@@ -452,7 +452,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
const { canReadFiles } = fileAccess;
const entriesQuery = useFileTreeEntries({
environmentId,
- cwd: !canReadFiles || hasFileInspector ? null : cwd,
+ cwd: canReadFiles && !hasFileInspector ? cwd : null,
searchQuery,
});
const handleReturnToThread = () => {
@@ -565,6 +565,9 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
<ScreenContent insetHorizontal={layout.usesSplitView}>
<FileTreeBrowser
key={JSON.stringify([environmentId, cwd])}
+ revealSelection={entriesQuery.revealSelection}
+ expandedPaths={entriesQuery.expandedPaths}
+ setExpandedPaths={entriesQuery.setExpandedPaths}
entries={entriesQuery.entries}
loadingDirectories={entriesQuery.loadingDirectories}
onLoadDirectory={entriesQuery.loadDirectory}
@@ -574,10 +577,13 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
searchQuery={searchQuery}
searchResultPaths={entriesQuery.searchResultPaths}
searchTruncated={entriesQuery.searchTruncated}
- selectedPath={null}
+ selectedPath={entriesQuery.selectedPath}
onPreviewFile={handlePreviewFile}
onRefresh={entriesQuery.refresh}
- onSelectFile={handleSelectFile}
+ onSelectFile={(path) => {
+ entriesQuery.selectPath(path);
+ handleSelectFile(path);
+ }}
/>
<FilesToolbarBottomFade />
</ScreenContent>
@@ -767,7 +773,10 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
headerInset={headerInset}
projectName={directoryPath ?? projectName}
selectedPath={directoryPath === null ? relativePath : null}
- onSelectFile={handleSelectFile}
+ onSelectFile={(path) => {
+ if (directoryPath !== null) entriesQuery.selectPath(path);
+ handleSelectFile(path);
+ }}
/>
) : undefined;
const safeAreaInsets = useSafeAreaInsets();
@@ -945,6 +954,9 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
<ScreenContent>
<FileTreeBrowser
key={JSON.stringify([environmentId, directoryPath])}
+ revealSelection={entriesQuery.revealSelection}
+ expandedPaths={entriesQuery.expandedPaths}
+ setExpandedPaths={entriesQuery.setExpandedPaths}
entries={entriesQuery.entries}
loadingDirectories={entriesQuery.loadingDirectories}
onLoadDirectory={entriesQuery.loadDirectory}
@@ -954,9 +966,12 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
searchQuery={searchQuery}
searchResultPaths={entriesQuery.searchResultPaths}
searchTruncated={entriesQuery.searchTruncated}
- selectedPath={null}
+ selectedPath={entriesQuery.selectedPath}
onRefresh={entriesQuery.refresh}
- onSelectFile={handleSelectFile}
+ onSelectFile={(path) => {
+ entriesQuery.selectPath(path);
+ handleSelectFile(path);
+ }}
/>
<FilesToolbarBottomFade />
</ScreenContent>
diff --git a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx
index 5f3deb6089c..d10746616d7 100644
--- a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx
+++ b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx
@@ -87,6 +87,9 @@ export function ThreadFileNavigatorPane(props: {
const fileTree = (
<FileTreeBrowser
key={JSON.stringify([props.environmentId, props.cwd])}
+ revealSelection={entriesQuery.revealSelection}
+ expandedPaths={entriesQuery.expandedPaths}
+ setExpandedPaths={entriesQuery.setExpandedPaths}
entries={entriesQuery.entries}
loadingDirectories={entriesQuery.loadingDirectories}
onLoadDirectory={entriesQuery.loadDirectory}
@@ -102,10 +105,13 @@ export function ThreadFileNavigatorPane(props: {
searchQuery={searchQuery}
searchResultPaths={entriesQuery.searchResultPaths}
searchTruncated={entriesQuery.searchTruncated}
- selectedPath={props.selectedPath}
+ selectedPath={props.selectedPath ?? entriesQuery.selectedPath}
onPreviewFile={handlePreviewFile}
onRefresh={entriesQuery.refresh}
- onSelectFile={props.onSelectFile}
+ onSelectFile={(path) => {
+ entriesQuery.selectPath(path);
+ props.onSelectFile(path);
+ }}
/>
);
diff --git a/apps/mobile/src/features/files/useFileTreeEntries.test.tsx b/apps/mobile/src/features/files/useFileTreeEntries.test.tsx
new file mode 100644
index 00000000000..8d707fd379a
--- /dev/null
+++ b/apps/mobile/src/features/files/useFileTreeEntries.test.tsx
@@ -0,0 +1,721 @@
+import {
+ EnvironmentId,
+ ProjectListEntriesError,
+ type ProjectEntry,
+ type ProjectListEntriesResult,
+} from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
+import * as Option from "effect/Option";
+import { AsyncResult } from "effect/reactivity";
+import { act, useLayoutEffect, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+type Query = {
+ readonly environmentId: EnvironmentId;
+ readonly input: {
+ readonly cwd: string;
+ readonly query?: string;
+ readonly directoryPath?: string;
+ };
+};
+type Result =
+ | {
+ readonly _tag: "Success";
+ readonly value: ProjectListEntriesResult;
+ readonly timestamp: number;
+ }
+ | { readonly _tag: "Failure"; readonly cause: Cause.Cause<Error> };
+type QueryState = {
+ success: AsyncResult.Success<ProjectListEntriesResult, Error> | null;
+ data: ProjectListEntriesResult;
+ error: string | null;
+ failure: ProjectListEntriesError | null;
+ isPending: boolean;
+ refresh: () => void;
+};
+
+const rootEntries: ProjectEntry[] = [{ kind: "directory", path: "src" }];
+const firstTarget = { cwd: "/first", environmentId: EnvironmentId.make("first") };
+
+const mocks = vi.hoisted(() => {
+ const createState = () => ({
+ requests: [] as {
+ readonly query: Query;
+ readonly signal?: AbortSignal;
+ readonly resolve: (result: Result) => void;
+ }[],
+ responseTimestamp: 0,
+ reconnect: () => {},
+ rootQuery: null as unknown as QueryState,
+ searchQuery: null as unknown as QueryState,
+ results: new WeakMap<
+ object,
+ {
+ data: ProjectListEntriesResult;
+ error: string | null;
+ pending: boolean;
+ result: AsyncResult.AsyncResult<ProjectListEntriesResult, Error>;
+ }
+ >(),
+ });
+ return { createState, state: createState() };
+});
+
+vi.mock("@t3tools/client-runtime/state/runtime", () => ({
+ executeAtomQuery: (_registry: unknown, query: Query, options: { signal?: AbortSignal }) =>
+ new Promise<Result>((resolve) =>
+ mocks.state.requests.push({ query, signal: options.signal, resolve }),
+ ),
+}));
+vi.mock("../../state/atom-registry", () => ({ appAtomRegistry: { refresh: () => {} } }));
+vi.mock("../../state/projects", () => ({
+ projectEnvironment: {
+ listEntries: (query: Query) => query,
+ searchEntries: (query: Query) => query,
+ },
+}));
+vi.mock("../../connection/catalog", () => ({
+ environmentCatalog: { sessionGenerationAtom: () => ({}) },
+}));
+vi.mock("../../state/queries", () => ({ useDebouncedValue: (value: string) => value }));
+vi.mock("@effect/atom-react", () => ({
+ useAtomValue: (atom: Partial<Query>) => {
+ const state = mocks.state;
+ const query = atom.input?.query === undefined ? state.rootQuery : state.searchQuery;
+ if (query.success) return query.success;
+ const cached = state.results.get(query);
+ if (
+ cached &&
+ cached.data === query.data &&
+ cached.error === query.error &&
+ cached.pending === query.isPending
+ ) {
+ return cached.result;
+ }
+ const result = query.error
+ ? AsyncResult.fail(query.failure ?? new Error(query.error), {
+ previousSuccess: Option.some(AsyncResult.success(query.data)),
+ })
+ : AsyncResult.success(query.data, {
+ waiting: query.isPending,
+ timestamp: ++state.responseTimestamp,
+ });
+ state.results.set(query, {
+ data: query.data,
+ error: query.error,
+ pending: query.isPending,
+ result,
+ });
+ return result;
+ },
+ useAtomRefresh: () => mocks.state.rootQuery.refresh,
+ useAtomMount: () => {},
+ useAtomSubscribe: (_atom: unknown, callback: () => void) => {
+ mocks.state.reconnect = callback;
+ },
+}));
+
+const { Children, Nothing } = vi.hoisted(() => ({
+ Children: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Nothing: () => null,
+}));
+vi.mock("react-native", () => ({
+ Platform: { OS: "ios" },
+ View: Children,
+ RefreshControl: Nothing,
+ Pressable: ({
+ children,
+ onPress,
+ accessibilityLabel,
+ }: {
+ children?: ReactNode;
+ onPress: () => void;
+ accessibilityLabel?: string;
+ }) => (
+ <button aria-label={accessibilityLabel} onClick={onPress}>
+ {children}
+ </button>
+ ),
+}));
+vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0 }) }));
+vi.mock("../../native/NativeScrollViewMarker", () => ({ NativeScrollView: Nothing }));
+vi.mock("../../native/native-layout-metrics", () => ({ useNativeColumnLayoutMetrics: () => null }));
+vi.mock("@legendapp/list/react-native", () => ({
+ LegendList: <T,>(props: {
+ data: ReadonlyArray<T>;
+ keyExtractor: (item: T) => string;
+ renderItem: (info: { item: T }) => ReactNode;
+ ListHeaderComponent?: ReactNode;
+ ListEmptyComponent?: ReactNode;
+ }) => (
+ <div>
+ {props.ListHeaderComponent}
+ {props.data.length === 0
+ ? props.ListEmptyComponent
+ : props.data.map((item) => (
+ <div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
+ ))}
+ </div>
+ ),
+}));
+vi.mock("../../components/ui/Button", () => ({
+ Button: ({
+ label,
+ onPress,
+ disabled,
+ }: {
+ label: string;
+ onPress: () => void;
+ disabled?: boolean;
+ }) => (
+ <button aria-label={label} disabled={disabled} onClick={onPress}>
+ {label}
+ </button>
+ ),
+}));
+vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: Nothing }));
+vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: Nothing }));
+vi.mock("../../components/ui/AppText", () => ({ AppText: Children }));
+vi.mock("../../components/PierreEntryIcon", () => ({ PierreEntryIcon: Nothing }));
+vi.mock("../../lib/cn", () => ({ cn: () => "" }));
+
+import { FileTreeBrowser } from "./FileTreeBrowser";
+import { useFileTreeEntries } from "./useFileTreeEntries";
+
+type Hook = typeof useFileTreeEntries;
+type Input = Parameters<Hook>[0];
+
+function setup(withBrowser = false) {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const state = mocks.createState();
+ mocks.state = state;
+ const rootQuery: QueryState = {
+ success: null,
+ data: { entries: rootEntries, truncated: false },
+ error: null,
+ failure: null,
+ isPending: false,
+ refresh: vi.fn(),
+ };
+ state.rootQuery = rootQuery;
+ const searchQuery: QueryState = { ...rootQuery, data: { entries: [], truncated: false } };
+ state.searchQuery = searchQuery;
+ const { requests } = state;
+ const container = document.body.appendChild(document.createElement("div"));
+ const root = createRoot(container);
+ let current: ReturnType<Hook>;
+ let renders = 0;
+ let controlledSelection: string | undefined;
+ function Probe(input: Input) {
+ if (++renders > 100 && withBrowser) throw new Error("File tree did not settle");
+ const result = useFileTreeEntries(input);
+ useLayoutEffect(() => {
+ current = result;
+ });
+ return withBrowser ? (
+ <FileTreeBrowser
+ key={JSON.stringify([input.environmentId, input.cwd])}
+ {...result}
+ selectedPath={controlledSelection ?? result.selectedPath}
+ searchQuery=""
+ onLoadDirectory={result.loadDirectory}
+ onRefresh={result.refresh}
+ onSelectFile={result.selectPath}
+ />
+ ) : null;
+ }
+ const unmount = () => {
+ act(() => root.unmount());
+ container.remove();
+ };
+ return {
+ requests,
+ rootQuery,
+ searchQuery,
+ get searchSuccess() {
+ const result = searchQuery.success ?? state.results.get(searchQuery)?.result;
+ if (result?._tag !== "Success") throw new Error("Search has not succeeded");
+ return result;
+ },
+ get responseTimestamp() {
+ return state.responseTimestamp;
+ },
+ controlSelection(path: string) {
+ controlledSelection = path;
+ },
+ updateView(expanded: string[], selected: string) {
+ renders = 0;
+ act(() => {
+ current.setExpandedPaths(() => new Set(expanded));
+ current.selectPath(selected);
+ });
+ },
+ unmount,
+ get current() {
+ return current;
+ },
+ get rows() {
+ return [...container.querySelectorAll("button")].map((button) =>
+ button.getAttribute("aria-label"),
+ );
+ },
+ press(label: string) {
+ renders = 0;
+ const button = container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
+ if (!button) throw new Error(`No row labelled ${label}`);
+ act(() => button.click());
+ },
+ render(target: Partial<Input> = {}) {
+ renders = 0;
+ const probe = <Probe {...firstTarget} searchQuery="" {...target} />;
+ act(() => root.render(probe));
+ },
+ load(path = "src", refresh = false) {
+ renders = 0;
+ act(() => {
+ void current.loadDirectory(path, refresh);
+ });
+ },
+ async succeed(index: number, entries: ProjectEntry[] = []) {
+ renders = 0;
+ await act(async () => {
+ requests[index]!.resolve({
+ _tag: "Success",
+ value: { entries, truncated: false },
+ timestamp: ++state.responseTimestamp,
+ });
+ });
+ },
+ async fail(index: number, message = "Directory unavailable") {
+ renders = 0;
+ await act(async () => {
+ requests[index]!.resolve({ _tag: "Failure", cause: Cause.fail(new Error(message)) });
+ });
+ },
+ [Symbol.dispose]: unmount,
+ };
+}
+
+describe("file tree workspace state", () => {
+ it("retries failed folders once on reconnect", async () => {
+ using screen = setup();
+ screen.render();
+ screen.load();
+ await screen.fail(0);
+ act(() => mocks.state.reconnect());
+ expect(screen.requests).toHaveLength(2);
+ act(() => mocks.state.reconnect());
+ expect(screen.requests).toHaveLength(2);
+ await screen.succeed(1);
+ act(() => mocks.state.reconnect());
+ expect(screen.requests).toHaveLength(2);
+ });
+
+ it("publishes immutable loading and loaded snapshots", async () => {
+ using screen = setup();
+ screen.render();
+ const initial = screen.current;
+ screen.load();
+ const loading = screen.current;
+ expect(loading.isPending).toBe(true);
+ expect([...loading.loadingDirectories]).toEqual(["src"]);
+ expect([...initial.loadingDirectories]).toEqual([]);
+ await screen.succeed(0, [{ kind: "file", path: "src/first.ts" }]);
+ expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/first.ts"]);
+ expect([...screen.current.loadedDirectories]).toEqual(["src"]);
+ expect(screen.current.isPending).toBe(false);
+ expect([...screen.current.loadingDirectories]).toEqual([]);
+ expect(loading.entries.map((entry) => entry.path)).toEqual(["src"]);
+ expect([...loading.loadedDirectories]).toEqual([]);
+ expect([...loading.loadingDirectories]).toEqual(["src"]);
+ });
+
+ it.each([{ cwd: "/second" }, { environmentId: EnvironmentId.make("second") }])(
+ "isolates directory state and restores it on return from %j",
+ async (target) => {
+ using screen = setup();
+ screen.render();
+ screen.load();
+ await screen.succeed(0, [{ kind: "file", path: "src/first.ts" }]);
+
+ screen.updateView(["src"], "src/first.ts");
+ const firstView = screen.current;
+ screen.render(target);
+ expect([...screen.current.expandedPaths]).toEqual([]);
+ expect(screen.current.selectedPath).toBeNull();
+ expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]);
+ expect([...screen.current.loadedDirectories]).toEqual([]);
+ expect([...screen.current.loadingDirectories]).toEqual([]);
+ screen.load();
+ expect(screen.requests[1]!.query).toEqual({
+ environmentId: target.environmentId ?? firstTarget.environmentId,
+ input: { cwd: target.cwd ?? firstTarget.cwd, directoryPath: "src" },
+ });
+ await screen.succeed(1, [{ kind: "file", path: "src/second.ts" }]);
+
+ screen.updateView([], "src/second.ts");
+ expect([...firstView.expandedPaths]).toEqual(["src"]);
+ expect(firstView.selectedPath).toBe("src/first.ts");
+ screen.render();
+ expect([...screen.current.expandedPaths]).toEqual(["src"]);
+ expect(screen.current.selectedPath).toBe("src/first.ts");
+ expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/first.ts"]);
+ expect([...screen.current.loadedDirectories]).toEqual(["src"]);
+ screen.load();
+ expect(screen.requests).toHaveLength(3);
+ await screen.succeed(2, [{ kind: "file", path: "src/first.ts" }]);
+
+ screen.render(target);
+ expect([...screen.current.expandedPaths]).toEqual([]);
+ expect(screen.current.selectedPath).toBe("src/second.ts");
+ expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/second.ts"]);
+ expect([...screen.current.loadedDirectories]).toEqual(["src"]);
+ },
+ );
+
+ it("ignores stale successes and failures after leaving and returning to a workspace", async () => {
+ using screen = setup();
+ screen.render();
+ screen.load();
+ screen.load("src/other");
+ screen.render({ cwd: "/second" });
+ screen.render();
+ screen.load();
+
+ await screen.succeed(0, [{ kind: "file", path: "src/stale.ts" }]);
+ await screen.fail(1, "Stale error");
+ expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]);
+ expect(screen.current.error).toBeNull();
+ expect([...screen.current.loadingDirectories]).toEqual(["src"]);
+ expect(screen.current.isPending).toBe(true);
+
+ await screen.succeed(2, [{ kind: "file", path: "src/current.ts" }]);
+ expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/current.ts"]);
+ expect(screen.current.error).toBeNull();
+ expect(screen.current.isPending).toBe(false);
+ expect([...screen.current.loadingDirectories]).toEqual([]);
+ });
+
+ it("retains recent listings and expansion when leaving a large workspace", async () => {
+ using screen = setup();
+ screen.render();
+ const paths = Array.from({ length: 70 }, (_, index) => `src/directory-${index}`);
+ screen.load();
+ await screen.succeed(
+ 0,
+ paths.map((path) => ({ kind: "directory", path })),
+ );
+ for (const path of paths) {
+ screen.load(path);
+ await screen.succeed(screen.requests.length - 1, [{ kind: "file", path: `${path}/file.ts` }]);
+ }
+ screen.updateView(["src", ...paths], `${paths[69]}/file.ts`);
+ screen.render({ cwd: "/other" });
+ screen.render();
+ expect(screen.current.loadedDirectories.size).toBe(64);
+ expect(screen.current.loadedDirectories.has(paths[69]!)).toBe(true);
+ expect(screen.current.expandedPaths.size).toBe(71);
+ expect(screen.current.selectedPath).toBe(`${paths[69]}/file.ts`);
+ for (let index = 1; index <= 8; index++) screen.render({ cwd: `/workspace-${index}` });
+ screen.render();
+ expect(screen.current.loadedDirectories.size).toBe(0);
+ expect(screen.current.expandedPaths.size).toBe(0);
+ expect(screen.current.selectedPath).toBeNull();
+ });
+
+ it("retries a failed folder only when the user expands it again", async () => {
+ using screen = setup(true);
+ screen.render();
+ expect(screen.rows).toEqual(["src"]);
+ expect(screen.requests).toHaveLength(0);
+
+ screen.press("src");
+ expect(screen.requests).toHaveLength(1);
+ await screen.fail(0);
+ expect(screen.current.error).toBe("Directory unavailable");
+ // Re-rendering and the browser's passive expansion effect never retry a failed listing.
+ screen.render();
+ screen.render();
+ expect(screen.requests).toHaveLength(1);
+ expect(screen.rows).toEqual(["src"]);
+
+ screen.press("src");
+ expect([...screen.current.expandedPaths]).toEqual([]);
+ expect(screen.requests).toHaveLength(1);
+ screen.press("src");
+ expect([...screen.current.expandedPaths]).toEqual(["src"]);
+ expect(screen.requests).toHaveLength(2);
+ await screen.succeed(1, [{ kind: "file", path: "src/file.ts" }]);
+ expect(screen.current.error).toBeNull();
+ expect(screen.rows).toEqual(["src", "src/file.ts"]);
+
+ // A loaded folder serves from cache on collapse and expand.
+ screen.press("src");
+ screen.press("src");
+ expect(screen.rows).toEqual(["src", "src/file.ts"]);
+ expect(screen.requests).toHaveLength(2);
+ });
+
+ it("reveals a controlled leaf-only search result after search clears", () => {
+ using screen = setup(true);
+ screen.render();
+ screen.searchQuery.data = {
+ entries: [{ kind: "file", path: "src/new/file.ts" }],
+ truncated: false,
+ };
+ screen.controlSelection("src/new/file.ts");
+ screen.render({ searchQuery: "file" });
+ expect([...screen.current.expandedPaths]).toEqual(["src", "src/new"]);
+ screen.render();
+ expect(screen.current.entries.map((entry) => entry.path)).toContain("src/new/file.ts");
+ });
+
+ it.each(["collapse", "delete"])("settles controlled selection after %s", async (action) => {
+ using screen = setup(true);
+ screen.render();
+ screen.updateView([], "src/nested/file.ts");
+ await screen.succeed(0, [{ kind: "directory", path: "src/nested" }]);
+ expect([...screen.current.expandedPaths]).toEqual(["src", "src/nested"]);
+ if (action === "collapse") {
+ screen.updateView([], "src/nested/file.ts");
+ expect([...screen.current.expandedPaths]).toEqual([]);
+ screen.render({ cwd: "/second" });
+ screen.render();
+ expect([...screen.current.expandedPaths]).toEqual([]);
+ }
+ screen.rootQuery.data = { entries: [], truncated: false };
+ screen.render();
+ expect([...screen.current.expandedPaths]).toEqual([]);
+ expect(screen.current.selectedPath).toBeNull();
+ if (action === "delete") {
+ screen.controlSelection("src/nested/file.ts");
+ screen.searchQuery.data = {
+ entries: [
+ { kind: "directory", path: "src" },
+ { kind: "directory", path: "src/nested" },
+ { kind: "file", path: "src/nested/file.ts" },
+ ],
+ truncated: false,
+ };
+ screen.rootQuery.failure = new ProjectListEntriesError({
+ cwd: "/first",
+ failure: "workspace_root_not_found",
+ });
+ screen.rootQuery.error = screen.rootQuery.failure.message;
+ const requestCount = screen.requests.length;
+ for (const error of [null, "Search unavailable"]) {
+ screen.searchQuery.error = error;
+ screen.render({ searchQuery: "nested" });
+ expect(screen.current.entries).toEqual([]);
+ expect([...screen.current.expandedPaths]).toEqual([]);
+ expect([...screen.current.loadedDirectories]).toEqual([]);
+ expect(screen.current.isPending).toBe(false);
+ expect(screen.requests).toHaveLength(requestCount);
+ }
+ }
+ });
+
+ it.each(["return", "missing root"])(
+ "revalidates retained children after %s without clearing for transient errors",
+ async (scenario) => {
+ using screen = setup();
+ screen.render();
+ screen.load();
+ await screen.succeed(0, [{ kind: "file", path: "src/old.ts" }]);
+ screen.updateView(["src"], "src/old.ts");
+ screen.render({ cwd: "/second" });
+ screen.render();
+ screen.rootQuery.error = "Connection unavailable";
+ screen.render();
+ expect(screen.current.selectedPath).toBe("src/old.ts");
+ expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src", "src/old.ts"]);
+ if (scenario === "missing root") {
+ screen.rootQuery.failure = new ProjectListEntriesError({
+ cwd: "/first",
+ failure: "workspace_root_not_found",
+ });
+ screen.rootQuery.error = screen.rootQuery.failure.message;
+ expect(screen.rootQuery.error).toBe("Failed to list workspace entries in '/first'.");
+ screen.render();
+ expect(screen.current.selectedPath).toBeNull();
+ expect([...screen.current.expandedPaths]).toEqual([]);
+ expect([...screen.current.loadedDirectories]).toEqual([]);
+ }
+ screen.rootQuery.error = null;
+ screen.rootQuery.failure = null;
+ screen.render();
+ if (scenario === "missing root") {
+ expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]);
+ expect(screen.current.selectedPath).toBeNull();
+ }
+ screen.load();
+ expect(screen.requests).toHaveLength(2);
+ await screen.succeed(1, []);
+ expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]);
+ expect(screen.current.selectedPath).toBeNull();
+ },
+ );
+
+ it.each(["new", "src/new"])(
+ "keeps search discovery %s until its parent listing revalidates it",
+ async (path) => {
+ using screen = setup();
+ screen.render();
+ screen.load();
+ await screen.succeed(0, []);
+ screen.searchQuery.data = {
+ entries: [{ kind: "file", path: `${path}/file.ts` }],
+ truncated: false,
+ };
+ screen.render({ searchQuery: "new" });
+ const expanded = path.includes("/") ? ["src", path] : [path];
+ screen.updateView(expanded, `${path}/file.ts`);
+ expect(screen.current.selectedPath).toBe(`${path}/file.ts`);
+ expect([...screen.current.expandedPaths]).toEqual(expanded);
+ screen.load(path);
+ await screen.succeed(1, [
+ { kind: "file", path: `${path}/file.ts` },
+ { kind: "file", path: `${path}/other.ts` },
+ ]);
+ expect([...screen.current.loadedDirectories]).toEqual(["src", path]);
+
+ const cachedSearch = screen.searchSuccess;
+ for (const searchQuery of ["", "other"]) {
+ screen.searchQuery.data = { entries: [], truncated: false };
+ screen.render({ searchQuery });
+ expect(screen.current.selectedPath).toBe(`${path}/file.ts`);
+ expect([...screen.current.expandedPaths]).toEqual(expanded);
+ expect([...screen.current.loadedDirectories]).toEqual(["src", path]);
+ expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/file.ts` });
+ expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/other.ts` });
+ }
+
+ screen.render();
+ for (const target of [{ cwd: "/second" }, { environmentId: EnvironmentId.make("second") }]) {
+ screen.render(target);
+ screen.render();
+ expect(screen.current.selectedPath).toBe(`${path}/file.ts`);
+ expect([...screen.current.expandedPaths]).toEqual(expanded);
+ expect([...screen.current.loadedDirectories]).toEqual(["src", path]);
+ expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/other.ts` });
+ }
+
+ screen.searchQuery.data = {
+ entries: [{ kind: "file", path: `${path}/file.ts` }],
+ truncated: false,
+ };
+ screen.render({ searchQuery: "new" });
+ for (const equalContents of [false, true]) {
+ // A later parent listing wins over retained discovery evidence.
+ if (path.includes("/")) {
+ // Refresh re-lists the root and every reachable folder; the empty parent prunes the child.
+ const refreshed = screen.requests.length;
+ act(() => {
+ void screen.current.refresh();
+ });
+ expect(screen.requests.slice(refreshed).map((request) => request.query.input)).toEqual([
+ { cwd: "/first", directoryPath: "" },
+ { cwd: "/first", query: "new", limit: 200 },
+ { cwd: "/first", directoryPath: "src" },
+ { cwd: "/first", directoryPath: path },
+ ]);
+ // The parent settles last so its listing carries the newest response timestamp.
+ for (const index of [refreshed, refreshed + 1, refreshed + 3, refreshed + 2]) {
+ await screen.succeed(index, []);
+ }
+ } else {
+ const cachedData = screen.rootQuery.data;
+ screen.rootQuery.isPending = true;
+ screen.render({ searchQuery: "new" });
+ expect(screen.current.selectedPath).toBe(`${path}/file.ts`);
+ screen.rootQuery.isPending = false;
+ expect(screen.rootQuery.data).toBe(cachedData);
+ screen.render({ searchQuery: "new" });
+ }
+ expect(screen.current.selectedPath).toBeNull();
+ expect([...screen.current.expandedPaths]).toEqual(path.includes("/") ? ["src"] : []);
+ expect([...screen.current.loadedDirectories]).toEqual(["src"]);
+
+ // Cover an older cache and the timestamp's ambiguous same-millisecond boundary.
+ for (const success of [
+ cachedSearch,
+ AsyncResult.success(cachedSearch.value, { timestamp: screen.responseTimestamp }),
+ ]) {
+ screen.searchQuery.data = { entries: [], truncated: false };
+ screen.render({ searchQuery: "other" });
+ screen.searchQuery.success = success;
+ screen.searchQuery.data = success.value;
+ screen.render({ searchQuery: "new" });
+ screen.updateView(expanded, `${path}/file.ts`);
+ const requestCount = screen.requests.length;
+ screen.load(path);
+ expect(screen.requests).toHaveLength(requestCount + 1);
+ await screen.fail(requestCount);
+ screen.searchQuery.success = null;
+ screen.render();
+ expect(screen.current.selectedPath).toBeNull();
+ expect([...screen.current.expandedPaths]).toEqual(path.includes("/") ? ["src"] : []);
+ expect([...screen.current.loadedDirectories]).toEqual(["src"]);
+ expect(
+ screen.current.entries.some(
+ (entry) => entry.path === path || entry.path.startsWith(`${path}/`),
+ ),
+ ).toBe(false);
+ }
+
+ const cachedSearchData = screen.searchQuery.data;
+ screen.searchQuery.isPending = true;
+ screen.render({ searchQuery: "new" });
+ expect(screen.current.selectedPath).toBeNull();
+ expect([...screen.current.loadedDirectories]).toEqual(["src"]);
+ screen.searchQuery.isPending = false;
+ if (!equalContents) {
+ screen.searchQuery.data = {
+ ...cachedSearchData,
+ entries: [...cachedSearchData.entries, { kind: "file", path: `${path}/added.ts` }],
+ };
+ }
+ expect(screen.searchQuery.data === cachedSearchData).toBe(equalContents);
+ screen.render({ searchQuery: "new" });
+ screen.updateView(expanded, `${path}/file.ts`);
+ screen.load(path);
+ await screen.succeed(screen.requests.length - 1, [
+ { kind: "file", path: `${path}/file.ts` },
+ { kind: "file", path: `${path}/recreated.ts` },
+ ]);
+ expect(screen.current.selectedPath).toBe(`${path}/file.ts`);
+ expect([...screen.current.expandedPaths]).toEqual(expanded);
+ expect([...screen.current.loadedDirectories]).toEqual(["src", path]);
+ expect(screen.current.entries).toContainEqual({ kind: "file", path: `${path}/file.ts` });
+ expect(screen.current.entries).toContainEqual({
+ kind: "file",
+ path: `${path}/recreated.ts`,
+ });
+ }
+ },
+ );
+
+ it("prunes deleted directory contents, expansion and selection after a fresh parent listing", async () => {
+ using screen = setup();
+ screen.render();
+ screen.load();
+ await screen.succeed(0, [{ kind: "directory", path: "src/nested" }]);
+ screen.load("src/nested");
+ await screen.succeed(1, [{ kind: "file", path: "src/nested/file.ts" }]);
+ screen.updateView(["src", "src/nested"], "src/nested/file.ts");
+ screen.rootQuery.data = { entries: [], truncated: true };
+ screen.render();
+ expect([...screen.current.loadedDirectories]).toEqual(["src", "src/nested"]);
+ expect(screen.current.selectedPath).toBe("src/nested/file.ts");
+ screen.rootQuery.data = { entries: [], truncated: false };
+ screen.render();
+ expect(screen.current.entries).toEqual([]);
+ expect([...screen.current.loadedDirectories]).toEqual([]);
+ expect([...screen.current.expandedPaths]).toEqual([]);
+ expect(screen.current.selectedPath).toBeNull();
+ screen.rootQuery.data = { entries: rootEntries, truncated: false };
+ screen.render();
+ expect(screen.current.entries.map((entry) => entry.path)).toEqual(["src"]);
+ });
+});
diff --git a/apps/mobile/src/features/files/useFileTreeEntries.ts b/apps/mobile/src/features/files/useFileTreeEntries.ts
index d171f80e602..1734cb705a7 100644
--- a/apps/mobile/src/features/files/useFileTreeEntries.ts
+++ b/apps/mobile/src/features/files/useFileTreeEntries.ts
@@ -1,9 +1,9 @@
import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
-import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
+import { ProjectListEntriesError, type EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
+import { useCallback, useLayoutEffect, useRef, useState } from "react";
import { Atom } from "effect/reactivity";
-import { useEffect, useReducer, useRef, useState } from "react";
import { environmentCatalog } from "../../connection/catalog";
import { appAtomRegistry } from "../../state/atom-registry";
@@ -11,6 +11,92 @@ import { projectEnvironment } from "../../state/projects";
import { useDebouncedValue } from "../../state/queries";
import { useEnvironmentQuery } from "../../state/query";
+function createDirectories() {
+ return {
+ target: {},
+ entries: new Map<string, ReadonlyArray<ProjectEntry>>(),
+ errors: new Map<string, string>(),
+ completeDirectories: new Set<string>(),
+ listingCompletedAt: new Map<string, number>(),
+ discoveries: new Map<string, ProjectEntry>(),
+ rootListing: null as { readonly timestamp: number } | null,
+ validatedDirectories: new Set<string>(),
+ loading: new Set<string>(),
+ expandedPaths: new Set<string>(),
+ selectedPath: null as string | null,
+ revealedSelection: { path: null as string | null, ancestors: new Set<string>() },
+ isRefreshing: false,
+ };
+}
+
+function boundDirectories(current: ReturnType<typeof createDirectories>, preserveVisible = true) {
+ const visible = (path: string) => {
+ const parts = path.split("/");
+ return parts.every((_, index) =>
+ current.expandedPaths.has(parts.slice(0, index + 1).join("/")),
+ );
+ };
+ const inactive = [...new Set([...current.entries.keys(), ...current.errors.keys()])].filter(
+ (path) => !preserveVisible || !visible(path),
+ );
+ const ownedPaths = [
+ ...current.entries.keys(),
+ ...current.expandedPaths,
+ current.selectedPath,
+ ].filter((path) => path !== null);
+ const discoveries = new Map(
+ [...current.discoveries].filter(([path]) =>
+ ownedPaths.some((owned) => owned === path || owned.startsWith(`${path}/`)),
+ ),
+ );
+ if (inactive.length <= 64)
+ return discoveries.size === current.discoveries.size ? current : { ...current, discoveries };
+ const evicted = new Set(inactive.slice(0, -64));
+ // Evict listing data, not the user's expansion and selection. A missing parent reloads on return.
+ return {
+ ...current,
+ discoveries,
+ entries: new Map([...current.entries].filter(([path]) => !evicted.has(path))),
+ errors: new Map([...current.errors].filter(([path]) => !evicted.has(path))),
+ completeDirectories: new Set(
+ [...current.completeDirectories].filter((path) => !evicted.has(path)),
+ ),
+ validatedDirectories: new Set(
+ [...current.validatedDirectories].filter((path) => !evicted.has(path)),
+ ),
+ listingCompletedAt: new Map(
+ [...current.listingCompletedAt].filter(([path]) => !evicted.has(path)),
+ ),
+ };
+}
+
+function contradictsListing(path: string, parent: string, entries: ReadonlyArray<ProjectEntry>) {
+ if (parent !== "" && !path.startsWith(`${parent}/`)) return false;
+ const child = path.slice(parent === "" ? 0 : parent.length + 1).split("/")[0];
+ const childPath = parent === "" ? child : `${parent}/${child}`;
+ const entry = entries.find((item) => item.path === childPath);
+ return !entry || (path !== childPath && entry.kind !== "directory");
+}
+
+function createRequests() {
+ return {
+ active: true,
+ refreshVersion: 0,
+ pending: new Map<string, AbortController>(),
+ };
+}
+
+function getRequests(
+ requestsByTarget: WeakMap<object, ReturnType<typeof createRequests>>,
+ target: object,
+) {
+ let requests = requestsByTarget.get(target);
+ if (!requests) {
+ requests = createRequests();
+ requestsByTarget.set(target, requests);
+ }
+ return requests;
+}
const noSessionGeneration = Atom.make(0);
export function useFileTreeEntries(input: {
@@ -27,6 +113,7 @@ export function useFileTreeEntries(input: {
? projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath: "" } })
: null,
);
+ const { refresh: refreshRoot } = root;
const search = useEnvironmentQuery(
searching && debouncedQuery.length > 0 && cwd !== null && environmentId !== null
? projectEnvironment.searchEntries({
@@ -35,42 +122,102 @@ export function useFileTreeEntries(input: {
})
: null,
);
- const [, render] = useReducer((value: number) => value + 1, 0);
- const [entriesRevision, entriesChanged] = useReducer((value: number) => value + 1, 0);
- const refreshVersion = useRef(0);
- const directories = {
- cwd,
- environmentId,
- entries: new Map<string, ReadonlyArray<ProjectEntry>>(),
- requested: new Set<string>(),
- pending: new Map<string, AbortController>(),
- errors: new Map<string, string>(),
- };
- const [refreshingDirectories, setRefreshingDirectories] = useState<typeof directories | null>(
- null,
- );
- useEffect(
- () => () => {
- refreshVersion.current++;
- for (const controller of directories.pending.values()) controller.abort();
- directories.pending.clear();
- },
- [directories],
+ const workspaceKey = JSON.stringify([environmentId, cwd]);
+ const [cache, setCache] = useState(() => ({
+ key: workspaceKey,
+ workspaces: new Map([[workspaceKey, createDirectories()]]),
+ }));
+ const savedDirectories = cache.workspaces.get(workspaceKey) ?? createDirectories();
+ // Requests belong to a visit, so returning cannot revive an old completion.
+ const directories =
+ cache.key === workspaceKey
+ ? savedDirectories
+ : {
+ ...savedDirectories,
+ target: {},
+ validatedDirectories: new Set<string>(),
+ errors: new Map<string, string>(),
+ loading: new Set<string>(),
+ isRefreshing: false,
+ };
+ if (cache.key !== workspaceKey) {
+ const workspaces = new Map(cache.workspaces);
+ const previous = workspaces.get(cache.key);
+ if (previous) {
+ workspaces.set(
+ cache.key,
+ boundDirectories(
+ {
+ ...previous,
+ errors: new Map(),
+ loading: new Set(),
+ isRefreshing: false,
+ },
+ false,
+ ),
+ );
+ }
+ workspaces.delete(workspaceKey);
+ workspaces.set(workspaceKey, directories);
+ if (workspaces.size > 8) workspaces.delete(workspaces.keys().next().value!);
+ setCache({ key: workspaceKey, workspaces });
+ }
+ const setDirectories = useCallback(
+ (
+ update: (
+ current: ReturnType<typeof createDirectories>,
+ ) => ReturnType<typeof createDirectories>,
+ ) =>
+ setCache((current) => {
+ const previous = current.workspaces.get(workspaceKey);
+ if (!previous) return current;
+ const next = boundDirectories(update(previous));
+ if (next === previous) return current;
+ return { ...current, workspaces: new Map(current.workspaces).set(workspaceKey, next) };
+ }),
+ [workspaceKey],
);
+ const { target } = directories;
+ const requestsByTarget = useRef(new WeakMap<object, ReturnType<typeof createRequests>>());
+ // Cancel the old target before consumers' passive effects start new directory loads.
+ useLayoutEffect(() => {
+ const requests = getRequests(requestsByTarget.current, target);
+ requests.active = true;
+ refreshRoot();
+ return () => {
+ requests.active = false;
+ requests.refreshVersion++;
+ for (const controller of requests.pending.values()) controller.abort();
+ requests.pending.clear();
+ setDirectories((current) =>
+ current.target === target
+ ? { ...current, loading: new Set(), isRefreshing: false }
+ : current,
+ );
+ };
+ }, [target, setDirectories, requestsByTarget, refreshRoot]);
+ const updateDirectories = (
+ update: (current: ReturnType<typeof createDirectories>) => ReturnType<typeof createDirectories>,
+ ) => setDirectories((current) => (current.target === target ? update(current) : current));
const loadDirectory = (directoryPath: string, refresh = false) => {
+ const requests = getRequests(requestsByTarget.current, target);
if (
+ !requests.active ||
+ missingRoot ||
cwd === null ||
environmentId === null ||
- (!refresh && directories.entries.has(directoryPath)) ||
- directories.pending.has(directoryPath)
+ (!refresh && directories.validatedDirectories.has(directoryPath)) ||
+ requests.pending.has(directoryPath)
) {
return;
}
const controller = new AbortController();
- directories.requested.add(directoryPath);
- directories.pending.set(directoryPath, controller);
- directories.errors.delete(directoryPath);
- render();
+ requests.pending.set(directoryPath, controller);
+ updateDirectories((current) => {
+ const errors = new Map(current.errors);
+ errors.delete(directoryPath);
+ return { ...current, errors, loading: new Set(current.loading).add(directoryPath) };
+ });
const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
appAtomRegistry.refresh(atom);
return executeAtomQuery(appAtomRegistry, atom, {
@@ -79,26 +226,73 @@ export function useFileTreeEntries(input: {
reportDefect: false,
}).then((result) => {
if (controller.signal.aborted) return;
- directories.pending.delete(directoryPath);
- if (result._tag === "Success") {
- directories.entries.set(
- directoryPath,
- result.value.entries.filter(
- (entry) =>
- entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
- ),
- );
- entriesChanged();
- } else {
+ requests.pending.delete(directoryPath);
+ updateDirectories((current) => {
+ const validatedDirectories = new Set(current.validatedDirectories).add(directoryPath);
+ const loading = new Set(current.loading);
+ loading.delete(directoryPath);
+ if (result._tag === "Success") {
+ const entries = new Map(current.entries);
+ entries.delete(directoryPath);
+ entries.set(
+ directoryPath,
+ result.value.entries.filter(
+ (entry) =>
+ entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
+ ),
+ );
+ const completeDirectories = new Set(current.completeDirectories);
+ if (result.value.truncated) completeDirectories.delete(directoryPath);
+ else completeDirectories.add(directoryPath);
+ return {
+ ...current,
+ entries,
+ loading,
+ completeDirectories,
+ discoveries: result.value.truncated
+ ? current.discoveries
+ : new Map(
+ [...current.discoveries].filter(
+ ([path]) => !contradictsListing(path, directoryPath, result.value.entries),
+ ),
+ ),
+ validatedDirectories,
+ listingCompletedAt: new Map(current.listingCompletedAt).set(
+ directoryPath,
+ result.timestamp,
+ ),
+ };
+ }
const error = Cause.squash(result.cause);
- directories.errors.set(
- directoryPath,
- error instanceof Error ? error.message : "Files unavailable",
- );
- }
- render();
+ return {
+ ...current,
+ loading,
+ validatedDirectories,
+ errors: new Map(current.errors).set(
+ directoryPath,
+ error instanceof Error ? error.message : "Files unavailable",
+ ),
+ };
+ });
});
};
+ const missingRoot =
+ root.failure instanceof ProjectListEntriesError &&
+ root.failure.failure === "workspace_root_not_found";
+ const rootData = missingRoot ? null : root.data;
+ const rootListing = root.successResult ?? directories.rootListing;
+ if (
+ missingRoot &&
+ (directories.entries.size > 0 ||
+ directories.errors.size > 0 ||
+ directories.loading.size > 0 ||
+ directories.expandedPaths.size > 0 ||
+ directories.selectedPath !== null ||
+ directories.discoveries.size > 0)
+ ) {
+ setDirectories(() => createDirectories());
+ }
+ const { refresh: refreshSearch, data: searchData, successResult: searchResult } = search;
// A folder read fails at once while its environment is unreachable; read it again once a new
// session is up rather than leaving the error until someone refreshes.
const sessionGeneration =
@@ -108,13 +302,11 @@ export function useFileTreeEntries(input: {
// A listener alone does not compute the atom, so nothing would follow the connection.
useAtomMount(sessionGeneration);
useAtomSubscribe(sessionGeneration, () => {
- for (const path of directories.errors.keys()) void loadDirectory(path);
+ for (const path of directories.errors.keys()) void loadDirectory(path, true);
});
- const { refresh: refreshRoot, data: rootData } = root;
- const { refresh: refreshSearch, data: searchData } = search;
const snapshot = (() => {
- const merged = new Map<string, ProjectEntry>();
- if (searching) {
+ const merged = new Map(missingRoot ? [] : directories.discoveries);
+ if (searching && !missingRoot) {
for (const entry of searchData?.entries ?? []) merged.set(entry.path, entry);
}
const reachableDirectories = new Set<string>();
@@ -127,31 +319,158 @@ export function useFileTreeEntries(input: {
}
}
};
+ if (!missingRoot) {
+ const discoveries = new Map(directories.discoveries);
+ // Search can return only leaves; their inferred parents still own loaded children.
+ for (const entry of directories.discoveries.values()) {
+ const parts = entry.path.split("/");
+ for (let index = 1; index < parts.length; index++) {
+ const path = parts.slice(0, index).join("/");
+ if (!discoveries.has(path)) discoveries.set(path, { kind: "directory", path });
+ }
+ }
+ visit([...discoveries.values()]);
+ }
visit((rootData?.entries ?? []).filter((entry) => !entry.path.includes("/")));
return {
- revision: entriesRevision,
entries: [...merged.values()],
reachableDirectories,
- searchResultPaths: searching
- ? new Set((searchData?.entries ?? []).map((entry) => entry.path))
- : null,
+ searchResultPaths:
+ searching && !missingRoot
+ ? new Set((searchData?.entries ?? []).map((entry) => entry.path))
+ : null,
};
})();
+ if (rootData) {
+ const deleted = (path: string, directory = false) => {
+ const parts = path.split("/");
+ for (let index = 0; index < parts.length; index++) {
+ const parent = parts.slice(0, index).join("/");
+ const listing = index === 0 ? rootData.entries : directories.entries.get(parent);
+ const child = parts.slice(0, index + 1).join("/");
+ const complete =
+ index === 0 ? !rootData.truncated : directories.completeDirectories.has(parent);
+ const entry = listing?.find((item) => item.path === child);
+ if (complete && listing && !entry) {
+ const listingCompletedAt =
+ index === 0 && directories.rootListing !== rootListing
+ ? rootListing?.timestamp
+ : directories.listingCompletedAt.get(parent);
+ // Cached queries keep their completion time across query switches.
+ // Equal-millisecond responses cannot prove a path postdates the listing.
+ const retained =
+ !(index === 0 && directories.rootListing !== rootListing) &&
+ [...directories.discoveries.keys()].some(
+ (path) => path === child || path.startsWith(`${child}/`),
+ );
+ const discovered =
+ retained ||
+ (searching &&
+ query === debouncedQuery &&
+ searchResult !== null &&
+ searchResult.timestamp > (listingCompletedAt ?? -Infinity) &&
+ searchData?.entries.some(
+ (item) => item.path === child || item.path.startsWith(`${child}/`),
+ ));
+ if (!discovered) return true;
+ }
+ if (entry && (directory || index < parts.length - 1) && entry.kind !== "directory")
+ return true;
+ }
+ return false;
+ };
+ const reconciled = (() => {
+ const current = directories;
+ const discoveries = new Map(current.discoveries);
+ if (current.rootListing !== rootListing && !rootData.truncated) {
+ for (const path of discoveries.keys()) {
+ if (contradictsListing(path, "", rootData.entries)) discoveries.delete(path);
+ }
+ }
+ if (searching && query === debouncedQuery && searchResult !== null) {
+ const ownedPaths = [
+ ...current.entries.keys(),
+ ...current.expandedPaths,
+ current.selectedPath,
+ ];
+ for (const entry of searchData?.entries ?? []) {
+ if (
+ ownedPaths.some((path) => path === entry.path || path?.startsWith(`${entry.path}/`)) &&
+ !deleted(entry.path, entry.kind === "directory")
+ )
+ discoveries.set(entry.path, entry);
+ }
+ }
+ const entries = new Map([...current.entries].filter(([path]) => !deleted(path, true)));
+ const errors = new Map([...current.errors].filter(([path]) => !deleted(path, true)));
+ const expandedPaths = new Set(
+ [...current.expandedPaths].filter((path) => !deleted(path, true)),
+ );
+ const selectedPath =
+ current.selectedPath !== null && deleted(current.selectedPath)
+ ? null
+ : current.selectedPath;
+ if (
+ entries.size === current.entries.size &&
+ errors.size === current.errors.size &&
+ expandedPaths.size === current.expandedPaths.size &&
+ selectedPath === current.selectedPath &&
+ current.rootListing === rootListing &&
+ discoveries.size === current.discoveries.size &&
+ [...discoveries].every(([path, entry]) => current.discoveries.get(path) === entry)
+ )
+ return current;
+ const completeDirectories = new Set(
+ [...current.completeDirectories].filter((path) => entries.has(path)),
+ );
+ return {
+ ...current,
+ rootListing,
+ discoveries,
+ listingCompletedAt: new Map(
+ [...current.listingCompletedAt].filter(([path]) => path === "" || entries.has(path)),
+ ).set(
+ "",
+ current.rootListing === rootListing
+ ? (current.listingCompletedAt.get("") ?? -Infinity)
+ : (rootListing?.timestamp ?? -Infinity),
+ ),
+ entries,
+ errors,
+ expandedPaths,
+ selectedPath,
+ completeDirectories,
+ validatedDirectories: new Set(
+ [...current.validatedDirectories].filter((path) => !deleted(path, true)),
+ ),
+ };
+ })();
+ if (reconciled !== directories) setDirectories(() => reconciled);
+ }
+
const refresh = () => {
+ const requests = getRequests(requestsByTarget.current, target);
+ if (!requests.active) return Promise.resolve();
refreshRoot();
- if (searching) refreshSearch();
+ if (searching && !missingRoot) refreshSearch();
const paths = new Set(
- [...directories.requested].filter((path) => snapshot.reachableDirectories.has(path)),
+ [...directories.entries.keys(), ...directories.errors.keys(), ...directories.loading].filter(
+ (path) => snapshot.reachableDirectories.has(path),
+ ),
);
- for (const controller of directories.pending.values()) controller.abort();
- directories.pending.clear();
- directories.errors.clear();
- const version = ++refreshVersion.current;
- setRefreshingDirectories(directories);
+ for (const controller of requests.pending.values()) controller.abort();
+ requests.pending.clear();
+ const version = ++requests.refreshVersion;
+ updateDirectories((current) => ({
+ ...current,
+ errors: new Map(),
+ loading: new Set(),
+ isRefreshing: true,
+ }));
const remaining = paths.values();
const worker = async () => {
- while (version === refreshVersion.current) {
+ while (requests.active && version === requests.refreshVersion) {
const next = remaining.next();
if (next.done) return;
await loadDirectory(next.value, true);
@@ -161,7 +480,7 @@ export function useFileTreeEntries(input: {
cwd !== null && environmentId !== null
? [
projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath: "" } }),
- ...(searching
+ ...(searching && !missingRoot
? [
projectEnvironment.searchEntries({
environmentId,
@@ -177,29 +496,83 @@ export function useFileTreeEntries(input: {
),
...Array.from({ length: Math.min(4, paths.size) }, () => worker()),
];
- render();
return Promise.all(work).finally(() => {
- if (version === refreshVersion.current) setRefreshingDirectories(null);
+ if (version === requests.refreshVersion) {
+ updateDirectories((current) => ({ ...current, isRefreshing: false }));
+ }
});
};
+ const revealSelection = (path: string | null) => {
+ if (missingRoot) return;
+ updateDirectories((current) => {
+ const previous = current.revealedSelection;
+ const handled = previous.path === path ? previous.ancestors : new Set<string>();
+ const parts = path?.split("/").filter(Boolean) ?? [];
+ const ancestors = parts
+ .slice(1)
+ .map((_, index) => parts.slice(0, index + 1).join("/"))
+ .filter(
+ (ancestor) =>
+ !handled.has(ancestor) &&
+ snapshot.entries.some(
+ (entry) =>
+ (entry.kind === "directory" && entry.path === ancestor) ||
+ (entry.path === path && entry.path.startsWith(`${ancestor}/`)),
+ ),
+ );
+ if (previous.path === path && ancestors.length === 0) return current;
+ return {
+ ...current,
+ discoveries: new Map([
+ ...current.discoveries,
+ ...snapshot.entries
+ .filter((entry) => entry.path === path)
+ .map((entry) => [entry.path, entry] as const),
+ ]),
+ selectedPath: path,
+ revealedSelection: { path, ancestors: new Set([...handled, ...ancestors]) },
+ expandedPaths: new Set([...current.expandedPaths, ...ancestors]),
+ };
+ });
+ };
+
+ const setExpandedPaths = useCallback(
+ (update: (current: ReadonlySet<string>) => ReadonlySet<string>) =>
+ setDirectories((current) => {
+ const expandedPaths = update(current.expandedPaths);
+ return expandedPaths === current.expandedPaths
+ ? current
+ : { ...current, expandedPaths: new Set(expandedPaths) };
+ }),
+ [setDirectories],
+ );
+
return {
+ revealSelection,
+ expandedPaths: directories.expandedPaths,
+ setExpandedPaths,
+ selectedPath: directories.selectedPath,
+ selectPath: (selectedPath: string) =>
+ updateDirectories((current) => ({ ...current, selectedPath })),
entries: snapshot.entries,
searchResultPaths: snapshot.searchResultPaths,
- isRefreshing: refreshingDirectories === directories,
+ isRefreshing: directories.isRefreshing,
error:
root.error ??
(searching ? search.error : null) ??
[...directories.errors].find(([path]) => snapshot.reachableDirectories.has(path))?.[1] ??
null,
isPending:
- root.isPending ||
- directories.pending.size > 0 ||
- (searching && (query !== debouncedQuery || search.isPending)),
- searchTruncated: searching && (search.data?.truncated ?? false),
+ !missingRoot &&
+ (root.isPending ||
+ directories.loading.size > 0 ||
+ (searching && (query !== debouncedQuery || search.isPending))),
+ searchTruncated: !missingRoot && searching && (search.data?.truncated ?? false),
loadedDirectories: new Set(directories.entries.keys()),
- loadingDirectories: new Set(directories.pending.keys()),
- loadDirectory,
+ loadingDirectories: directories.loading,
+ loadDirectory: (path: string, retry = false) =>
+ loadDirectory(path, retry && directories.errors.has(path)),
refresh,
};
}
diff --git a/apps/mobile/src/state/query.ts b/apps/mobile/src/state/query.ts
index ad8a0f2cdf9..b5d5b6a6a1a 100644
--- a/apps/mobile/src/state/query.ts
+++ b/apps/mobile/src/state/query.ts
@@ -9,7 +9,9 @@ const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(fals
export interface EnvironmentQueryView<A> {
readonly data: A | null;
+ readonly successResult: AsyncResult.Success<A, unknown> | null;
readonly error: string | null;
+ readonly failure: unknown;
readonly isPending: boolean;
readonly isSuccess: boolean;
readonly refresh: () => void;
@@ -30,6 +32,9 @@ export function useEnvironmentQuery<A, E>(
const refresh = useAtomRefresh(selectedAtom);
return {
data: Option.getOrNull(AsyncResult.value(result)),
+ // Data may be structurally shared; only a settled success proves a new response.
+ successResult: result._tag === "Success" && !result.waiting ? result : null,
+ failure: result._tag === "Failure" ? Cause.squash(result.cause) : null,
error: result._tag === "Failure" ? formatError(result.cause) : null,
isPending: atom !== null && result.waiting,
isSuccess: result._tag === "Success",
diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts
index 8eaaaa1604f..e1509e98e11 100644
--- a/apps/mobile/vite.config.ts
+++ b/apps/mobile/vite.config.ts
@@ -4,6 +4,7 @@ import { defineConfig, normalizePath } from "vite-plus";
import "vite-plus/test/config";
const reactTests = [
+ "src/features/files/useFileTreeEntries.test.tsx",
"src/features/projects/AddProjectScreen.test.ts",
"src/lib/useMediaVideoPlayback.test.tsx",
"src/features/pull-requests/usePullRequestEnvironmentFallback.test.tsx",