Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: support S3, GCS, Azure paths in mo.ui.file_browser() (#4087)

Myles Scolnickddcc420f9628
diff --git a/frontend/src/plugins/impl/FileBrowserPlugin.tsx b/frontend/src/plugins/impl/FileBrowserPlugin.tsx
index cdb78f0022..373a298e87 100644
--- a/frontend/src/plugins/impl/FileBrowserPlugin.tsx
+++ b/frontend/src/plugins/impl/FileBrowserPlugin.tsx
@@ -22,6 +22,7 @@ import { cn } from "@/utils/cn";
import { Label } from "@/components/ui/label";
import { PluralWords } from "@/utils/pluralize";
import { useInternalStateWithSync } from "@/hooks/useInternalStateWithSync";
+import { getProtocolAndParentDirectories } from "@/utils/pathUtils";
/**
* Arguments for a file browser component.
@@ -50,14 +51,12 @@ interface Data {
* @param path - File path
* @param name - File name
* @param is_directory - Whether file is a directory or not
- * @param is_marimo_file - Whether file is a marimo file or not
*/
interface FileInfo {
id: string;
path: string;
name: string;
is_directory: boolean;
- is_marimo_file: boolean;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
@@ -95,7 +94,6 @@ export const FileBrowserPlugin = createPlugin<S>("marimo-file-browser")
path: z.string(),
name: z.string(),
is_directory: z.boolean(),
- is_marimo_file: z.boolean(),
}),
),
}),
@@ -228,7 +226,6 @@ export const FileBrowser = ({
name: name,
path: path,
is_directory: isDirectory,
- is_marimo_file: false,
};
}
@@ -292,7 +289,7 @@ export const FileBrowser = ({
);
for (const file of files) {
- let filePath = pathBuilder.join(path, file.name);
+ let filePath = file.path;
if (filePath.startsWith("//")) {
filePath = filePath.slice(1) as FilePath;
@@ -363,20 +360,12 @@ export const FileBrowser = ({
//
// Assumes that path contains at least one delimiter, which is true
// only if this is an absolute path.
- const directories = path.split(delimiter).filter((x) => x !== "");
- directories.push(path);
-
- let parentDirectories = directories.map((dir, index) => {
- const dirList = directories.slice(0, index);
- return `/${dirList.join(delimiter)}`;
- });
-
- if (restrictNavigation) {
- parentDirectories = parentDirectories.filter((x) =>
- x.startsWith(initialPath),
- );
- }
- parentDirectories.reverse();
+ const { parentDirectories } = getProtocolAndParentDirectories(
+ path,
+ delimiter,
+ initialPath,
+ restrictNavigation,
+ );
const selectionKindLabel =
selectionMode === "all"
@@ -384,6 +373,7 @@ export const FileBrowser = ({
: selectionMode === "directory"
? PluralWords.of("folder")
: PluralWords.of("file");
+
const renderHeader = () => {
label = label ?? `Select ${selectionKindLabel.join(" and ", 2)}...`;
const labelText = <Label>{renderHTML({ html: label })}</Label>;
diff --git a/frontend/src/utils/pathUtils.test.ts b/frontend/src/utils/pathUtils.test.ts
new file mode 100644
index 0000000000..f03324b03f
--- /dev/null
+++ b/frontend/src/utils/pathUtils.test.ts
@@ -0,0 +1,82 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { getProtocolAndParentDirectories } from "./pathUtils";
+
+describe("getProtocolAndParentDirectories", () => {
+ it("should extract protocol and list parent directories correctly", () => {
+ const path = "http://example.com/folder/subfolder/";
+ const delimiter = "/";
+ const initialPath = "http://example.com/folder";
+ const restrictNavigation = true;
+
+ const { protocol, parentDirectories } = getProtocolAndParentDirectories(
+ path,
+ delimiter,
+ initialPath,
+ restrictNavigation,
+ );
+
+ expect(protocol).toBe("http://");
+ expect(parentDirectories).toEqual([
+ "http://example.com/folder/subfolder",
+ "http://example.com/folder",
+ ]);
+ });
+
+ it("should handle Google Cloud Storage paths", () => {
+ const path = "gs://bucket/folder/subfolder/";
+ const delimiter = "/";
+ const initialPath = "gs://bucket/folder";
+ const restrictNavigation = true;
+
+ const { protocol, parentDirectories } = getProtocolAndParentDirectories(
+ path,
+ delimiter,
+ initialPath,
+ restrictNavigation,
+ );
+
+ expect(protocol).toBe("gs://");
+ expect(parentDirectories).toEqual([
+ "gs://bucket/folder/subfolder",
+ "gs://bucket/folder",
+ ]);
+ });
+
+ it("should handle paths without protocol", () => {
+ const path = "/folder/subfolder/";
+ const delimiter = "/";
+ const initialPath = "/folder";
+ const restrictNavigation = false;
+
+ const { protocol, parentDirectories } = getProtocolAndParentDirectories(
+ path,
+ delimiter,
+ initialPath,
+ restrictNavigation,
+ );
+
+ expect(protocol).toBe("/");
+ expect(parentDirectories).toEqual(["/folder/subfolder", "/folder", "/"]);
+ });
+ it("should handle Windows paths", () => {
+ const path = "C:\\folder\\subfolder\\";
+ const delimiter = "\\";
+ const initialPath = "C:\\folder";
+ const restrictNavigation = false;
+
+ const { protocol, parentDirectories } = getProtocolAndParentDirectories(
+ path,
+ delimiter,
+ initialPath,
+ restrictNavigation,
+ );
+
+ expect(protocol).toBe("C:\\");
+ expect(parentDirectories).toEqual([
+ "C:\\folder\\subfolder",
+ "C:\\folder",
+ "C:\\",
+ ]);
+ });
+});
diff --git a/frontend/src/utils/pathUtils.ts b/frontend/src/utils/pathUtils.ts
new file mode 100644
index 0000000000..e1572a72ba
--- /dev/null
+++ b/frontend/src/utils/pathUtils.ts
@@ -0,0 +1,64 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+/**
+ * Get the protocol and parent directories of a path.
+ */
+export function getProtocolAndParentDirectories(
+ path: string,
+ delimiter: string,
+ initialPath: string,
+ restrictNavigation: boolean,
+) {
+ // Determine protocol (http://, gs://, C:\, or /)
+ const protocolMatch = path.match(/^[A-Za-z]+:\/\//);
+ const isWindowsPath = /^[A-Za-z]:\\/.test(path);
+ const protocol = protocolMatch
+ ? protocolMatch[0]
+ : isWindowsPath
+ ? path.slice(0, 3)
+ : "/";
+
+ // Remove protocol from path
+ const pathWithoutProtocol = isWindowsPath
+ ? path.slice(protocol.length)
+ : protocolMatch
+ ? path.slice(protocol.length)
+ : path;
+
+ // Split path into segments
+ const segments = pathWithoutProtocol.split(delimiter).filter(Boolean);
+
+ // Build parent directories from segments
+ let parentDirectories: string[] = [];
+
+ if (isWindowsPath) {
+ // Handle Windows paths differently
+ for (let i = segments.length; i >= 0; i--) {
+ const dirPath = protocol + segments.slice(0, i).join(delimiter);
+ parentDirectories.push(dirPath);
+ }
+ } else {
+ // Handle non-Windows paths
+ let currentPath = protocol;
+ for (let i = 0; i <= segments.length; i++) {
+ const dirPath = currentPath + segments.slice(0, i).join(delimiter);
+ parentDirectories.push(dirPath);
+
+ // Add delimiter if not already present
+ if (i < segments.length && !currentPath.endsWith(delimiter)) {
+ currentPath += delimiter;
+ }
+ }
+ // Reverse to get parent directories in descending order
+ parentDirectories.reverse();
+ }
+
+ // Filter to paths within initial path if navigation is restricted
+ if (restrictNavigation) {
+ parentDirectories = parentDirectories.filter((dir) =>
+ dir.startsWith(initialPath),
+ );
+ }
+
+ return { protocol, parentDirectories };
+}
diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.py
index 5c62eec343..6696cf2e2b 100644
--- a/marimo/_plugins/ui/__init__.py
+++ b/marimo/_plugins/ui/__init__.py
@@ -56,6 +56,7 @@ from marimo._plugins.ui._impl.dates import (
datetime,
)
from marimo._plugins.ui._impl.dictionary import dictionary
+from marimo._plugins.ui._impl.file_browser import file_browser
from marimo._plugins.ui._impl.from_anywidget import anywidget
from marimo._plugins.ui._impl.from_panel import panel
from marimo._plugins.ui._impl.input import (
@@ -64,7 +65,6 @@ from marimo._plugins.ui._impl.input import (
code_editor,
dropdown,
file,
- file_browser,
form,
multiselect,
number,
diff --git a/marimo/_plugins/ui/_impl/file_browser.py b/marimo/_plugins/ui/_impl/file_browser.py
new file mode 100644
index 0000000000..ffb4ba2ea0
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/file_browser.py
@@ -0,0 +1,271 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+from collections.abc import Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import (
+ Callable,
+ Final,
+ Optional,
+ TypedDict,
+ Union,
+)
+
+from marimo import _loggers
+from marimo._output.rich_help import mddoc
+from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._runtime.functions import Function
+
+LOGGER = _loggers.marimo_logger()
+
+
+@dataclass
+class ListDirectoryArgs:
+ path: str
+
+
+@dataclass
+class FileBrowserFileInfo:
+ id: str
+ path: Path
+ name: str
+ is_directory: bool
+
+
+class TypedFileBrowserFileInfo(TypedDict):
+ id: str
+ path: str
+ name: str
+ is_directory: bool
+
+
+@dataclass
+class ListDirectoryResponse:
+ files: list[TypedFileBrowserFileInfo]
+
+
+@mddoc
+class file_browser(
+ UIElement[list[TypedFileBrowserFileInfo], Sequence[FileBrowserFileInfo]]
+):
+ """File browser for browsing and selecting server-side files.
+ This element supports local files, S3, GCS, and Azure.
+
+ Examples:
+ Selecting multiple files:
+ ```python
+ file_browser = mo.ui.file_browser(
+ initial_path=Path("path/to/dir"), multiple=True
+ )
+
+ # Access the selected file path(s):
+ file_browser.path(index) # returns a Path object
+
+ # Get name of selected file(s)
+ file_browser.name(index)
+ ```
+
+ Connecting to an S3 (or GCS, Azure) bucket:
+ ```python
+ from cloudpathlib import S3Path
+
+ file_browser = mo.ui.file_browser(
+ initial_path=S3Path("s3://mybucket/mydir")
+ )
+
+ # Access the selected file path(s):
+ file_browser.path(index) # returns a S3Path object
+
+ # Read the contents of the selected file(s):
+ file_browser.path(index).read_text()
+ ```
+
+ Attributes:
+ value (Sequence[FileInfo]): A sequence of file paths representing selected
+ files.
+
+ Args:
+ initial_path (Union[str, Path, AnyPath], optional): Starting directory. Defaults to current
+ working directory.
+ If a string, it will be interpreted as a local path.
+ If a Path, it will be interpreted as a local path.
+ If a CloudPath (from cloudpathlib), such as S3Path, GCSPath, or AzurePath,
+ files will be loaded from the respective cloud storage bucket.
+ filetypes (Sequence[str], optional): The file types to display in each
+ directory; for example, filetypes=[".txt", ".csv"]. If None, all
+ files are displayed. Defaults to None.
+ selection_mode (str, optional): Either "file" or "directory". Defaults to
+ "file".
+ multiple (bool, optional): If True, allow the user to select multiple
+ files. Defaults to True.
+ restrict_navigation (bool, optional): If True, prevent the user from
+ navigating any level above the given path. Defaults to False.
+ limit (int, optional): Maximum number of files to display. Defaults to 50.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Callable[[Sequence[FileInfo]], None], optional): Optional
+ callback to run when this element's value changes. Defaults to None.
+ """
+
+ _name: Final[str] = "marimo-file-browser"
+
+ def __init__(
+ self,
+ initial_path: Union[str, Path] = "",
+ filetypes: Optional[Sequence[str]] = None,
+ selection_mode: str = "file",
+ multiple: bool = True,
+ restrict_navigation: bool = False,
+ *,
+ limit: int = 50,
+ label: str = "",
+ on_change: Optional[
+ Callable[[Sequence[FileBrowserFileInfo]], None]
+ ] = None,
+ ) -> None:
+ if (
+ selection_mode != "file"
+ and selection_mode != "directory"
+ and selection_mode != "all"
+ ):
+ raise ValueError(
+ "Invalid argument for selection_mode. "
+ + "Must be either 'file' or 'directory'."
+ )
+ else:
+ self.selection_mode = selection_mode
+
+ if not initial_path:
+ initial_path = Path.cwd()
+ elif isinstance(initial_path, str):
+ initial_path = Path(initial_path)
+
+ # frontend plugin can't handle relative paths
+ initial_path = initial_path.resolve()
+ # initial path must be a directory
+ if not initial_path.is_dir():
+ raise ValueError(
+ f"Initial path {initial_path} is not a directory."
+ )
+
+ self.filetypes: set[str] = set(filetypes) if filetypes else set()
+ self.restrict_navigation = restrict_navigation
+ self.initial_path: Path = initial_path
+ self.limit = limit
+
+ self.path_cls: type[Path]
+ if isinstance(initial_path, str):
+ self.path_cls = Path
+ else:
+ self.path_cls = initial_path.__class__
+
+ super().__init__(
+ component_name=file_browser._name,
+ initial_value=[],
+ label=label,
+ args={
+ "initial-path": str(initial_path),
+ "selection-mode": selection_mode,
+ "filetypes": filetypes if filetypes is not None else [],
+ "multiple": multiple,
+ "restrict-navigation": restrict_navigation,
+ },
+ functions=(
+ Function(
+ name="list_directory",
+ arg_cls=ListDirectoryArgs,
+ function=self._list_directory,
+ ),
+ ),
+ on_change=on_change,
+ )
+
+ def _list_directory(
+ self, args: ListDirectoryArgs
+ ) -> ListDirectoryResponse:
+ # When navigation is restricted, the navigated-to path cannot be
+ # be a parent of the initial path
+
+ # Convert to original class of initial_path
+ # so that it works with anything that extended Path
+ # such as CloudPath
+ path = self.path_cls(args.path)
+
+ if self.restrict_navigation and path in self.initial_path.parents:
+ raise RuntimeError(
+ "Navigation is restricted; navigating to a "
+ "parent of initial path is not allowed."
+ )
+
+ files: list[TypedFileBrowserFileInfo] = []
+ for file in path.iterdir():
+ _, extension = os.path.splitext(file.name)
+
+ # Skip non-directories if selection mode is directory
+ if self.selection_mode == "directory" and not file.is_dir():
+ continue
+
+ # Skip non-matching file types
+ if self.filetypes and not file.is_dir():
+ if extension not in self.filetypes:
+ continue
+
+ files.append(
+ TypedFileBrowserFileInfo(
+ id=str(file),
+ path=str(file),
+ name=file.name,
+ is_directory=file.is_dir(),
+ )
+ )
+
+ if len(files) >= self.limit:
+ break
+
+ return ListDirectoryResponse(files)
+
+ def _convert_value(
+ self, value: list[TypedFileBrowserFileInfo]
+ ) -> Sequence[FileBrowserFileInfo]:
+ return tuple(
+ FileBrowserFileInfo(
+ id=file["id"],
+ name=file["name"],
+ path=self.path_cls(file["path"]),
+ is_directory=file["is_directory"],
+ )
+ for file in value
+ )
+
+ def name(self, index: int = 0) -> Optional[str]:
+ """Get file name at index.
+
+ Args:
+ index (int, optional): Index of the file to get the name from.
+ Defaults to 0.
+
+ Returns:
+ Optional[str]: The name of the file at the specified index,
+ or None if index is out of range.
+ """
+ if not self.value or index >= len(self.value):
+ return None
+ else:
+ return self.value[index].name
+
+ def path(self, index: int = 0) -> Optional[Path]:
+ """Get file path at index.
+
+ Args:
+ index (int, optional): Index of the file to get the path from.
+ Defaults to 0.
+
+ Returns:
+ Optional[str]: The path of the file at the specified index,
+ or None if index is out of range.
+ """
+ if not self.value or index >= len(self.value):
+ return None
+ else:
+ return self.value[index].path
diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.py
index 9479cbc9e4..31d1d7b850 100644
--- a/marimo/_plugins/ui/_impl/input.py
+++ b/marimo/_plugins/ui/_impl/input.py
@@ -3,8 +3,6 @@ from __future__ import annotations
import base64
import dataclasses
-import os
-import pathlib
import sys
import traceback
from collections.abc import Sequence
@@ -36,8 +34,6 @@ from marimo._plugins.validators import (
warn_js_safe_number,
)
from marimo._runtime.functions import Function
-from marimo._server.files.os_file_system import OSFileSystem
-from marimo._server.models.files import FileInfo
LOGGER = _loggers.marimo_logger()
@@ -1366,195 +1362,6 @@ class file(UIElement[list[tuple[str, str]], Sequence[FileUploadResults]]):
return self.value[index].contents
-@dataclass
-class ListDirectoryArgs:
- path: str
-
-
-@dataclass
-class ListDirectoryResponse:
- files: list[FileInfo]
-
-
-@mddoc
-class file_browser(UIElement[list[dict[str, Any]], Sequence[FileInfo]]):
- """File browser for browsing and selecting server-side files.
-
- Examples:
- Selecting multiple files:
- ```python
- file_browser = mo.ui.file_browser(
- initial_path="path/to/dir", multiple=True
- )
-
- # Access the selected file path(s):
- file_browser.path(index)
-
- # Get name of selected file(s)
- file_browser.name(index)
- ```
-
- Attributes:
- value (Sequence[FileInfo]): A sequence of file paths representing selected
- files.
-
- Args:
- initial_path (str, optional): Starting directory. Defaults to current
- working directory.
- filetypes (Sequence[str], optional): The file types to display in each
- directory; for example, filetypes=[".txt", ".csv"]. If None, all
- files are displayed. Defaults to None.
- selection_mode (str, optional): Either "file" or "directory". Defaults to
- "file".
- multiple (bool, optional): If True, allow the user to select multiple
- files. Defaults to True.
- restrict_navigation (bool, optional): If True, prevent the user from
- navigating any level above the given path. Defaults to False.
- label (str, optional): Markdown label for the element. Defaults to "".
- on_change (Callable[[Sequence[FileInfo]], None], optional): Optional
- callback to run when this element's value changes. Defaults to None.
- """
-
- _name: Final[str] = "marimo-file-browser"
-
- def __init__(
- self,
- initial_path: str = "",
- filetypes: Optional[Sequence[str]] = None,
- selection_mode: str = "file",
- multiple: bool = True,
- restrict_navigation: bool = False,
- *,
- label: str = "",
- on_change: Optional[Callable[[Sequence[FileInfo]], None]] = None,
- ) -> None:
- self.filetypes = filetypes
-
- if (
- selection_mode != "file"
- and selection_mode != "directory"
- and selection_mode != "all"
- ):
- raise ValueError(
- "Invalid argument for selection_mode. "
- + "Must be either 'file' or 'directory'."
- )
- else:
- self.selection_mode = selection_mode
-
- if not initial_path:
- initial_path = os.getcwd()
-
- # frontend plugin can't handle relative paths
- initial_path = os.path.realpath(os.path.expanduser(initial_path))
- # initial path must be a directory
- if not os.path.isdir(initial_path):
- raise ValueError(
- f"Initial path {initial_path} is not a directory."
- )
-
- self.restrict_navigation = restrict_navigation
- self.initial_path = initial_path
- super().__init__(
- component_name=file_browser._name,
- initial_value=[],
- label=label,
- args={
- "initial-path": initial_path,
- "selection-mode": selection_mode,
- "filetypes": filetypes if filetypes is not None else [],
- "multiple": multiple,
- "restrict-navigation": restrict_navigation,
- },
- functions=(
- Function(
- name="list_directory",
- arg_cls=ListDirectoryArgs,
- function=self._list_directory,
- ),
- ),
- on_change=on_change,
- )
-
- def _list_directory(
- self, args: ListDirectoryArgs
- ) -> ListDirectoryResponse:
- # When navigation is restricted, the navigated-to path cannot be
- # be a parent of the initial path
- if (
- self.restrict_navigation
- and pathlib.Path(args.path)
- in pathlib.Path(self.initial_path).parents
- ):
- raise RuntimeError(
- "Navigation is restricted; navigating to a "
- "parent of initial path is not allowed."
- )
-
- files = []
- files_in_path = OSFileSystem().list_files(args.path)
-
- for file in files_in_path:
- _, extension = os.path.splitext(file.name)
-
- if self.selection_mode == "directory" and not file.is_directory:
- continue
-
- if self.filetypes and not file.is_directory:
- if extension not in self.filetypes:
- continue
-
- files.append(file)
-
- return ListDirectoryResponse(files)
-
- def _convert_value(
- self, value: list[dict[str, Any]]
- ) -> Sequence[FileInfo]:
- return tuple(
- FileInfo(
- id=file["id"],
- name=file["name"],
- path=file["path"],
- is_directory=file["is_directory"],
- is_marimo_file=file["is_marimo_file"],
- )
- for file in value
- )
-
- def name(self, index: int = 0) -> Optional[str]:
- """Get file name at index.
-
- Args:
- index (int, optional): Index of the file to get the name from.
- Defaults to 0.
-
- Returns:
- Optional[str]: The name of the file at the specified index,
- or None if index is out of range.
- """
- if not self.value or index >= len(self.value):
- return None
- else:
- return self.value[index].name
-
- def path(self, index: int = 0) -> Optional[str]:
- """Get file path at index.
-
- Args:
- index (int, optional): Index of the file to get the path from.
- Defaults to 0.
-
- Returns:
- Optional[str]: The path of the file at the specified index,
- or None if index is out of range.
- """
- if not self.value or index >= len(self.value):
- return None
- else:
- return self.value[index].path
-
-
T = TypeVar("T")
diff --git a/marimo/_smoke_tests/files/cloudpath_file_browser.py b/marimo/_smoke_tests/files/cloudpath_file_browser.py
new file mode 100644
index 0000000000..0c1c76f076
--- /dev/null
+++ b/marimo/_smoke_tests/files/cloudpath_file_browser.py
@@ -0,0 +1,76 @@
+import marimo
+
+__generated_with = "0.11.19"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+def _(mo):
+ file_browser = mo.ui.file_browser()
+ file_browser
+ return (file_browser,)
+
+
+def _():
+ BUCKET = "gs://public-datasets-deepmind-alphafold-v4/"
+ # BUCKET = "s3://"
+ # BUCKET = "az://bucket_name/"
+ return (BUCKET,)
+
+
+def _(BUCKET):
+ from cloudpathlib import CloudPath
+
+ # dispatches to S3Path based on prefix
+ root_dir = CloudPath(BUCKET)
+ root_dir
+ return CloudPath, root_dir
+
+
+def _(cloud_file_browser):
+ cloud_file_browser.value
+ return
+
+
+def _(mo, root_dir):
+ cloud_file_browser = mo.ui.file_browser(initial_path=root_dir, limit=10)
+ cloud_file_browser
+ return (cloud_file_browser,)
+
+
+def _(cloud_file_browser):
+ [f.path.is_dir() for f in cloud_file_browser.value]
+ return
+
+
+def _(cloud_file_browser):
+ [type(f.path) for f in cloud_file_browser.value]
+ return
+
+
+def _(cloud_file_browser):
+ [f.path for f in cloud_file_browser.value]
+ return
+
+
+def _(cloud_file_browser):
+ [f.path.read_text() for f in cloud_file_browser.value]
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_plugins/ui/_impl/test_file_browser.py b/tests/_plugins/ui/_impl/test_file_browser.py
new file mode 100644
index 0000000000..ecf2c55bdc
--- /dev/null
+++ b/tests/_plugins/ui/_impl/test_file_browser.py
@@ -0,0 +1,110 @@
+from __future__ import annotations
+
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from marimo._plugins.ui._impl.file_browser import (
+ FileBrowserFileInfo,
+ ListDirectoryArgs,
+ ListDirectoryResponse,
+ file_browser,
+)
+
+
+def test_file_browser_init() -> None:
+ # Use a temporary directory for testing
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fb = file_browser(initial_path=temp_dir)
+ assert isinstance(fb.initial_path, Path)
+ assert str(fb.initial_path) == str(Path(temp_dir).resolve())
+ assert fb.selection_mode == "file"
+ assert fb.filetypes == set()
+ assert fb.restrict_navigation is False
+
+ # Test with custom filetypes
+ custom_filetypes = [".txt", ".csv"]
+ fb = file_browser(
+ initial_path=temp_dir,
+ filetypes=custom_filetypes,
+ selection_mode="directory",
+ restrict_navigation=True,
+ )
+ assert fb.initial_path == Path(temp_dir).resolve()
+ assert fb.filetypes == set(custom_filetypes)
+ assert fb.selection_mode == "directory"
+ assert fb.restrict_navigation is True
+
+
+def test_list_directory() -> None:
+ fb = file_browser(
+ initial_path=Path.cwd(), filetypes=[".txt"], selection_mode="file"
+ )
+ response = fb._list_directory(ListDirectoryArgs(path=str(Path.cwd())))
+ assert isinstance(response, ListDirectoryResponse)
+ for file_info in response.files:
+ assert file_info["is_directory"] or file_info["path"].endswith(
+ tuple(fb.filetypes)
+ )
+
+
+def test_navigation_restriction() -> None:
+ fb = file_browser(initial_path=Path.cwd(), restrict_navigation=True)
+ with pytest.raises(RuntimeError) as e:
+ fb._list_directory(ListDirectoryArgs(path=str(Path.cwd().parent)))
+ assert "Navigation is restricted" in str(e.value)
+
+
+def test_name_method() -> None:
+ fb = file_browser(initial_path=Path.cwd())
+ fb._value = [
+ FileBrowserFileInfo(
+ id="1",
+ path="/some/path/file.txt",
+ name="file.txt",
+ is_directory=False,
+ )
+ ]
+ assert fb.name(0) == "file.txt"
+ assert fb.name(1) is None
+
+
+def test_path_method() -> None:
+ fb = file_browser(initial_path=Path.cwd())
+ fb._value = [
+ FileBrowserFileInfo(
+ id="1",
+ path="/some/path/file.txt",
+ name="file.txt",
+ is_directory=False,
+ )
+ ]
+ assert fb.path(0) == "/some/path/file.txt"
+ assert fb.path(1) is None
+
+
+ sys.version_info <= (3, 12), reason="Only works with Python 3.12+"
+)
+def test_extended_path_class(tmp_path: Path) -> None:
+ class CustomPath(Path):
+ pass
+
+ (tmp_path / "file.txt").touch()
+
+ fb = file_browser(initial_path=CustomPath(tmp_path), limit=1)
+ response = fb._list_directory(
+ ListDirectoryArgs(path=str(tmp_path)),
+ )
+ assert isinstance(response, ListDirectoryResponse)
+ for file_info in response.files:
+ assert isinstance(file_info["path"], str)
+
+ # Convert the value
+ value = fb._convert_value(response.files)
+ assert isinstance(value, tuple)
+ assert len(value) == 1
+ assert isinstance(value[0], FileBrowserFileInfo)
+ assert isinstance(value[0].path, CustomPath)