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.

feat: add smart limits and file count display to ui.file_browser (#5882)

Anirudh Dagarbf654a776524
diff --git a/frontend/src/plugins/impl/FileBrowserPlugin.tsx b/frontend/src/plugins/impl/FileBrowserPlugin.tsx
index d1cb649c91..f673c06f0c 100644
--- a/frontend/src/plugins/impl/FileBrowserPlugin.tsx
+++ b/frontend/src/plugins/impl/FileBrowserPlugin.tsx
@@ -64,6 +64,8 @@ interface FileInfo {
type PluginFunctions = {
list_directory: (req: { path: string }) => Promise<{
files: FileInfo[];
+ total_count: number;
+ is_truncated: boolean;
}>;
};
@@ -97,6 +99,8 @@ export const FileBrowserPlugin = createPlugin<S>("marimo-file-browser")
is_directory: z.boolean(),
}),
),
+ total_count: z.number(),
+ is_truncated: z.boolean(),
}),
),
})
@@ -447,6 +451,15 @@ export const FileBrowser = ({
</option>
))}
</NativeSelect>
+
+ {data && typeof data.total_count === "number" && (
+ <div className="text-xs text-muted-foreground mt-1 px-1">
+ {data.is_truncated
+ ? `Showing ${files.length} of ${data.total_count} items`
+ : `${data.total_count} ${data.total_count === 1 ? "item" : "items"}`}
+ </div>
+ )}
+
<div
className="mt-3 overflow-y-auto w-full border"
style={{ height: "14rem" }}
diff --git a/marimo/_plugins/ui/_impl/file_browser.py b/marimo/_plugins/ui/_impl/file_browser.py
index 396aa70ad6..bbaee9a158 100644
--- a/marimo/_plugins/ui/_impl/file_browser.py
+++ b/marimo/_plugins/ui/_impl/file_browser.py
@@ -47,6 +47,8 @@ class TypedFileBrowserFileInfo(TypedDict):
@dataclass
class ListDirectoryResponse:
files: list[TypedFileBrowserFileInfo]
+ total_count: int
+ is_truncated: bool = False # Whether results were truncated due to limit
@mddoc
@@ -120,7 +122,9 @@ class file_browser(
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.
+ limit (int, optional): Maximum number of files to display.
+ If None (default), automatically chooses 50 for cloud storage (S3, GCS, Azure)
+ or 10000 for local filesystems. Set explicitly to override defaults.
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.
@@ -136,7 +140,7 @@ class file_browser(
multiple: bool = True,
restrict_navigation: bool = False,
*,
- limit: int = 50,
+ limit: Optional[int] = None,
label: str = "",
on_change: Optional[
Callable[[Sequence[FileBrowserFileInfo]], None]
@@ -161,7 +165,6 @@ class file_browser(
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):
@@ -169,6 +172,16 @@ class file_browser(
else:
self._path_cls = initial_path.__class__
+ # Smart default limit based on path type
+ if limit is None:
+ # Check if it's a cloud path
+ if self._path_cls.__module__.startswith("cloudpathlib"):
+ limit = 50 # Conservative for cloud storage
+ else:
+ limit = 10000 # High limit for local filesystems
+
+ self._limit = limit
+
super().__init__(
component_name=file_browser._name,
initial_value=[],
@@ -221,9 +234,15 @@ class file_browser(
folders: list[TypedFileBrowserFileInfo] = []
files: list[TypedFileBrowserFileInfo] = []
- for file in path.iterdir():
+ # Sort based on natural sort (alpha, then num)
+ all_file_paths = sorted(
+ list(path.iterdir()), key=lambda f: natural_sort(f.name)
+ )
+ is_truncated = False
+
+ for files_examined, file in enumerate(all_file_paths, 1):
extension = file.suffix
- is_directory = file.is_dir()
+ is_directory = file.is_dir() # Expensive call for cloud paths
# Skip non-directories if selection mode is directory
if self._selection_mode == "directory" and not is_directory:
@@ -247,18 +266,18 @@ class file_browser(
files.append(file_info)
if len(folders) + len(files) >= self._limit:
+ # handles the case where limit equals exactly the number of items
+ is_truncated = files_examined < len(all_file_paths)
break
- def natural_sort_info(
- info: TypedFileBrowserFileInfo,
- ) -> list[Union[int, str]]:
- return natural_sort(info["name"])
+ # Display folders first, then files
+ all_files = folders + files
- # Sort folders then files, based on natural sort (alpha, then num)
- all_files = sorted(folders, key=natural_sort_info) + sorted(
- files, key=natural_sort_info
+ return ListDirectoryResponse(
+ files=all_files,
+ total_count=len(all_file_paths),
+ is_truncated=is_truncated,
)
- return ListDirectoryResponse(all_files)
def _convert_value(
self, value: list[TypedFileBrowserFileInfo]
diff --git a/tests/_plugins/ui/_impl/test_file_browser.py b/tests/_plugins/ui/_impl/test_file_browser.py
index 8e2830d1eb..8ac2a73466 100644
--- a/tests/_plugins/ui/_impl/test_file_browser.py
+++ b/tests/_plugins/ui/_impl/test_file_browser.py
@@ -45,6 +45,11 @@ def test_list_directory() -> None:
)
response = fb._list_directory(ListDirectoryArgs(path=str(Path.cwd())))
assert isinstance(response, ListDirectoryResponse)
+ assert isinstance(response.total_count, int)
+ assert isinstance(response.is_truncated, bool)
+ assert hasattr(response, "total_count")
+ assert hasattr(response, "is_truncated")
+
for file_info in response.files:
assert file_info["is_directory"] or file_info["path"].endswith(
tuple(fb._filetypes)
@@ -239,3 +244,93 @@ def test_validation() -> None:
with pytest.raises(ValueError) as e:
file_browser(initial_path="invalid", selection_mode="invalid")
assert "Value must be one of" in str(e.value)
+
+
+def test_limit_arg(tmp_path: Path) -> None:
+ """Test limit argument behavior: defaults and explicit overrides."""
+ fb_default = file_browser(initial_path=tmp_path)
+ assert fb_default._limit == 10000 # High limit for local filesystem
+
+ fb_custom = file_browser(initial_path=tmp_path, limit=25)
+ assert fb_custom._limit == 25
+
+ fb_zero = file_browser(initial_path=tmp_path, limit=0)
+ assert fb_zero._limit == 0
+
+
+def test_is_truncated_true_when_limit_exceeded(tmp_path: Path) -> None:
+ """Test is_truncated=True when directory has more files than limit."""
+ # Create more files than the limit
+ for i in range(10):
+ (tmp_path / f"file{i}.txt").touch()
+
+ fb = file_browser(initial_path=tmp_path, limit=5)
+ response = fb._list_directory(ListDirectoryArgs(path=str(tmp_path)))
+
+ assert response.is_truncated is True
+ assert response.total_count == 10
+ assert len(response.files) == 5
+
+
+def test_is_truncated_false_when_under_limit(tmp_path: Path) -> None:
+ """Test is_truncated=False when directory has fewer files than limit."""
+ # Create fewer files than the limit
+ for i in range(3):
+ (tmp_path / f"file{i}.txt").touch()
+
+ fb = file_browser(initial_path=tmp_path, limit=5)
+ response = fb._list_directory(ListDirectoryArgs(path=str(tmp_path)))
+
+ assert response.is_truncated is False
+ assert response.total_count == 3
+ assert len(response.files) == 3
+
+
+def test_is_truncated_false_when_exactly_at_limit(tmp_path: Path) -> None:
+ """Test is_truncated=False when directory has exactly limit number of files."""
+ # Create exactly the limit number of files
+ for i in range(5):
+ (tmp_path / f"file{i}.txt").touch()
+
+ fb = file_browser(initial_path=tmp_path, limit=5)
+ response = fb._list_directory(ListDirectoryArgs(path=str(tmp_path)))
+
+ assert response.is_truncated is False
+ assert response.total_count == 5
+ assert len(response.files) == 5
+
+
+def test_total_count_includes_all_items(tmp_path: Path) -> None:
+ """Test that total_count reflects all files in directory, not just displayed ones."""
+ # Create mix of files and directories
+ for i in range(8):
+ (tmp_path / f"file{i}.txt").touch()
+ for i in range(3):
+ (tmp_path / f"dir{i}").mkdir()
+
+ fb = file_browser(initial_path=tmp_path, limit=5)
+ response = fb._list_directory(ListDirectoryArgs(path=str(tmp_path)))
+
+ assert response.total_count == 11 # All files and directories
+ assert len(response.files) == 5 # Only displayed items
+ assert response.is_truncated is True
+
+
+def test_is_truncated_with_filetype_filtering_edge_case(
+ tmp_path: Path,
+) -> None:
+ """Test is_truncated when filtering creates ambiguity about remaining files."""
+ # Create files where filtering matters for truncation detection
+ (tmp_path / "file1.txt").touch()
+ (tmp_path / "file2.txt").touch()
+ (tmp_path / "file3.txt").touch()
+ (tmp_path / "file4.py").touch()
+ (tmp_path / "file5.py").touch()
+
+ fb = file_browser(initial_path=tmp_path, filetypes=[".txt"], limit=2)
+ response = fb._list_directory(ListDirectoryArgs(path=str(tmp_path)))
+
+ # We should show two .txt files, but there's a third .txt file we didn't process
+ assert response.total_count == 5
+ assert len(response.files) == 2
+ assert response.is_truncated is True