Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { afterEach, describe, expect, test } from "vitest";
import { HttpResponse, http, server } from "~/test/msw/server";
import { cleanup, render, waitFor } from "~/test/test-utils";
import { LocalFileBrowser } from "../local-file-browser";

afterEach(() => {
cleanup();
});

describe("LocalFileBrowser", () => {
test("keeps Windows drive roots as host paths", async () => {
const requests: string[] = [];

server.use(
http.get("/api/v1/volumes/filesystem/browse", ({ request }) => {
const url = new URL(request.url);
requests.push(url.searchParams.get("path") ?? "");

return HttpResponse.json({
directories: [],
path: "C:\\",
});
}),
);

render(<LocalFileBrowser initialPath={"C:\\"} />);

await waitFor(() => {
expect(requests).toEqual(["C:\\"]);
});
});

test("uses the trimmed initial path for the first browse request", async () => {
const requests: string[] = [];

server.use(
http.get("/api/v1/volumes/filesystem/browse", ({ request }) => {
const url = new URL(request.url);
requests.push(url.searchParams.get("path") ?? "");

return HttpResponse.json({
directories: [],
path: "/tmp",
});
}),
);

render(<LocalFileBrowser initialPath={" /tmp "} />);

await waitFor(() => {
expect(requests).toEqual(["/tmp"]);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import type { ComponentProps } from "react";
import { afterEach, describe, expect, test } from "vitest";
import { HttpResponse, http, server } from "~/test/msw/server";
import { cleanup, fireEvent, render, screen, userEvent, waitFor, within } from "~/test/test-utils";
import { VolumeFileBrowser } from "../volume-file-browser";

type VolumeFilesRequest = {
shortId: string;
path: string | null;
offset: string | null;
};

const renderVolumeFileBrowser = (props: Partial<ComponentProps<typeof VolumeFileBrowser>> = {}) => {
return render(<VolumeFileBrowser volumeId="volume-1" {...props} />);
};

afterEach(() => {
cleanup();
});

describe("VolumeFileBrowser", () => {
test("returns literal selected paths when the volume API uses encoded navigation paths", async () => {
server.use(
http.get("/api/v1/volumes/:shortId/files", () => {
return HttpResponse.json({
files: [{ name: "movies [1]", path: "/movies%20%5B1%5D", type: "directory" }],
path: "/",
offset: 0,
limit: 500,
total: 1,
hasMore: false,
});
}),
);

let selectedPaths: Set<string> | undefined;
renderVolumeFileBrowser({
withCheckboxes: true,
onSelectionChange: (paths) => {
selectedPaths = paths;
},
});

const row = await screen.findByRole("button", { name: "movies [1]" });
await userEvent.click(within(row).getByRole("checkbox"));

expect(selectedPaths ? Array.from(selectedPaths) : []).toEqual(["/movies [1]"]);
});

test("uses encoded paths when fetching an expanded folder's children", async () => {
const requests: VolumeFilesRequest[] = [];

server.use(
http.get("/api/v1/volumes/:shortId/files", ({ params, request }) => {
const url = new URL(request.url);
const requestPath = url.searchParams.get("path");
requests.push({
shortId: String(params.shortId),
path: requestPath,
offset: url.searchParams.get("offset"),
});

if (requestPath === "/movies%20%5B1%5D") {
return HttpResponse.json({
files: [{ name: "clip.txt", path: "/movies%20%5B1%5D/clip.txt", type: "file" }],
path: "/movies%20%5B1%5D",
offset: 0,
limit: 500,
total: 1,
hasMore: false,
});
}

return HttpResponse.json({
files: [{ name: "movies [1]", path: "/movies%20%5B1%5D", type: "directory" }],
path: "/",
offset: 0,
limit: 500,
total: 1,
hasMore: false,
});
}),
);

renderVolumeFileBrowser();

const row = await screen.findByRole("button", { name: "movies [1]" });
const expandIcon = row.querySelector("svg");
if (!expandIcon) {
throw new Error("Expected expand icon for folder row");
}
fireEvent.click(expandIcon);

await waitFor(() => {
expect(requests).toEqual([
{ shortId: "volume-1", path: null, offset: null },
{ shortId: "volume-1", path: "/movies%20%5B1%5D", offset: null },
]);
});
});
});
5 changes: 2 additions & 3 deletions app/client/components/file-browsers/local-file-browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { browseFilesystemOptions } from "~/client/api-client/@tanstack/react-que
import { FileBrowser, type FileBrowserUiProps } from "~/client/components/file-browsers/file-browser";
import { useFileBrowser } from "~/client/hooks/use-file-browser";
import { parseError } from "~/client/lib/errors";
import { normalizeAbsolutePath } from "@zerobyte/core/utils";
import { logger } from "~/client/lib/logger";

type LocalFileBrowserProps = FileBrowserUiProps & {
Expand All @@ -13,10 +12,10 @@ type LocalFileBrowserProps = FileBrowserUiProps & {

export const LocalFileBrowser = ({ initialPath = "/", enabled = true, ...uiProps }: LocalFileBrowserProps) => {
const queryClient = useQueryClient();
const normalizedInitialPath = normalizeAbsolutePath(initialPath);
const browsePath = initialPath.trim() || "/";

const { data, isLoading, error } = useQuery({
...browseFilesystemOptions({ query: { path: normalizedInitialPath } }),
...browseFilesystemOptions({ query: { path: browsePath } }),
enabled,
});

Expand Down
11 changes: 11 additions & 0 deletions app/client/components/file-browsers/volume-file-browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ type VolumeFileBrowserProps = FileBrowserUiProps & {
enabled?: boolean;
};

const mapVolumePathSegments = (volumePath: string, transform: (segment: string) => string) => {
const segments = volumePath.split("/").filter(Boolean).map(transform);
return segments.length ? `/${segments.join("/")}` : "/";
};

const volumePathTransform = {
strip: (volumePath: string) => mapVolumePathSegments(volumePath, decodeURIComponent),
add: (volumePath: string) => mapVolumePathSegments(volumePath, encodeURIComponent),
};

export const VolumeFileBrowser = ({ volumeId, enabled = true, ...uiProps }: VolumeFileBrowserProps) => {
const queryClient = useQueryClient();

Expand Down Expand Up @@ -39,6 +49,7 @@ export const VolumeFileBrowser = ({ volumeId, enabled = true, ...uiProps }: Volu
)
.catch((e) => logger.error(e));
},
pathTransform: volumePathTransform,
});

return (
Expand Down
6 changes: 5 additions & 1 deletion apps/agent/src/commands/__tests__/volume.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ test("runs backend-backed volume commands on the agent host", async () => {
commandId: "command-1",
command: {
name: "volume.mount",
volume: { id: 1, config: { backend: "directory", path: "/tmp/source" }, provisioningId: undefined },
volume: {
id: 1,
config: { backend: "directory", path: "/tmp/source" },
provisioningId: undefined,
},
},
}),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,4 +199,12 @@ describe("backup path options", () => {
expect(options.includePaths).toEqual([path.join(volumePath, "movies [1]")]);
expect(options.includePatterns).toEqual([path.join(volumePath, "**/*.txt")]);
});

test("treats selected include paths as literal path values", () => {
const volumePath = "/var/lib/zerobyte/volumes/vol123/_data";

const options = createOptions(createPathOptions({ includePaths: ["/movies%20%5B1%5D"] }), volumePath);

expect(options.includePaths).toEqual([path.join(volumePath, "movies%20%5B1%5D")]);
});
});
44 changes: 43 additions & 1 deletion apps/agent/src/volume-host/__tests__/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,48 @@ test("listVolumeFiles returns sorted paginated entries inside the volume", async
expect(result.files[1]).toMatchObject({ path: "/b-file.txt", type: "file", size: 5 });
});

test("listVolumeFiles treats an empty string as the volume root", async () => {
const volume = await createDirectoryVolume();
await fs.mkdir(path.join(tempRoot!, "logs"));

const result = await listVolumeFiles(volume, "", 0, 10);

expect(result.path).toBe("/");
expect(result.files[0]).toMatchObject({ name: "logs", path: "/logs", type: "directory" });
});

test("listVolumeFiles preserves literal POSIX path segment characters", async () => {
const volume = await createDirectoryVolume();
await fs.mkdir(path.join(tempRoot!, "movies [1]"));
await fs.writeFile(path.join(tempRoot!, "movies [1]", "clip one.txt"), "hello");
await fs.mkdir(path.join(tempRoot!, "foo\\bar"));
await fs.writeFile(path.join(tempRoot!, "foo\\bar", "nested.txt"), "hello");
await fs.mkdir(path.join(tempRoot!, "foo%2Fbar"));

const result = await listVolumeFiles(volume, undefined, 0, 10);

expect(result.files).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "movies [1]", path: "/movies%20%5B1%5D" }),
expect.objectContaining({ name: "foo\\bar", path: "/foo%5Cbar" }),
expect.objectContaining({ name: "foo%2Fbar", path: "/foo%252Fbar" }),
]),
);

const spacedNested = await listVolumeFiles(volume, "/movies%20%5B1%5D", 0, 10);

expect(spacedNested.path).toBe("/movies%20%5B1%5D");
expect(spacedNested.files[0]).toMatchObject({
name: "clip one.txt",
path: "/movies%20%5B1%5D/clip%20one.txt",
});

const nested = await listVolumeFiles(volume, "/foo%5Cbar", 0, 10);

expect(nested.path).toBe("/foo%5Cbar");
expect(nested.files[0]).toMatchObject({ name: "nested.txt", path: "/foo%5Cbar/nested.txt" });
});

test("listVolumeFiles rejects traversal outside the volume", async () => {
const volume = await createDirectoryVolume();

Expand All @@ -62,5 +104,5 @@ test("listVolumeFiles rejects traversal outside the volume", async () => {
test("listVolumeFiles reports missing directories consistently", async () => {
const volume = await createDirectoryVolume();

await expect(listVolumeFiles(volume, "missing", 0, 10)).rejects.toThrow("Directory not found");
await expect(listVolumeFiles(volume, "/missing", 0, 10)).rejects.toThrow("Directory not found");
});
Loading