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.

workspace management: add hooks, and shared components (#9272)

Shahmir Varqha6d375cf50696
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.ts
index 3a332cfbaa..ff84f54b6a 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
@@ -182,10 +182,24 @@ describe("RequestingTree", () => {
expect(mockOnChange).toHaveBeenCalled();
});
+ test("delete should drop a file on success", async () => {
+ sendDeleteFileOrFolder.mockResolvedValue({ success: true });
+
+ await requestingTree.delete("1.1");
+ expect(sendDeleteFileOrFolder).toHaveBeenCalledWith({
+ path: "/root/file1",
+ });
+ const lastCall = mockOnChange.mock.calls.at(-1);
+ expect(lastCall?.[0].map((f: { id: string }) => f.id)).toEqual([
+ "1.2",
+ "1.3",
+ ]);
+ });
+
test("createFile should create a new file", async () => {
sendCreateFileOrFolder.mockResolvedValue({ success: true });
- await requestingTree.createFile("file3", "1.2");
+ await requestingTree.createFile({ name: "file3", parentId: "1.2" });
expect(sendCreateFileOrFolder).toHaveBeenCalledWith({
path: "/root/folder1",
type: "file",
@@ -197,7 +211,11 @@ describe("RequestingTree", () => {
test("createFile should create a new notebook", async () => {
sendCreateFileOrFolder.mockResolvedValue({ success: true });
- await requestingTree.createFile("notebook1", "1.2", "notebook");
+ await requestingTree.createFile({
+ name: "notebook1",
+ parentId: "1.2",
+ type: "notebook",
+ });
expect(sendCreateFileOrFolder).toHaveBeenCalledWith({
path: "/root/folder1",
type: "notebook",
@@ -277,6 +295,70 @@ describe("RequestingTree", () => {
});
});
+ test("rename should NOT mutate the local tree on API failure", async () => {
+ sendRenameFileOrFolder.mockResolvedValue({
+ success: false,
+ message: "Error renaming",
+ });
+ const changesBefore = mockOnChange.mock.calls.length;
+
+ await requestingTree.rename("1.1", "file2");
+
+ // No further onChange calls should fire after the failed rename, so the
+ // tree stays in sync with the backend.
+ expect(mockOnChange.mock.calls.length).toBe(changesBefore);
+ });
+
+ test("delete should NOT drop the node on API failure", async () => {
+ sendDeleteFileOrFolder.mockResolvedValue({
+ success: false,
+ message: "Error deleting",
+ });
+ const changesBefore = mockOnChange.mock.calls.length;
+
+ await requestingTree.delete("1.1");
+ expect(sendDeleteFileOrFolder).toHaveBeenCalledWith({
+ path: "/root/file1",
+ });
+ expect(toast).toHaveBeenCalledWith({
+ title: "Failed",
+ description: "Error deleting",
+ });
+ expect(mockOnChange.mock.calls.length).toBe(changesBefore);
+ });
+
+ test("move should NOT mutate the local tree when rename fails", async () => {
+ sendRenameFileOrFolder.mockResolvedValue({
+ success: false,
+ message: "Error moving",
+ });
+
+ await requestingTree.move(["1.1"], "1.2");
+
+ expect(toast).toHaveBeenCalledWith({
+ title: "Failed",
+ description: "Error moving",
+ });
+ // The last emitted state should still have file1 at the top level, not
+ // moved under folder1.
+ const lastCall = mockOnChange.mock.calls.at(-1);
+ expect(lastCall?.[0]).toEqual([
+ { id: "1.1", name: "file1", path: "/root/file1" },
+ {
+ id: "1.2",
+ name: "folder1",
+ isDirectory: true,
+ path: "/root/folder1",
+ },
+ {
+ id: "1.3",
+ name: "folder2",
+ isDirectory: true,
+ path: "/root/folder2",
+ },
+ ]);
+ });
+
test("copy should handle API failure", async () => {
sendCopyFileOrFolder.mockResolvedValue({
success: false,
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index 2fd379c8df..f98936a5d0 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -6,21 +6,18 @@ import {
ArrowLeftIcon,
BetweenHorizontalStartIcon,
BracesIcon,
- CopyIcon,
CopyMinusIcon,
DownloadIcon,
- Edit3Icon,
ExternalLinkIcon,
EyeOffIcon,
FilePlus2Icon,
FolderPlusIcon,
ListTreeIcon,
PlaySquareIcon,
- Trash2Icon,
UploadIcon,
ViewIcon,
} from "lucide-react";
-import React, { Suspense, use, useEffect, useRef, useState } from "react";
+import React, { Suspense, use, useRef, useState } from "react";
import {
type NodeApi,
type NodeRendererProps,
@@ -34,9 +31,15 @@ import {
type FileIconType,
guessFileIconType,
} from "@/components/editor/file-tree/file-icons";
+import {
+ DeleteMenuItem,
+ DuplicateMenuItem,
+ FileActionsDropdown,
+ RenameMenuItem,
+} from "@/components/editor/file-tree/file-operations";
+import { FileNameInput } from "@/components/editor/file-tree/file-name-input";
import {
MENU_ITEM_ICON_CLASS,
- MoreActionsButton,
RefreshIconButton,
TreeChevron,
} from "@/components/editor/file-tree/tree-actions";
@@ -46,11 +49,8 @@ import { useImperativeModal } from "@/components/modal/ImperativeModal";
import { AlertDialogDestructiveAction } from "@/components/ui/alert-dialog";
import { Button, buttonVariants } from "@/components/ui/button";
import {
- DropdownMenu,
- DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
- DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip } from "@/components/ui/tooltip";
import { toast } from "@/components/ui/use-toast";
@@ -69,7 +69,7 @@ import { downloadBlob } from "@/utils/download";
import { type Base64String, base64ToDataURL } from "@/utils/json/base64";
import { openNotebook } from "@/utils/links";
import type { FilePath } from "@/utils/paths";
-import { fileSplit } from "@/utils/pathUtils";
+import { makeDuplicateName } from "@/utils/pathUtils";
import { jotaiJsonStorage } from "@/utils/storage/jotai";
import { useTreeDndManager } from "./dnd-wrapper";
import { FileViewer } from "./file-viewer";
@@ -131,7 +131,7 @@ export const FileExplorer: React.FC<{
openPrompt({
title: "File name",
onConfirm: async (name) => {
- tree.createFile(name, null);
+ tree.createFile({ name, parentId: null });
},
});
});
@@ -140,7 +140,7 @@ export const FileExplorer: React.FC<{
openPrompt({
title: "Notebook name",
onConfirm: async (name) => {
- tree.createFile(name, null, "notebook");
+ tree.createFile({ name, parentId: null, type: "notebook" });
},
});
});
@@ -392,33 +392,6 @@ const Show = ({
);
};
-const Edit = ({ node }: { node: NodeApi<FileInfo> }) => {
- const ref = useRef<HTMLInputElement>(null);
- useEffect(() => {
- ref.current?.focus();
- // Select everything, but the extension
- ref.current?.setSelectionRange(0, node.data.name.lastIndexOf("."));
- }, [node.data.name]);
-
- return (
- <input
- ref={ref}
- className="flex-1 bg-transparent border border-border text-muted-foreground"
- defaultValue={node.data.name}
- onClick={(e) => e.stopPropagation()}
- onBlur={() => node.reset()}
- onKeyDown={(e) => {
- if (e.key === "Escape") {
- node.reset();
- }
- if (e.key === "Enter") {
- node.submit(e.currentTarget.value);
- }
- }}
- />
- );
-};
-
const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
const { openFile, sendFileDetails } = useRequestClient();
const disableFileDownloads = useAtomValue(disableFileDownloadsAtom);
@@ -486,7 +459,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
openPrompt({
title: "File name",
onConfirm: async (name) => {
- tree?.createFile(name, node.id);
+ tree?.createFile({ name, parentId: node.id });
},
});
});
@@ -496,7 +469,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
openPrompt({
title: "Notebook name",
onConfirm: async (name) => {
- tree?.createFile(name, node.id, "notebook");
+ tree?.createFile({ name, parentId: node.id, type: "notebook" });
},
});
});
@@ -505,158 +478,9 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
if (!tree) {
return;
}
-
- const [name, extension] = fileSplit(node.data.name);
- const duplicateName = `${name}_copy${extension}`;
-
- await tree.copy(node.id, duplicateName);
+ await tree.copy(node.id, makeDuplicateName(node.data.name));
});
- const renderActions = () => {
- const ic = MENU_ITEM_ICON_CLASS;
- return (
- <DropdownMenuContent
- align="end"
- className="print:hidden w-[220px]"
- onClick={(e) => e.stopPropagation()}
- onCloseAutoFocus={(e) => e.preventDefault()}
- >
- {!node.data.isDirectory && (
- <DropdownMenuItem onSelect={() => node.select()}>
- <ViewIcon className={ic} />
- Open file
- </DropdownMenuItem>
- )}
- {!node.data.isDirectory && !isWasm() && (
- <DropdownMenuItem
- onSelect={() => {
- openFile({ path: node.data.path });
- }}
- >
- <ExternalLinkIcon className={ic} />
- Open file in external editor
- </DropdownMenuItem>
- )}
- {node.data.isDirectory && (
- <>
- <DropdownMenuItem onSelect={() => handleCreateNotebook()}>
- <MarimoPlusIcon className={ic} />
- Create notebook
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => handleCreateFile()}>
- <FilePlus2Icon className={ic} />
- Create file
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => handleCreateFolder()}>
- <FolderPlusIcon className={ic} />
- Create folder
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- </>
- )}
- <DropdownMenuItem onSelect={() => node.edit()}>
- <Edit3Icon className={ic} />
- Rename
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={handleDuplicate}>
- <CopyIcon className={ic} />
- Duplicate
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={async () => {
- await copyToClipboard(node.data.path);
- toast({ title: "Copied to clipboard" });
- }}
- >
- <ListTreeIcon className={ic} />
- Copy path
- </DropdownMenuItem>
- {tree && (
- <DropdownMenuItem
- onSelect={async () => {
- await copyToClipboard(
- tree.relativeFromRoot(node.data.path as FilePath),
- );
- toast({ title: "Copied to clipboard" });
- }}
- >
- <ListTreeIcon className={ic} />
- Copy relative path
- </DropdownMenuItem>
- )}
- <DropdownMenuSeparator />
-
- <DropdownMenuItem
- onSelect={() => {
- const { path } = node.data;
- const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);
- handleInsertCode(pythonCode);
- }}
- >
- <BetweenHorizontalStartIcon className={ic} />
- Insert snippet for reading file
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={async () => {
- toast({
- title: "Copied to clipboard",
- description:
- "Code to open the file has been copied to your clipboard. You can also drag and drop this file into the editor",
- });
- const { path } = node.data;
- const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);
- await copyToClipboard(pythonCode);
- }}
- >
- <BracesIcon className={ic} />
- Copy snippet for reading file
- </DropdownMenuItem>
- {/* Not shown in WASM */}
- {node.data.isMarimoFile && !isWasm() && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem onSelect={handleOpenMarimoFile}>
- <PlaySquareIcon className={ic} />
- Open notebook
- </DropdownMenuItem>
- </>
- )}
- <DropdownMenuSeparator />
- {!node.data.isDirectory && !disableFileDownloads && (
- <>
- <DropdownMenuItem
- onSelect={async () => {
- const details = await sendFileDetails({ path: node.data.path });
- if (details.isBase64 && details.contents) {
- const blob = deserializeBlob(
- base64ToDataURL(
- details.contents as Base64String,
- details.mimeType || "application/octet-stream",
- ),
- );
- downloadBlob(blob, node.data.name);
- } else {
- downloadBlob(
- new Blob([details.contents || ""]),
- node.data.name,
- );
- }
- }}
- >
- <DownloadIcon className={ic} />
- Download
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- </>
- )}
- <DropdownMenuItem onSelect={handleDeleteFile} variant="danger">
- <Trash2Icon className={ic} />
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- );
- };
-
return (
<div
style={style}
@@ -690,23 +514,138 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
/>
)}
{node.isEditing ? (
- <Edit node={node} />
+ <FileNameInput node={node} />
) : (
<Show node={node} onOpenMarimoFile={handleOpenMarimoFile} />
)}
- <DropdownMenu modal={false}>
- <DropdownMenuTrigger
- asChild={true}
- tabIndex={-1}
- onClick={(e) => e.stopPropagation()}
+ <FileActionsDropdown
+ testId="file-explorer-more-button"
+ iconClassName="w-5 h-5"
+ >
+ {!node.data.isDirectory && (
+ <DropdownMenuItem onSelect={() => node.select()}>
+ <ViewIcon className={MENU_ITEM_ICON_CLASS} />
+ Open file
+ </DropdownMenuItem>
+ )}
+ {!node.data.isDirectory && !isWasm() && (
+ <DropdownMenuItem
+ onSelect={() => {
+ openFile({ path: node.data.path });
+ }}
+ >
+ <ExternalLinkIcon className={MENU_ITEM_ICON_CLASS} />
+ Open file in external editor
+ </DropdownMenuItem>
+ )}
+ {node.data.isDirectory && (
+ <>
+ <DropdownMenuItem onSelect={() => handleCreateNotebook()}>
+ <MarimoPlusIcon className={MENU_ITEM_ICON_CLASS} />
+ Create notebook
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => handleCreateFile()}>
+ <FilePlus2Icon className={MENU_ITEM_ICON_CLASS} />
+ Create file
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => handleCreateFolder()}>
+ <FolderPlusIcon className={MENU_ITEM_ICON_CLASS} />
+ Create folder
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ <RenameMenuItem onSelect={() => node.edit()} />
+ <DuplicateMenuItem onSelect={handleDuplicate} />
+ <DropdownMenuItem
+ onSelect={async () => {
+ await copyToClipboard(node.data.path);
+ toast({ title: "Copied to clipboard" });
+ }}
>
- <MoreActionsButton
- data-testid="file-explorer-more-button"
- iconClassName="w-5 h-5"
- />
- </DropdownMenuTrigger>
- {renderActions()}
- </DropdownMenu>
+ <ListTreeIcon className={MENU_ITEM_ICON_CLASS} />
+ Copy path
+ </DropdownMenuItem>
+ {tree && (
+ <DropdownMenuItem
+ onSelect={async () => {
+ await copyToClipboard(
+ tree.relativeFromRoot(node.data.path as FilePath),
+ );
+ toast({ title: "Copied to clipboard" });
+ }}
+ >
+ <ListTreeIcon className={MENU_ITEM_ICON_CLASS} />
+ Copy relative path
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ const { path } = node.data;
+ const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);
+ handleInsertCode(pythonCode);
+ }}
+ >
+ <BetweenHorizontalStartIcon className={MENU_ITEM_ICON_CLASS} />
+ Insert snippet for reading file
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={async () => {
+ toast({
+ title: "Copied to clipboard",
+ description:
+ "Code to open the file has been copied to your clipboard. You can also drag and drop this file into the editor",
+ });
+ const { path } = node.data;
+ const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);
+ await copyToClipboard(pythonCode);
+ }}
+ >
+ <BracesIcon className={MENU_ITEM_ICON_CLASS} />
+ Copy snippet for reading file
+ </DropdownMenuItem>
+ {node.data.isMarimoFile && !isWasm() && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={handleOpenMarimoFile}>
+ <PlaySquareIcon className={MENU_ITEM_ICON_CLASS} />
+ Open notebook
+ </DropdownMenuItem>
+ </>
+ )}
+ <DropdownMenuSeparator />
+ {!node.data.isDirectory && !disableFileDownloads && (
+ <>
+ <DropdownMenuItem
+ onSelect={async () => {
+ const details = await sendFileDetails({
+ path: node.data.path,
+ });
+ if (details.isBase64 && details.contents) {
+ const blob = deserializeBlob(
+ base64ToDataURL(
+ details.contents as Base64String,
+ details.mimeType || "application/octet-stream",
+ ),
+ );
+ downloadBlob(blob, node.data.name);
+ } else {
+ downloadBlob(
+ new Blob([details.contents || ""]),
+ node.data.name,
+ );
+ }
+ }}
+ >
+ <DownloadIcon className={MENU_ITEM_ICON_CLASS} />
+ Download
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ <DeleteMenuItem onSelect={handleDeleteFile} />
+ </FileActionsDropdown>
</span>
</div>
);
diff --git a/frontend/src/components/editor/file-tree/file-name-input.tsx b/frontend/src/components/editor/file-tree/file-name-input.tsx
new file mode 100644
index 0000000000..7c672b2ea6
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/file-name-input.tsx
@@ -0,0 +1,41 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { NodeApi } from "react-arborist";
+import { useEffect, useRef } from "react";
+import type { FileInfo } from "@/core/network/types";
+
+/**
+ * Inline rename input used by `react-arborist` nodes when `node.isEditing`
+ * is true. Auto-focuses and selects everything except the extension so a
+ * user can type straight into the name.
+ */
+export const FileNameInput = ({ node }: { node: NodeApi<FileInfo> }) => {
+ const ref = useRef<HTMLInputElement>(null);
+ useEffect(() => {
+ ref.current?.focus();
+ // Select everything but the extension. For extensionless names
+ // (`README`) and dotfiles (`.env`), select the full name.
+ const name = node.data.name;
+ const dotIndex = name.lastIndexOf(".");
+ const end = dotIndex > 0 ? dotIndex : name.length;
+ ref.current?.setSelectionRange(0, end);
+ }, [node.data.name]);
+
+ return (
+ <input
+ ref={ref}
+ className="flex-1 bg-transparent border border-border text-muted-foreground"
+ defaultValue={node.data.name}
+ onClick={(e) => e.stopPropagation()}
+ onBlur={() => node.reset()}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ node.reset();
+ }
+ if (e.key === "Enter") {
+ node.submit(e.currentTarget.value);
+ }
+ }}
+ />
+ );
+};
diff --git a/frontend/src/components/editor/file-tree/file-operations.tsx b/frontend/src/components/editor/file-tree/file-operations.tsx
new file mode 100644
index 0000000000..0b2f7df052
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/file-operations.tsx
@@ -0,0 +1,266 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { CopyIcon, Edit3Icon, Trash2Icon } from "lucide-react";
+import type React from "react";
+import { useCallback } from "react";
+import type { NodeApi } from "react-arborist";
+import useEvent from "react-use-event-hook";
+import { useImperativeModal } from "@/components/modal/ImperativeModal";
+import { AlertDialogDestructiveAction } from "@/components/ui/alert-dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { useRequestClient } from "@/core/network/requests";
+import type { FileInfo } from "@/core/network/types";
+import {
+ makeDuplicateName,
+ resolvePaths,
+ toAbsolutePath,
+} from "@/utils/pathUtils";
+import {
+ type FileOperationResult,
+ handleFileResponse,
+} from "./requesting-tree";
+import { MENU_ITEM_ICON_CLASS, MoreActionsButton } from "./tree-actions";
+
+/**
+ * Hook that exposes rename / duplicate / delete operations against absolute
+ * paths, handling path resolution (via `resolvePaths`) and error toasting.
+ *
+ * `root` is the workspace / tree root used to turn relative node paths into
+ * absolute paths for the API. Pass `""` if all node paths are already
+ * absolute (in which case `resolvePaths` is a no-op transformation).
+ */
+export function useFileOperations({ root }: { root: string }) {
+ const {
+ sendRenameFileOrFolder,
+ sendCopyFileOrFolder,
+ sendDeleteFileOrFolder,
+ } = useRequestClient();
+
+ const renameFile = useCallback(
+ async (
+ file: Pick<FileInfo, "path">,
+ newName: string,
+ ): Promise<FileOperationResult> => {
+ const { path, newPath } = resolvePaths({
+ path: file.path,
+ name: newName,
+ root,
+ });
+ const resp = await sendRenameFileOrFolder({ path, newPath });
+ return handleFileResponse(resp);
+ },
+ [root, sendRenameFileOrFolder],
+ );
+
+ const duplicateFile = useCallback(
+ async (
+ file: Pick<FileInfo, "path" | "name">,
+ ): Promise<FileOperationResult> => {
+ const { path, newPath } = resolvePaths({
+ path: file.path,
+ name: makeDuplicateName(file.name),
+ root,
+ });
+ const resp = await sendCopyFileOrFolder({ path, newPath });
+ return handleFileResponse(resp);
+ },
+ [root, sendCopyFileOrFolder],
+ );
+
+ const deleteFile = useCallback(
+ async (file: Pick<FileInfo, "path">): Promise<FileOperationResult> => {
+ const resp = await sendDeleteFileOrFolder({
+ path: toAbsolutePath(file.path, root),
+ });
+ return handleFileResponse(resp);
+ },
+ [root, sendDeleteFileOrFolder],
+ );
+
+ return { renameFile, duplicateFile, deleteFile };
+}
+
+export type FileItemKind = "file" | "folder" | "notebook";
+
+const DELETE_TITLE_BY_KIND: Record<FileItemKind, string> = {
+ file: "Delete file",
+ folder: "Delete folder",
+ notebook: "Delete notebook",
+};
+
+export function useConfirmDeleteFile() {
+ const { openConfirm } = useImperativeModal();
+
+ return useCallback(
+ (
+ target: { name: string; kind?: FileItemKind },
+ onConfirm: () => void | Promise<void>,
+ ) => {
+ const kind = target.kind ?? "file";
+ openConfirm({
+ title: DELETE_TITLE_BY_KIND[kind],
+ description: `Are you sure you want to delete ${target.name}?`,
+ confirmAction: (
+ <AlertDialogDestructiveAction
+ onClick={async () => {
+ await onConfirm();
+ }}
+ aria-label="Confirm"
+ >
+ Delete
+ </AlertDialogDestructiveAction>
+ ),
+ });
+ },
+ [openConfirm],
+ );
+}
+
+/**
+ * High-level handlers for rename/duplicate/delete against a single node
+ *
+ * All successful operations fire `onAfterChange` so callers can refresh their
+ * data sources (workspace tree + recent notebooks on the homepage).
+ */
+export function useNotebookFileActions({
+ node,
+ root,
+ onAfterChange,
+}: {
+ node: NodeApi<FileInfo>;
+ root: string;
+ onAfterChange?: () => void;
+}) {
+ const { duplicateFile, deleteFile } = useFileOperations({ root });
+ const confirmDelete = useConfirmDeleteFile();
+
+ const handleRename = useEvent(() => {
+ node.edit();
+ });
+
+ const handleDuplicate = useEvent(async () => {
+ const result = await duplicateFile(node.data);
+ if (result) {
+ onAfterChange?.();
+ }
+ });
+
+ const handleDelete = useEvent(() => {
+ const kind: FileItemKind = node.data.isDirectory
+ ? "folder"
+ : node.data.isMarimoFile
+ ? "notebook"
+ : "file";
+ confirmDelete({ name: node.data.name, kind }, async () => {
+ const result = await deleteFile(node.data);
+ if (result) {
+ onAfterChange?.();
+ }
+ });
+ });
+
+ return { handleRename, handleDuplicate, handleDelete };
+}
+
+export const FileActionsDropdown = ({
+ testId,
+ buttonClassName,
+ iconClassName,
+ contentClassName,
+ preventDefaultOnTrigger = false,
+ children,
+}: {
+ testId?: string;
+ buttonClassName?: string;
+ iconClassName?: string;
+ contentClassName?: string;
+ /**
+ * When true, the trigger also calls `preventDefault()` on click — needed
+ * when the dropdown is nested inside an `<a>` or other element whose
+ * default click behavior (navigation, submit, etc.) should be suppressed.
+ */
+ preventDefaultOnTrigger?: boolean;
+ children: React.ReactNode;
+}) => (
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger
+ asChild={true}
+ tabIndex={-1}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (preventDefaultOnTrigger) {
+ e.preventDefault();
+ }
+ }}
+ >
+ <MoreActionsButton
+ data-testid={testId}
+ className={buttonClassName}
+ iconClassName={iconClassName}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ className={contentClassName ?? "print:hidden w-[220px]"}
+ onClick={(e) => e.stopPropagation()}
+ onCloseAutoFocus={(e) => e.preventDefault()}
+ >
+ {children}
+ </DropdownMenuContent>
+ </DropdownMenu>
+);
+
+export const RenameMenuItem = ({
+ onSelect,
+ disabled,
+ title,
+}: {
+ onSelect: (evt: Event) => void;
+ disabled?: boolean;
+ title?: string;
+}) => (
+ <DropdownMenuItem onSelect={onSelect} disabled={disabled} title={title}>
+ <Edit3Icon className={MENU_ITEM_ICON_CLASS} />
+ Rename
+ </DropdownMenuItem>
+);
+
+export const DuplicateMenuItem = ({
+ onSelect,
+ disabled,
+ title,
+}: {
+ onSelect: (evt: Event) => void;
+ disabled?: boolean;
+ title?: string;
+}) => (
+ <DropdownMenuItem onSelect={onSelect} disabled={disabled} title={title}>
+ <CopyIcon className={MENU_ITEM_ICON_CLASS} />
+ Duplicate
+ </DropdownMenuItem>
+);
+
+export const DeleteMenuItem = ({
+ onSelect,
+ disabled,
+ title,
+}: {
+ onSelect: (evt: Event) => void;
+ disabled?: boolean;
+ title?: string;
+}) => (
+ <DropdownMenuItem
+ onSelect={onSelect}
+ variant="danger"
+ disabled={disabled}
+ title={title}
+ >
+ <Trash2Icon className={MENU_ITEM_ICON_CLASS} />
+ Delete
+ </DropdownMenuItem>
+);
diff --git a/frontend/src/components/editor/file-tree/requesting-tree.tsx b/frontend/src/components/editor/file-tree/requesting-tree.tsx
index f1b1515757..21f56b7821 100644
--- a/frontend/src/components/editor/file-tree/requesting-tree.tsx
+++ b/frontend/src/components/editor/file-tree/requesting-tree.tsx
@@ -10,6 +10,26 @@ import type {
import { prettyError } from "@/utils/errors";
import { Functions } from "@/utils/functions";
import { type FilePath, PathBuilder } from "@/utils/paths";
+import { resolvePaths } from "@/utils/pathUtils";
+
+/**
+ * Normalized result of a file mutation: the server response when successful,
+ * `null` when the server rejected the request and a toast was surfaced.
+ */
+export type FileOperationResult = FileUpdateResponse | null;
+
+export function handleFileResponse(
+ response: FileUpdateResponse,
+): FileOperationResult {
+ if (!response.success) {
+ toast({
+ title: "Failed",
+ description: response.message,
+ });
+ return null;
+ }
+ return response;
+}
export class RequestingTree {
private delegate = new SimpleTree<FileInfo>([]);
@@ -85,15 +105,15 @@ export class RequestingTree {
});
return;
}
- const currentPath = node.data.path as FilePath;
- const parentPath = this.path.dirname(currentPath);
- const newPath = this.path.join(parentPath, newName);
+ const { path, newPath } = resolvePaths({
+ path: node.data.path,
+ name: newName,
+ root: this.rootPath,
+ });
+ const parentPath = this.path.dirname(path);
const newFile = await this.callbacks
- .copyFileOrFolder({
- path: currentPath,
- newPath: newPath,
- })
- .then(this.handleResponse);
+ .copyFileOrFolder({ path, newPath })
+ .then(handleFileResponse);
if (!newFile?.info) {
return;
}
@@ -116,14 +136,18 @@ export class RequestingTree {
});
return;
}
- const currentPath = node.data.path as FilePath;
- const newPath = this.path.join(this.path.dirname(currentPath), name);
- await this.callbacks
- .renameFileOrFolder({
- path: currentPath,
- newPath: newPath,
- })
- .then(this.handleResponse);
+ const { path, newPath } = resolvePaths({
+ path: node.data.path,
+ name,
+ root: this.rootPath,
+ });
+ const result = await this.callbacks
+ .renameFileOrFolder({ path, newPath })
+ .then(handleFileResponse);
+ if (!result) {
+ return;
+ }
+
this.delegate.update({ id, changes: { name, path: newPath } });
this.onChange(this.delegate.data);
// Rename all of its children
@@ -136,23 +160,25 @@ export class RequestingTree {
: this.rootPath;
await Promise.all(
- fromIds.map((id) => {
- this.delegate.move({ id, parentId, index: 0 });
+ fromIds.map(async (id) => {
const node = this.delegate.find(id);
if (!node) {
- return Promise.resolve();
+ return;
}
+ const originalPath = node.data.path;
const newPath = this.path.join(
parentPath,
- this.path.basename(node.data.path as FilePath),
+ this.path.basename(originalPath as FilePath),
);
+ const result = await this.callbacks
+ .renameFileOrFolder({ path: originalPath, newPath })
+ .then(handleFileResponse);
+ if (!result) {
+ return;
+ }
+
+ this.delegate.move({ id, parentId, index: 0 });
this.delegate.update({ id, changes: { path: newPath } });
- return this.callbacks
- .renameFileOrFolder({
- path: node.data.path,
- newPath: newPath,
- })
- .then(this.handleResponse);
}),
);
@@ -162,17 +188,21 @@ export class RequestingTree {
await this.refreshAll([parentPath]);
}
- async createFile(
- name: string,
- parentId: string | null,
- type: "file" | "notebook" = "file",
- ): Promise<void> {
+ async createFile({
+ name,
+ parentId,
+ type = "file",
+ }: {
+ name: string;
+ parentId: string | null;
+ type?: "file" | "notebook";
+ }): Promise<void> {
const parentPath = parentId
? (this.delegate.find(parentId)?.data.path ?? parentId)
: this.rootPath;
const newFile = await this.callbacks
.createFileOrFolder({ path: parentPath, type: type, name: name })
- .then(this.handleResponse);
+ .then(handleFileResponse);
if (!newFile?.info) {
return;
}
@@ -192,7 +222,7 @@ export class RequestingTree {
: this.rootPath;
const newFolder = await this.callbacks
.createFileOrFolder({ path: parentPath, type: "directory", name: name })
- .then(this.handleResponse);
+ .then(handleFileResponse);
if (!newFolder?.info) {
return;
}
@@ -216,9 +246,12 @@ export class RequestingTree {
return;
}
- await this.callbacks
+ const result = await this.callbacks
.deleteFileOrFolder({ path: node.data.path })
- .then(this.handleResponse);
+ .then(handleFileResponse);
+ if (!result) {
+ return;
+ }
this.delegate.drop({ id });
this.onChange(this.delegate.data);
}
@@ -262,18 +295,4 @@ export class RequestingTree {
}
return path;
};
-
- private handleResponse = (
- response: FileUpdateResponse,
- ): FileUpdateResponse | null => {
- if (!response.success) {
- toast({
- title: "Failed",
- description: response.message,
- });
- return null;
- }
-
- return response;
- };
}
diff --git a/frontend/src/components/home/state.ts b/frontend/src/components/home/state.ts
index 34659a4855..079ac97f6c 100644
--- a/frontend/src/components/home/state.ts
+++ b/frontend/src/components/home/state.ts
@@ -15,7 +15,19 @@ export const RunningNotebooksContext = React.createContext<{
runningNotebooks: new Map(),
setRunningNotebooks: Functions.NOOP,
});
-export const WorkspaceRootContext = React.createContext<string>("");
+
+/**
+ * Context providing the workspace root plus a `refreshWorkspace` hook used by
+ * file actions (rename/duplicate/delete) so they can invalidate both the
+ * workspace tree and any sibling views (e.g. recent notebooks) in one call.
+ */
+export const WorkspaceContext = React.createContext<{
+ root: string;
+ refreshWorkspace: () => void;
+}>({
+ root: "",
+ refreshWorkspace: Functions.NOOP,
+});
export const includeMarkdownAtom = atomWithStorage<boolean>(
"marimo:home:include-markdown",
diff --git a/frontend/src/components/pages/home-page.tsx b/frontend/src/components/pages/home-page.tsx
index 68975414ca..763db0813e 100644
--- a/frontend/src/components/pages/home-page.tsx
+++ b/frontend/src/components/pages/home-page.tsx
@@ -14,7 +14,7 @@ import {
SearchIcon,
} from "lucide-react";
import type React from "react";
-import { Suspense, use, useEffect, useRef, useState } from "react";
+import { Suspense, use, useEffect, useMemo, useRef, useState } from "react";
import {
type NodeApi,
type NodeRendererProps,
@@ -22,16 +22,27 @@ import {
type TreeApi,
} from "react-arborist";
import { useLocale } from "react-aria";
+import useEvent from "react-use-event-hook";
import { MarkdownIcon } from "@/components/editor/cell/code/icons";
import {
FILE_ICON as FILE_TYPE_ICONS,
type FileIconType as FileType,
guessFileIconType as guessFileType,
} from "@/components/editor/file-tree/file-icons";
+import { FileNameInput } from "@/components/editor/file-tree/file-name-input";
+import {
+ DeleteMenuItem,
+ DuplicateMenuItem,
+ FileActionsDropdown,
+ RenameMenuItem,
+ useFileOperations,
+ useNotebookFileActions,
+} from "@/components/editor/file-tree/file-operations";
import { useImperativeModal } from "@/components/modal/ImperativeModal";
import { AlertDialogDestructiveAction } from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
+import { DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { Label } from "@/components/ui/label";
import { Tooltip } from "@/components/ui/tooltip";
import { toast } from "@/components/ui/use-toast";
@@ -61,7 +72,7 @@ import {
expandedFoldersAtom,
includeMarkdownAtom,
RunningNotebooksContext,
- WorkspaceRootContext,
+ WorkspaceContext,
} from "../home/state";
import { Spinner } from "../icons/spinner";
import { Input } from "../ui/input";
@@ -131,7 +142,7 @@ const HomePage: React.FC = () => {
files={recents.files}
/>
<ErrorBoundary>
- <WorkspaceNotebooks />
+ <WorkspaceNotebooks onRefreshRecents={recentsResponse.refetch} />
</ErrorBoundary>
</div>
</RunningNotebooksContext>
@@ -139,7 +150,9 @@ const HomePage: React.FC = () => {
);
};
-const WorkspaceNotebooks: React.FC = () => {
+const WorkspaceNotebooks: React.FC<{ onRefreshRecents: () => void }> = ({
+ onRefreshRecents,
+}) => {
const { getWorkspaceFiles } = useRequestClient();
const [includeMarkdown, setIncludeMarkdown] = useAtom(includeMarkdownAtom);
const [searchText, setSearchText] = useState("");
@@ -154,6 +167,19 @@ const WorkspaceNotebooks: React.FC = () => {
[includeMarkdown],
);
+ // Fire-and-forget refresh of both the workspace tree and the "Recent
+ // notebooks" list — file mutations on the workspace tree can affect both,
+ // so we invalidate them together rather than having two refresh triggers.
+ const refreshWorkspace = useEvent(() => {
+ refetch();
+ onRefreshRecents();
+ });
+
+ const workspaceContextValue = useMemo(
+ () => ({ root: workspace?.root ?? "", refreshWorkspace }),
+ [workspace?.root, refreshWorkspace],
+ );
+
if (isPending) {
return <Spinner centered={true} size="xlarge" className="mt-6" />;
}
@@ -167,7 +193,7 @@ const WorkspaceNotebooks: React.FC = () => {
}
return (
- <WorkspaceRootContext value={workspace.root}>
+ <WorkspaceContext value={workspaceContextValue}>
<div className="flex flex-col gap-2">
{workspace.hasMore && (
<Banner kind="warn" className="rounded p-4">
@@ -216,7 +242,7 @@ const WorkspaceNotebooks: React.FC = () => {
<NotebookFileTree searchText={searchText} files={workspace.files} />
</div>
</div>
- </WorkspaceRootContext>
+ </WorkspaceContext>
);
};
@@ -244,6 +270,8 @@ const NotebookFileTree: React.FC<{
const [openState, setOpenState] = useAtom(expandedFoldersAtom);
const openStateIsEmpty = Object.keys(openState).length === 0;
const ref = useRef<TreeApi<FileInfo>>(undefined);
+ const { root, refreshWorkspace } = use(WorkspaceContext);
+ const { renameFile } = useFileOperations({ root });
useEffect(() => {
// If empty, collapse all
@@ -252,6 +280,21 @@ const NotebookFileTree: React.FC<{
}
}, [openStateIsEmpty]);
+ const handleRename = useEvent(async (id: string, name: string) => {
+ const node = ref.current?.get(id);
+ if (!node) {
+ toast({
+ title: "Failed",
+ description: `Node with id ${id} not found in the tree`,
+ });
+ return;
+ }
+ const result = await renameFile(node.data, name);
+ if (result) {
+ refreshWorkspace();
+ }
+ });
+
if (files.length === 0) {
return (
<div className="flex flex-col px-5 py-10 items-center justify-center">
@@ -277,6 +320,9 @@ const NotebookFileTree: React.FC<{
const prevOpen = openState[id] ?? false;
setOpenState({ ...openState, [id]: !prevOpen });
}}
+ onRename={async ({ id, name }) => {
+ await handleRename(id, name);
+ }}
padding={5}
rowHeight={35}
indent={15}
@@ -286,7 +332,6 @@ const NotebookFileTree: React.FC<{
// Disable interactions
disableDrop={true}
disableDrag={true}
- disableEdit={true}
disableMultiSelection={true}
>
{Node}
@@ -301,11 +346,24 @@ const Node = ({ node, style }: NodeRendererProps<FileInfo>) => {
const Icon = FILE_TYPE_ICONS[fileType];
const iconEl = <Icon className="w-5 h-5 shrink-0" strokeWidth={1.5} />;
- const root = use(WorkspaceRootContext);
+ const { root } = use(WorkspaceContext);
+ const { runningNotebooks } = use(RunningNotebooksContext);
const renderItem = () => {
const itemClassName =
"flex items-center pl-1 cursor-pointer hover:bg-accent/50 hover:text-accent-foreground rounded-l flex-1 overflow-hidden h-full pr-3 gap-2";
+
+ // Inline rename input; react-arborist flips `node.isEditing` when
+ // `node.edit()` is called from the FileActions menu.
+ if (node.isEditing) {
+ return (
+ <div className={itemClassName}>
+ {iconEl}
+ <FileNameInput node={node} />
+ </div>
+ );
+ }
+
if (node.data.isDirectory) {
return (
<span className={itemClassName}>
@@ -322,6 +380,7 @@ const Node = ({ node, style }: NodeRendererProps<FileInfo>) => {
const isMarkdown =
relativePath.endsWith(".md") || relativePath.endsWith(".qmd");
+ const isRunning = runningNotebooks.has(relativePath);
return (
<a
@@ -334,10 +393,19 @@ const Node = ({ node, style }: NodeRendererProps<FileInfo>) => {
{node.data.name}
{isMarkdown && <MarkdownIcon className="ml-2 inline opacity-80" />}
</span>
- <SessionShutdownButton filePath={relativePath} />
+
+ <FileActions node={node} isRunning={isRunning} />
+ {/*
+ Trailing action slots. Using a fixed-width row here (rather than
+ conditionally rendered inline elements) keeps every row's right
+ edge aligned even though any individual slot may be empty.
+ */}
+ <div className="w-8 h-8 flex items-center justify-center shrink-0">
+ <SessionShutdownButton filePath={relativePath} />
+ </div>
<ExternalLinkIcon
size={20}
- className="group-hover:opacity-100 opacity-0 text-primary"
+ className="group-hover:opacity-100 opacity-0 text-primary shrink-0"
/>
</a>
);
@@ -362,6 +430,44 @@ const Node = ({ node, style }: NodeRendererProps<FileInfo>) => {
);
};
+const FileActions = ({
+ node,
+ isRunning,
+}: {
+ node: NodeApi<FileInfo>;
+ isRunning: boolean;
+}) => {
+ const { root, refreshWorkspace } = use(WorkspaceContext);
+ const { handleRename, handleDuplicate, handleDelete } =
+ useNotebookFileActions({ node, root, onAfterChange: refreshWorkspace });
+
+ const lockedReason = isRunning
+ ? "Stop the notebook's kernel before renaming or deleting."
+ : undefined;
+
+ return (
+ <FileActionsDropdown
+ testId="workspace-more-button"
+ buttonClassName="w-8 h-8 p-0 shrink-0"
+ contentClassName="print:hidden w-fit min-w-[140px]"
+ preventDefaultOnTrigger={true}
+ >
+ <RenameMenuItem
+ onSelect={handleRename}
+ disabled={isRunning}
+ title={lockedReason}
+ />
+ <DuplicateMenuItem onSelect={handleDuplicate} />
+ <DropdownMenuSeparator />
+ <DeleteMenuItem
+ onSelect={handleDelete}
+ disabled={isRunning}
+ title={lockedReason}
+ />
+ </FileActionsDropdown>
+ );
+};
+
const FolderArrow = ({ node }: { node: NodeApi<FileInfo> }) => {
if (!node.data.isDirectory) {
return <span className="w-5 h-5 shrink-0" />;
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index d361c6490b..e53ae139d9 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -305,7 +305,6 @@ export function createNetworkRequests(): EditRequests & RunRequests {
.then(handleResponse);
},
sendDeleteFileOrFolder: async (request) => {
- await waitForConnectionOpen();
return getClient()
.POST("/api/files/delete", {
body: request,
@@ -313,7 +312,6 @@ export function createNetworkRequests(): EditRequests & RunRequests {
.then(handleResponse);
},
sendCopyFileOrFolder: async (request) => {
- await waitForConnectionOpen();
return getClient()
.POST("/api/files/copy", {
body: request,
@@ -321,7 +319,6 @@ export function createNetworkRequests(): EditRequests & RunRequests {
.then(handleResponse);
},
sendRenameFileOrFolder: async (request) => {
- await waitForConnectionOpen();
return getClient()
.POST("/api/files/move", {
body: request,
diff --git a/frontend/src/utils/__tests__/path.test.ts b/frontend/src/utils/__tests__/path.test.ts
index 2d4fb166eb..34d335bdd0 100644
--- a/frontend/src/utils/__tests__/path.test.ts
+++ b/frontend/src/utils/__tests__/path.test.ts
@@ -9,6 +9,26 @@ describe("Paths", () => {
expect(Paths.isAbsolute("/user/docs/Letter.txt")).toBe(true);
expect(Paths.isAbsolute("C:\\user\\docs\\Letter.txt")).toBe(true);
expect(Paths.isAbsolute("user/docs/Letter.txt")).toBe(false);
+
+ // Any Windows drive letter, either separator, and any case
+ expect(Paths.isAbsolute("D:\\Users\\x\\a.py")).toBe(true);
+ expect(Paths.isAbsolute("z:/tmp/file")).toBe(true);
+ expect(Paths.isAbsolute("e:\\")).toBe(true);
+
+ // UNC / server paths
+ expect(Paths.isAbsolute("\\\\server\\share\\file")).toBe(true);
+
+ // URI schemes
+ expect(Paths.isAbsolute("s3://bucket/key")).toBe(true);
+ expect(Paths.isAbsolute("gs://bucket/key")).toBe(true);
+ expect(Paths.isAbsolute("file:///tmp/file")).toBe(true);
+ expect(Paths.isAbsolute("http://example.com/x")).toBe(true);
+
+ // Negative cases
+ expect(Paths.isAbsolute("C:file")).toBe(false); // drive without separator
+ expect(Paths.isAbsolute("notebook.py")).toBe(false);
+ expect(Paths.isAbsolute("./relative")).toBe(false);
+ expect(Paths.isAbsolute("")).toBe(false);
});
describe("dirname", () => {
diff --git a/frontend/src/utils/pathUtils.test.ts b/frontend/src/utils/pathUtils.test.ts
index a273b64b99..392be162c0 100644
--- a/frontend/src/utils/pathUtils.test.ts
+++ b/frontend/src/utils/pathUtils.test.ts
@@ -1,6 +1,12 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import { fileSplit, getProtocolAndParentDirectories } from "./pathUtils";
+import {
+ fileSplit,
+ getProtocolAndParentDirectories,
+ makeDuplicateName,
+ resolvePaths,
+ toAbsolutePath,
+} from "./pathUtils";
describe("getProtocolAndParentDirectories", () => {
it("should extract protocol and list parent directories correctly", () => {
@@ -111,3 +117,137 @@ describe("fileSplit", () => {
]);
});
});
+
+describe("makeDuplicateName", () => {
+ it("appends _copy before the extension", () => {
+ expect(makeDuplicateName("notebook.py")).toBe("notebook_copy.py");
+ expect(makeDuplicateName("foo.tar.gz")).toBe("foo.tar_copy.gz");
+ });
+
+ it("appends _copy for extensionless names", () => {
+ expect(makeDuplicateName("README")).toBe("README_copy");
+ });
+});
+
+describe("toAbsolutePath", () => {
+ it("joins relative paths against the root", () => {
+ expect(toAbsolutePath("notebooks/a.py", "/workspaces/marimo")).toBe(
+ "/workspaces/marimo/notebooks/a.py",
+ );
+ });
+
+ it("returns absolute POSIX paths unchanged", () => {
+ expect(toAbsolutePath("/abs/a.py", "/workspaces/marimo")).toBe("/abs/a.py");
+ });
+
+ it("returns absolute Windows paths unchanged", () => {
+ expect(toAbsolutePath("C:\\Users\\x\\a.py", "C:\\Users\\marimo")).toBe(
+ "C:\\Users\\x\\a.py",
+ );
+ });
+
+ it("joins relative paths using the Windows delimiter", () => {
+ expect(toAbsolutePath("a.py", "C:\\Users\\marimo")).toBe(
+ "C:\\Users\\marimo\\a.py",
+ );
+ });
+});
+
+describe("resolvePaths", () => {
+ it("resolves relative paths against the root", () => {
+ expect(
+ resolvePaths({
+ path: "notebooks/notebook.py",
+ name: "notebook_copy.py",
+ root: "/workspaces/marimo",
+ }),
+ ).toEqual({
+ path: "/workspaces/marimo/notebooks/notebook.py",
+ newPath: "/workspaces/marimo/notebooks/notebook_copy.py",
+ });
+ });
+
+ it("keeps absolute source paths untouched", () => {
+ expect(
+ resolvePaths({
+ path: "/abs/path/notebook.py",
+ name: "notebook_copy.py",
+ root: "/workspaces/marimo",
+ }),
+ ).toEqual({
+ path: "/abs/path/notebook.py",
+ newPath: "/abs/path/notebook_copy.py",
+ });
+ });
+
+ it("handles Windows roots for relative paths", () => {
+ expect(
+ resolvePaths({
+ path: "notebook.py",
+ name: "notebook_copy.py",
+ root: "C:\\Users\\marimo",
+ }),
+ ).toEqual({
+ path: "C:\\Users\\marimo\\notebook.py",
+ newPath: "C:\\Users\\marimo\\notebook_copy.py",
+ });
+ });
+
+ it("handles Windows absolute source paths", () => {
+ // The tricky case: `path` is an absolute Windows path with a drive letter,
+ // so it must be detected by `Paths.isAbsolute` AND the deliminator must be
+ // picked up from the root so the join uses backslashes.
+ expect(
+ resolvePaths({
+ path: "C:\\Users\\marimo\\folder\\notebook.py",
+ name: "notebook_copy.py",
+ root: "C:\\Users\\marimo",
+ }),
+ ).toEqual({
+ path: "C:\\Users\\marimo\\folder\\notebook.py",
+ newPath: "C:\\Users\\marimo\\folder\\notebook_copy.py",
+ });
+ });
+
+ it("keeps the file in its current directory when renaming", () => {
+ expect(
+ resolvePaths({
+ path: "/root/a/b/file.py",
+ name: "renamed.py",
+ root: "/root",
+ }),
+ ).toEqual({
+ path: "/root/a/b/file.py",
+ newPath: "/root/a/b/renamed.py",
+ });
+ });
+
+ it("handles an empty root with an absolute POSIX path", () => {
+ // Callers that already hold absolute paths pass `root: ""`. In that case
+ // the delimiter must be inferred from the path itself, not from `""` (which
+ // would otherwise default to Windows backslashes).
+ expect(
+ resolvePaths({
+ path: "/abs/path/file.py",
+ name: "renamed.py",
+ root: "",
+ }),
+ ).toEqual({
+ path: "/abs/path/file.py",
+ newPath: "/abs/path/renamed.py",
+ });
+ });
+
+ it("handles an empty root with an absolute Windows path", () => {
+ expect(
+ resolvePaths({
+ path: "C:\\Users\\marimo\\file.py",
+ name: "renamed.py",
+ root: "",
+ }),
+ ).toEqual({
+ path: "C:\\Users\\marimo\\file.py",
+ newPath: "C:\\Users\\marimo\\renamed.py",
+ });
+ });
+});
diff --git a/frontend/src/utils/pathUtils.ts b/frontend/src/utils/pathUtils.ts
index 080450be82..d849bb4d06 100644
--- a/frontend/src/utils/pathUtils.ts
+++ b/frontend/src/utils/pathUtils.ts
@@ -1,5 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import { type FilePath, Paths, PathBuilder } from "./paths";
+
/**
* Get the protocol and parent directories of a path.
*/
@@ -74,3 +76,47 @@ export function fileSplit(path: string): [name: string, extension: string] {
const extension = lastDotIndex > 0 ? path.slice(lastDotIndex) : "";
return [name, extension];
}
+
+/**
+ * Build the "_copy" filename used for duplicate operations.
+ * e.g. `foo.py` → `foo_copy.py`, `README` → `README_copy`.
+ */
+export function makeDuplicateName(name: string): string {
+ const [base, extension] = fileSplit(name);
+ return `${base}_copy${extension}`;
+}
+
+/**
+ * Return `path` as an absolute path, joining against `root` when it's
+ * workspace-relative. `root`'s delimiter determines the join style so
+ * Windows and POSIX paths both behave correctly.
+ */
+export function toAbsolutePath(path: string, root: string): FilePath {
+ if (Paths.isAbsolute(path)) {
+ return path as FilePath;
+ }
+ return PathBuilder.guessDeliminator(root).join(root, path as FilePath);
+}
+
+/**
+ * Resolve absolute current/new paths for a rename- or copy-style operation.
+ * Given a node's current `path` (absolute or workspace-relative) and a
+ * desired new `name` (basename only), returns the absolute source and the
+ * absolute destination, keeping the file in the same parent directory.
+ */
+export function resolvePaths({
+ path,
+ name,
+ root,
+}: {
+ path: string;
+ name: string;
+ root: string;
+}): { path: FilePath; newPath: FilePath } {
+ const absPath = toAbsolutePath(path, root);
+ // When `root` is empty (callers with already-absolute paths), fall back to
+ // the resolved absolute path so we don't default to the Windows delimiter.
+ const pathBuilder = PathBuilder.guessDeliminator(root || absPath);
+ const newPath = pathBuilder.join(pathBuilder.dirname(absPath), name);
+ return { path: absPath, newPath };
+}
diff --git a/frontend/src/utils/paths.ts b/frontend/src/utils/paths.ts
index 3a4e5add36..6e0d28bc27 100644
--- a/frontend/src/utils/paths.ts
+++ b/frontend/src/utils/paths.ts
@@ -4,10 +4,18 @@ import type { TypedString } from "./typed";
export type FilePath = TypedString<"FilePath">;
+// Windows drive-letter prefix like `C:\`, `d:/`, `Z:\`.
+const WINDOWS_DRIVE_PREFIX = /^[A-Za-z]:[/\\]/;
+// URI scheme prefix like `s3://`, `gs://`, `http://`, `file://`.
+const URI_SCHEME_PREFIX = /^[A-Za-z][\dA-Za-z+.-]*:\/\//;
+
export const Paths = {
isAbsolute: (path: string): boolean => {
return (
- path.startsWith("/") || path.startsWith("\\") || path.startsWith("C:\\")
+ path.startsWith("/") ||
+ path.startsWith("\\") ||
+ WINDOWS_DRIVE_PREFIX.test(path) ||
+ URI_SCHEME_PREFIX.test(path)
);
},
dirname: (path: string) => {