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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: Add option to create notebook from file tree (#8412)
Daizu1bab9a7b9043
diff --git a/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts b/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.tsindex 02731c3ec2..49681bc0a1 100644--- a/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts+++ b/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts@@ -174,7 +174,23 @@ describe("RequestingTree", () => {sendCreateFileOrFolder.mockResolvedValue({ success: true });await requestingTree.createFile("file3", "1.2");- expect(sendCreateFileOrFolder).toHaveBeenCalled();+ expect(sendCreateFileOrFolder).toHaveBeenCalledWith({+ path: "/root/folder1",+ type: "file",+ name: "file3",+ });+ expect(mockOnChange).toHaveBeenCalled();+ });++ test("createFile should create a new notebook", async () => {+ sendCreateFileOrFolder.mockResolvedValue({ success: true });++ await requestingTree.createFile("notebook1", "1.2", "notebook");+ expect(sendCreateFileOrFolder).toHaveBeenCalledWith({+ path: "/root/folder1",+ type: "notebook",+ name: "notebook1",+ });expect(mockOnChange).toHaveBeenCalled();});diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsxindex 5c390d20be..2f04b71ee1 100644--- a/frontend/src/components/editor/file-tree/file-explorer.tsx+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx@@ -19,6 +19,7 @@ import {ListTreeIcon,MoreVerticalIcon,PlaySquareIcon,+ PlusIcon,RefreshCcwIcon,Trash2Icon,UploadIcon,@@ -128,6 +129,15 @@ export const FileExplorer: React.FC<{});});+ const handleCreateNotebook = useEvent(async () => {+ openPrompt({+ title: "Notebook name",+ onConfirm: async (name) => {+ tree.createFile(name, null, "notebook");+ },+ });+ });+const handleCollapseAll = useEvent(() => {treeRef.current?.closeAll();setOpenState({});@@ -182,6 +192,7 @@ export const FileExplorer: React.FC<{onRefresh={handleRefresh}onHidden={handleHiddenFilesToggle}onCreateFile={handleCreateFile}+ onCreateNotebook={handleCreateNotebook}onCreateFolder={handleCreateFolder}onCollapseAll={handleCollapseAll}tree={tree}@@ -248,6 +259,7 @@ interface ToolbarProps {onRefresh: () => void;onHidden: () => void;onCreateFile: () => void;+ onCreateNotebook: () => void;onCreateFolder: () => void;onCollapseAll: () => void;tree: RequestingTree;@@ -257,6 +269,7 @@ const Toolbar = ({onRefresh,onHidden,onCreateFile,+ onCreateNotebook,onCreateFolder,onCollapseAll,}: ToolbarProps) => {@@ -267,6 +280,29 @@ const Toolbar = ({return (<div className="flex items-center justify-end px-2 shrink-0 border-b">+ <Tooltip content="Add notebook">+ <Button+ data-testid="file-explorer-add-notebook-button"+ onClick={onCreateNotebook}+ variant="text"+ size="xs"+ >+ <div className="relative w-4 h-4 shrink-0">+ <img+ src={marimoIcon}+ className="absolute top-0 left-0 w-full h-full filter grayscale"+ alt="Marimo"+ />+ <PlusIcon+ size={7}+ strokeWidth={4}+ className="absolute bottom-0 right-0 text-gray-800 dark:text-gray-200+ bg-background dark:bg-(--slate-1) rounded-full"+ style={{ transform: "translate(20%, 20%)" }}+ />+ </div>+ </Button>+ </Tooltip><Tooltip content="Add file"><Buttondata-testid="file-explorer-add-file-button"@@ -467,6 +503,16 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {});});+ const handleCreateNotebook = useEvent(async () => {+ node.open();+ openPrompt({+ title: "Notebook name",+ onConfirm: async (name) => {+ tree?.createFile(name, node.id, "notebook");+ },+ });+ });+const handleDuplicate = useEvent(async () => {if (!tree || node.data.isDirectory) {return;@@ -532,6 +578,23 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {)}{node.data.isDirectory && (<>+ <DropdownMenuItem onSelect={() => handleCreateNotebook()}>+ <div className="relative w-[14px] h-[14px] mr-2 shrink-0">+ <img+ src={marimoIcon}+ className="absolute top-0 left-0 w-full h-full filter grayscale"+ alt="Marimo"+ />+ <PlusIcon+ size={6}+ strokeWidth={3}+ className="absolute bottom-0 right-0 text-gray-800 dark:text-gray-200+ bg-popover rounded-full"+ style={{ transform: "translate(20%, 20%)" }}+ />+ </div>+ Create notebook+ </DropdownMenuItem><DropdownMenuItem onSelect={() => handleCreateFile()}><FilePlus2Icon {...iconProps} />Create filediff --git a/frontend/src/components/editor/file-tree/requesting-tree.tsx b/frontend/src/components/editor/file-tree/requesting-tree.tsxindex c040b0c7a4..e59cc730f8 100644--- a/frontend/src/components/editor/file-tree/requesting-tree.tsx+++ b/frontend/src/components/editor/file-tree/requesting-tree.tsx@@ -125,12 +125,16 @@ export class RequestingTree {await this.refreshAll([parentPath]);}- async createFile(name: string, parentId: string | null): Promise<void> {+ async createFile(+ name: string,+ parentId: string | null,+ type: "file" | "notebook" = "file",+ ): Promise<void> {const parentPath = parentId? (this.delegate.find(parentId)?.data.path ?? parentId): this.rootPath;const newFile = await this.callbacks- .createFileOrFolder({ path: parentPath, type: "file", name: name })+ .createFileOrFolder({ path: parentPath, type: type, name: name }).then(this.handleResponse);if (!newFile?.info) {return;diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pyindex 9793e171d9..845d2ffca0 100644--- a/marimo/_server/files/os_file_system.py+++ b/marimo/_server/files/os_file_system.py@@ -15,6 +15,7 @@ from typing import Literal, Optional, Unionfrom marimo import _loggersfrom marimo._server.files.file_system import FileSystemfrom marimo._server.models.files import FileDetailsResponse, FileInfo+from marimo._session.notebook.file_manager import AppFileManagerfrom marimo._utils.files import natural_sortLOGGER = _loggers.marimo_logger()@@ -126,7 +127,7 @@ class OSFileSystem(FileSystem):def create_file_or_directory(self,path: str,- file_type: Literal["file", "directory"],+ file_type: Literal["file", "directory", "notebook"],name: str,contents: Optional[bytes],) -> FileInfo:@@ -153,6 +154,13 @@ class OSFileSystem(FileSystem):if file_type == "directory":full_path.mkdir(parents=True, exist_ok=True)+ elif file_type == "notebook" and not contents:+ full_path.parent.mkdir(parents=True, exist_ok=True)+ # Create a new AppFileManager to get the default notebook code+ # We pass None as filename to get the empty notebook template+ notebook_code = AppFileManager(None).to_code()+ full_path.write_text(notebook_code, encoding="utf-8")+ contents = notebook_code.encode("utf-8")else:full_path.parent.mkdir(parents=True, exist_ok=True)full_path.write_bytes(contents or b"")diff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.pyindex b8f375d23f..7375547d6d 100644--- a/marimo/_server/models/files.py+++ b/marimo/_server/models/files.py@@ -45,8 +45,8 @@ class FileTreeRequest(msgspec.Struct, rename="camel"):class FileCreateRequest(msgspec.Struct, rename="camel"):# The path where to create the file or directorypath: str- # 'file' or 'directory'- type: Literal["file", "directory"]+ # 'file', 'directory', or 'notebook'+ type: Literal["file", "directory", "notebook"]# The name of the file or directoryname: str# The contents of the file, base64-encodeddiff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex 2198a4824b..ae1ce5422b 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -1562,6 +1562,7 @@ components:enum:- directory- file+ - notebookrequired:- path- type@@ -4940,7 +4941,7 @@ components:type: objectinfo:title: marimo API- version: 0.20.0+ version: 0.20.1openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 57bbe72202..00dfb9f93c 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -4005,7 +4005,7 @@ export interface components {name: string;path: string;/** @enum {unknown} */- type: "directory" | "file";+ type: "directory" | "file" | "notebook";};/** FileCreateResponse */FileCreateResponse: {diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.pyindex 188b62f795..8a22087e8c 100644--- a/tests/_server/files/test_os_file_system.py+++ b/tests/_server/files/test_os_file_system.py@@ -1,6 +1,7 @@from __future__ import annotationsfrom pathlib import Path+from typing import Literalimport pytest@@ -28,6 +29,34 @@ def test_create_file(test_dir: Path, fs: OSFileSystem) -> None:assert expected_path.exists()+def test_create_notebook(test_dir: Path, fs: OSFileSystem) -> None:+ test_notebook_name = "test_notebook.py"+ fs.create_file_or_directory(+ str(test_dir),+ "notebook",+ test_notebook_name,+ None,+ )+ expected_path = test_dir / test_notebook_name+ assert expected_path.exists()+ notebook_code = expected_path.read_text("utf-8")+ assert "import marimo" in notebook_code+ assert "app.run()" in notebook_code+++def test_create_notebook_with_contents(+ test_dir: Path, fs: OSFileSystem+) -> None:+ test_notebook_name = "test_notebook.py"+ fs.create_file_or_directory(+ str(test_dir), "notebook", test_notebook_name, b"marimo"+ )+ expected_path = test_dir / test_notebook_name+ assert expected_path.exists()+ notebook_code = expected_path.read_text("utf-8")+ assert notebook_code == "marimo"++def test_create_file_with_duplicate_name(test_dir: Path, fs: OSFileSystem) -> None:@@ -38,12 +67,13 @@ def test_create_file_with_duplicate_name(assert expected_path.exists()[email protected]("file_type", ["file", "notebook"])def test_create_file_and_parent_directories(- test_dir: Path, fs: OSFileSystem+ test_dir: Path, fs: OSFileSystem, file_type: Literal["file", "notebook"]) -> None:test_file_name = "test_file.txt"fs.create_file_or_directory(- str(test_dir / "parent"), "file", test_file_name, None+ str(test_dir / "parent"), file_type, test_file_name, None)expected_path = test_dir / "parent" / test_file_nameassert expected_path.exists()