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
improvement: improved homepage with search and file-explorer (#1759)
Myles Scolnick54ecc1a18e6d
diff --git a/frontend/src/components/home/state.ts b/frontend/src/components/home/state.tsnew file mode 100644index 0000000000..8ee3394b2d--- /dev/null+++ b/frontend/src/components/home/state.ts@@ -0,0 +1,30 @@+/* Copyright 2024 Marimo. All rights reserved. */+import React, {} from "react";+import { Functions } from "@/utils/functions";+import { atomWithStorage } from "jotai/utils";+import { MarimoFile } from "@/core/network/types";++export type RunningNotebooksMap = Map<string, MarimoFile>;++export const RunningNotebooksContext = React.createContext<{+ runningNotebooks: RunningNotebooksMap;+ setRunningNotebooks: (data: RunningNotebooksMap) => void;+ root: string;+}>({+ runningNotebooks: new Map(),+ root: "",+ setRunningNotebooks: Functions.NOOP,+});++export const includeMarkdownAtom = atomWithStorage<boolean>(+ "marimo:home:include-markdown",+ false,+ undefined,+ { getOnInit: true },+);+export const expandedFoldersAtom = atomWithStorage<Record<string, boolean>>(+ "marimo:home:expanded-folders",+ {},+ undefined,+ { getOnInit: true },+);diff --git a/frontend/src/components/pages/home-page.tsx b/frontend/src/components/pages/home-page.tsxindex 983f53fe43..4d36e94811 100644--- a/frontend/src/components/pages/home-page.tsx+++ b/frontend/src/components/pages/home-page.tsx@@ -6,9 +6,26 @@ import {shutdownSession,} from "@/core/network/requests";import { combineAsyncData, useAsyncData } from "@/hooks/useAsyncData";-import React, { Suspense, useState } from "react";+import React, {+ Suspense,+ useContext,+ useEffect,+ useRef,+ useState,+} from "react";import { Spinner } from "../icons/spinner";-import { ExternalLinkIcon, PowerOffIcon } from "lucide-react";+import {+ BookTextIcon,+ ChevronDownIcon,+ ChevronRightIcon,+ ChevronsDownUpIcon,+ ClockIcon,+ ExternalLinkIcon,+ PlayCircleIcon,+ PowerOffIcon,+ RefreshCcwIcon,+ SearchIcon,+} from "lucide-react";import { ShutdownButton } from "../editor/controls/shutdown-button";import {SessionId,@@ -17,19 +34,34 @@ import {isSessionId,} from "@/core/kernel/session";import { useInterval } from "@/hooks/useInterval";-import { cn } from "@/utils/cn";import { useImperativeModal } from "@/components/modal/ImperativeModal";import { AlertDialogDestructiveAction } from "@/components/ui/alert-dialog";import { assertExists } from "@/utils/assertExists";import { Button } from "@/components/ui/button";import { Tooltip } from "@/components/ui/tooltip";import { toast } from "@/components/ui/use-toast";-import { WorkspaceFilesResponse } from "@/core/network/types";+import { FileInfo, MarimoFile } from "@/core/network/types";import { ConfigButton } from "../app-config/app-config-button";import { Checkbox } from "@/components/ui/checkbox";import { Label } from "@/components/ui/label";import { MarkdownIcon } from "@/components/editor/cell/code/icons";import { asURL } from "@/utils/url";+import { timeAgo } from "@/utils/dates";+import { NodeApi, NodeRendererProps, Tree, TreeApi } from "react-arborist";+import { cn } from "@/utils/cn";+import {+ FileType,+ guessFileType,+ FILE_TYPE_ICONS,+} from "../editor/file-tree/types";+import { useAtom, useSetAtom } from "jotai";+import {+ expandedFoldersAtom,+ includeMarkdownAtom,+ RunningNotebooksContext,+} from "../home/state";+import { Maps } from "@/utils/maps";+import { Input } from "../ui/input";function tabTarget(path: string) {// Consistent tab target so we open in the same tab when clicking on the same notebook@@ -37,17 +69,16 @@ function tabTarget(path: string) {}const HomePage: React.FC = () => {- const [includeMarkdown, setIncludeMarkdown] = useState(false);+ const [includeMarkdown, setIncludeMarkdown] = useAtom(includeMarkdownAtom);+ const [searchText, setSearchText] = useState("");+ const [nonce, setNonce] = useState(0);- const fileResponse = useAsyncData(async () => {- const [workspace, recents] = await Promise.all([- getWorkspaceFiles({ includeMarkdown: includeMarkdown }),- getRecentFiles(),- ]);- return { workspace, recents };- }, [includeMarkdown]);+ const recentsResponse = useAsyncData(() => getRecentFiles(), []);+ const workspaceResponse = useAsyncData(+ () => getWorkspaceFiles({ includeMarkdown }),+ [includeMarkdown],+ );- const [nonce, setNonce] = useState(0);useInterval(() => {setNonce((nonce) => nonce + 1);@@ -57,221 +88,392 @@ const HomePage: React.FC = () => {);const runningResponse = useAsyncData(async () => {- return getRunningNotebooks();+ const response = await getRunningNotebooks();+ return Maps.keyBy(response.files, (file) => file.path);}, [nonce]);- const error = fileResponse.error || runningResponse.error;- if (error) {- throw error;+ const response = combineAsyncData(+ recentsResponse,+ workspaceResponse,+ runningResponse,+ );++ if (response.error) {+ throw response.error;}- const data = combineAsyncData(fileResponse, runningResponse).data;+ const data = response.data;if (!data) {return <Spinner centered={true} size="xlarge" />;}- const [{ workspace, recents }, running] = data;-- const runningNotebooks = new Map(- running.files.flatMap((file) =>- file.initializationId && file.sessionId- ? [- [- file.path,- {- sessionId: file.sessionId as SessionId,- initializationId: file.initializationId,- },- ],- ]- : [],- ),- );+ const [recents, workspace, running] = data;return (<Suspense>- {/*<GridBackground />*/}- <div className="absolute top-3 right-5 flex gap-2 z-10">- <ConfigButton showAppConfig={false} />- <ShutdownButton- description={`This will shutdown the notebook server and terminate all running notebooks (${running.files.length}). You'll lose all data that's in memory.`}- />- </div>- <div className="flex flex-col gap-8 max-w-5xl container pt-10 pb-20 z-10">- <img src="logo.png" alt="marimo logo" className="w-64 mb-4" />- <CreateNewNotebook />- <NotebookList- header="Running notebooks"- files={running.files}- runningNotebooks={runningNotebooks}- setRunningNotebooks={runningResponse.setData}- />- <NotebookList- header="Recent notebooks"- files={recents.files}- runningNotebooks={runningNotebooks}- setRunningNotebooks={runningResponse.setData}- />- <NotebookList- header="All notebooks"- control={- <div className="flex items-center gap-2">- {fileResponse.loading && <Spinner size="small" />}- <Checkbox- data-testid="include-markdown-checkbox"- id="include-markdown"- checked={includeMarkdown}- onCheckedChange={(checked) =>- setIncludeMarkdown(Boolean(checked))- }+ <RunningNotebooksContext.Provider+ value={{+ runningNotebooks: running,+ root: workspace.root,+ setRunningNotebooks: runningResponse.setData,+ }}+ >+ <div className="absolute top-3 right-5 flex gap-2 z-10">+ <ConfigButton showAppConfig={false} />+ <ShutdownButton+ description={`This will shutdown the notebook server and terminate all running notebooks (${running.size}). You'll lose all data that's in memory.`}+ />+ </div>+ <div className="flex flex-col gap-6 max-w-5xl container pt-5 pb-20 z-10">+ <img src="logo.png" alt="marimo logo" className="w-64 mb-4" />+ <CreateNewNotebook />+ <NotebookList+ header={<Header Icon={PlayCircleIcon}>Running notebooks</Header>}+ files={[...running.values()]}+ />+ <NotebookList+ header={<Header Icon={ClockIcon}>Recent notebooks</Header>}+ files={recents.files}+ />+ <div className="flex flex-col gap-2">+ <Header+ Icon={BookTextIcon}+ control={+ <div className="flex items-center gap-2">+ <Input+ id="search"+ value={searchText}+ icon={<SearchIcon size={13} />}+ onChange={(e) => setSearchText(e.target.value)}+ placeholder="Search"+ className="mb-0 border-border"+ />+ <CollapseAllButton />+ <Checkbox+ data-testid="include-markdown-checkbox"+ id="include-markdown"+ checked={includeMarkdown}+ onCheckedChange={(checked) =>+ setIncludeMarkdown(Boolean(checked))+ }+ />+ <Label htmlFor="include-markdown">Include markdown</Label>+ </div>+ }+ >+ Workspace+ <RefreshCcwIcon+ className="w-4 h-4 ml-1 cursor-pointer opacity-70 hover:opacity-100"+ onClick={() => workspaceResponse.reload()}+ />+ {workspaceResponse.loading && <Spinner size="small" />}+ </Header>+ <div className="flex flex-col divide-y divide-[var(--slate-3)] border rounded overflow-hidden max-h-[48rem] overflow-y-auto shadow-sm bg-background">+ <NotebookFileTree+ searchText={searchText}+ files={workspace.files}/>- <Label htmlFor="include-markdown">Include markdown</Label></div>- }- files={workspace.files}- runningNotebooks={runningNotebooks}- setRunningNotebooks={runningResponse.setData}- />- {/* <NotebookFromOrCodeUrl /> */}- </div>+ </div>+ </div>+ </RunningNotebooksContext.Provider></Suspense>);};-const NotebookList: React.FC<{- header: string;- control?: React.ReactNode;- files: Array<{- name: string;- path: string;- sessionId?: string | null;- initializationId?: string | null;- }>;- runningNotebooks: Map<- string,- {- sessionId: SessionId;- initializationId: string;+const CollapseAllButton: React.FC = () => {+ const setOpenState = useSetAtom(expandedFoldersAtom);+ return (+ <Button+ variant="text"+ size="sm"+ className="h-fit"+ onClick={() => {+ setOpenState({});+ }}+ >+ <ChevronsDownUpIcon className="w-4 h-4 mr-1" />+ Collapse all+ </Button>+ );+};++const NotebookFileTree: React.FC<{+ files: FileInfo[];+ searchText?: string;+}> = ({ files, searchText }) => {+ const [openState, setOpenState] = useAtom(expandedFoldersAtom);+ const openStateIsEmpty = Object.keys(openState).length === 0;+ const ref = useRef<TreeApi<FileInfo>>();++ useEffect(() => {+ // If empty, collapse all+ if (openStateIsEmpty) {+ ref.current?.closeAll();}- >;- setRunningNotebooks: (data: WorkspaceFilesResponse) => void;-}> = ({ control, header, files, runningNotebooks, setRunningNotebooks }) => {- const { openConfirm, closeModal } = useImperativeModal();+ }, [openStateIsEmpty]);if (files.length === 0) {- return null;+ return (+ <div className="flex flex-col px-5 py-10 items-center justify-center">+ <p className="text-center text-muted-foreground">+ No files in this workspace+ </p>+ </div>+ );}return (- <div className="flex flex-col gap-4">- <div className="flex items-center justify-between gap-2">- <Header>{header}</Header>- {control}- </div>- <div- className="flex flex-col divide-y divide-[var(--slate-3)] border rounded overflow-hidden- max-h-[48rem] overflow-y-auto shadow-sm bg-background- "+ <Tree<FileInfo>+ ref={ref}+ width="100%"+ height={500}+ searchTerm={searchText}+ className="h-full"+ idAccessor={(data) => data.path}+ data={files}+ openByDefault={false}+ initialOpenState={openState}+ onToggle={async (id) => {+ const prevOpen = openState[id] ?? false;+ setOpenState({ ...openState, [id]: !prevOpen });+ }}+ padding={5}+ rowHeight={35}+ indent={15}+ overscanCount={1000}+ // Hide the drop cursor+ renderCursor={() => null}+ // Disable interactions+ disableDrop={true}+ disableDrag={true}+ disableEdit={true}+ disableMultiSelection={true}+ >+ {Node}+ </Tree>+ );+};++const Node = ({ node, style }: NodeRendererProps<FileInfo>) => {+ const fileType: FileType = node.data.isDirectory+ ? "directory"+ : guessFileType(node.data.name);++ const Icon = FILE_TYPE_ICONS[fileType];+ const iconEl = <Icon className="w-5 h-5 flex-shrink-0" strokeWidth={1.5} />;+ const root = useContext(RunningNotebooksContext).root;++ 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";+ if (node.data.isDirectory) {+ return (+ <span className={itemClassName}>+ {iconEl}+ {node.data.name}+ </span>+ );+ }++ const relativePath = node.data.path.startsWith(root)+ ? node.data.path.slice(root.length + 1)+ : node.data.path;++ const isMarkdown = relativePath.endsWith(".md");++ return (+ <a+ className={itemClassName}+ href={asURL(`?file=${relativePath}`).toString()}+ target={tabTarget(relativePath)}>+ {iconEl}+ <span className="flex-1 overflow-hidden text-ellipsis">+ {node.data.name}+ {isMarkdown && <MarkdownIcon className="ml-2 inline opacity-80" />}+ </span>+ <SessionShutdownButton filePath={relativePath} />+ <ExternalLinkIcon+ size={20}+ className="group-hover:opacity-100 opacity-0 text-primary"+ />+ </a>+ );+ };++ return (+ <div+ style={style}+ className={cn(+ "flex items-center cursor-pointer ml-1 text-muted-foreground whitespace-nowrap group h-full",+ )}+ onClick={(evt) => {+ evt.stopPropagation();+ if (node.data.isDirectory) {+ node.toggle();+ }+ }}+ >+ <FolderArrow node={node} />+ {renderItem()}+ </div>+ );+};++const FolderArrow = ({ node }: { node: NodeApi<FileInfo> }) => {+ if (!node.data.isDirectory) {+ return <span className="w-5 h-5 flex-shrink-0" />;+ }++ return node.isOpen ? (+ <ChevronDownIcon className="w-5 h-5 flex-shrink-0" />+ ) : (+ <ChevronRightIcon className="w-5 h-5 flex-shrink-0" />+ );+};++const NotebookList: React.FC<{+ header: React.ReactNode;+ files: MarimoFile[];+}> = ({ header, files }) => {+ if (files.length === 0) {+ return null;+ }++ return (+ <div className="flex flex-col gap-2">+ {header}+ <div className="flex flex-col divide-y divide-[var(--slate-3)] border rounded overflow-hidden max-h-[48rem] overflow-y-auto shadow-sm bg-background">{files.map((file) => {- // If path is a sessionId, then it has not been saved yet- // We want to keep the sessionId in this case- const isNewNotebook = isSessionId(file.path);- const href = isNewNotebook- ? asURL(`?file=${file.initializationId}&session_id=${file.path}`)- : asURL(`?file=${file.path}`);-- const isMarkdown = file.path.endsWith(".md");-- return (- <a- className="py-2 px-4 hover:bg-[var(--blue-2)] hover:text-primary transition-all duration-300 cursor-pointer group relative"- key={file.path}- href={href.toString()}- target={tabTarget(file.initializationId || file.path)}- >- <div className="flex flex-col justify-between">- <span className="flex items-center gap-2">- {file.name}- {isMarkdown && (- <span className="opacity-80">- <MarkdownIcon />- </span>- )}- </span>- <p- title={file.path}- className="text-sm text-muted-foreground- overflow-hidden whitespace-nowrap overflow-ellipsis- "- >- {file.path}- </p>- </div>- <div className="absolute right-16 top-0 bottom-0 flex items-center">- {runningNotebooks.has(file.path) && (- <Tooltip content="Shutdown">- <Button- size={"xs"}- variant="outline"- className="m-0 opacity-80 hover:opacity-100 hover:bg-accent text-destructive border-destructive hover:border-destructive hover:text-destructive bg-background hover:bg-[var(--red-1)]"- onClick={(e) => {- e.stopPropagation();- e.preventDefault();- openConfirm({- title: "Shutdown",- description:- "This will terminate the Python kernel. You'll lose all data that's in memory.",- variant: "destructive",- confirmAction: (- <AlertDialogDestructiveAction- onClick={(e) => {- const ids = runningNotebooks.get(file.path);- assertExists(ids);- shutdownSession({- sessionId: ids.sessionId,- }).then((response) => {- setRunningNotebooks(response);- });- closeModal();- toast({- description: "Notebook has been shutdown.",- });- }}- aria-label="Confirm Shutdown"- >- Shutdown- </AlertDialogDestructiveAction>- ),- });- }}- >- <PowerOffIcon size={16} />- </Button>- </Tooltip>- )}- </div>- <div- className={cn(- "absolute right-8 top-0 bottom-0 rounded-lg flex items-center justify-center text-muted-foreground text-primary",- )}- >- <ExternalLinkIcon- size={24}- className="absolute group-hover:opacity-100 opacity-0 transition-all duration-300"- />- </div>- </a>- );+ return <MarimoFileComponent key={file.path} file={file} />;})}</div></div>);};-const Header: React.FC<{ children: React.ReactNode }> = ({ children }) => {+const Header: React.FC<{+ Icon: React.FC<React.SVGProps<SVGSVGElement>>;+ control?: React.ReactNode;+ children: React.ReactNode;+}> = ({ Icon, control, children }) => {return (- <h2 className="text-xl font-semibold text-muted-foreground">{children}</h2>+ <div className="flex items-center justify-between gap-2">+ <h2 className="flex items-center gap-2 text-xl font-semibold text-muted-foreground select-none">+ <Icon className="h-5 w-5" />+ {children}+ </h2>+ {control}+ </div>+ );+};++const MarimoFileComponent = ({ file }: { file: MarimoFile }) => {+ // If path is a sessionId, then it has not been saved yet+ // We want to keep the sessionId in this case+ const isNewNotebook = isSessionId(file.path);+ const href = isNewNotebook+ ? asURL(`?file=${file.initializationId}&session_id=${file.path}`)+ : asURL(`?file=${file.path}`);++ const isMarkdown = file.path.endsWith(".md");++ return (+ <a+ className="py-1.5 px-4 hover:bg-[var(--blue-2)] hover:text-primary transition-all duration-300 cursor-pointer group relative flex items-end gap-4 items-center"+ key={file.path}+ href={href.toString()}+ target={tabTarget(file.initializationId || file.path)}+ >+ <div className="flex flex-col justify-between flex-1">+ <span className="flex items-center gap-2">+ {file.name}+ {isMarkdown && (+ <span className="opacity-80">+ <MarkdownIcon />+ </span>+ )}+ </span>+ <p+ title={file.path}+ className="text-sm text-muted-foreground overflow-hidden whitespace-nowrap overflow-ellipsis"+ >+ {file.path}+ </p>+ </div>+ <div className="flex flex-col gap-1 items-end">+ <div className="flex gap-3 items-center">+ <div>+ <SessionShutdownButton filePath={file.path} />+ </div>+ <ExternalLinkIcon+ size={20}+ className="group-hover:opacity-100 opacity-0 transition-all duration-300 text-primary"+ />+ </div>+ {!!file.lastModified && (+ <div className="text-xs text-muted-foreground opacity-80">+ {timeAgo(file.lastModified * 1000)}+ </div>+ )}+ </div>+ </a>+ );+};++const SessionShutdownButton: React.FC<{ filePath: string }> = ({+ filePath,+}) => {+ const { openConfirm, closeModal } = useImperativeModal();+ const { runningNotebooks, setRunningNotebooks } = useContext(+ RunningNotebooksContext,+ );+ if (!runningNotebooks.has(filePath)) {+ return null;+ }+ return (+ <Tooltip content="Shutdown">+ <Button+ size={"icon"}+ variant="outline"+ className="opacity-80 hover:opacity-100 hover:bg-accent text-destructive border-destructive hover:border-destructive hover:text-destructive bg-background hover:bg-[var(--red-1)]"+ onClick={(e) => {+ e.stopPropagation();+ e.preventDefault();+ openConfirm({+ title: "Shutdown",+ description:+ "This will terminate the Python kernel. You'll lose all data that's in memory.",+ variant: "destructive",+ confirmAction: (+ <AlertDialogDestructiveAction+ onClick={(e) => {+ const ids = runningNotebooks.get(filePath);+ assertExists(ids);+ shutdownSession({+ sessionId: ids.sessionId as SessionId,+ }).then((response) => {+ setRunningNotebooks(+ Maps.keyBy(response.files, (file) => file.path),+ );+ });+ closeModal();+ toast({+ description: "Notebook has been shutdown.",+ });+ }}+ aria-label="Confirm Shutdown"+ >+ Shutdown+ </AlertDialogDestructiveAction>+ ),+ });+ }}+ >+ <PowerOffIcon size={14} />+ </Button>+ </Tooltip>);};@@ -295,19 +497,4 @@ const CreateNewNotebook: React.FC = () => {);};-// const NotebookFromOrCodeUrl: React.FC = () => {-// return (-// <div className="flex flex-col gap-2">-// <h3 className="text-lg font-semibold">-// Open a notebook from URL or paste code-// </h3>-// <Input-// className="h-12 px-4 border-border"-// type="text"-// placeholder="Enter URL"-// />-// </div>-// );-// };-export default HomePage;diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 3004a98b01..28a3f0ccd6 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -75,6 +75,7 @@ export type UsageResponse =paths["/api/usage"]["get"]["responses"]["200"]["content"]["application/json"];export type WorkspaceFilesRequest = schemas["WorkspaceFilesRequest"];export type WorkspaceFilesResponse = schemas["WorkspaceFilesResponse"];+export type RunningNotebooksResponse = schemas["RunningNotebooksResponse"];/*** Requests sent to the BE during run/edit mode.@@ -129,10 +130,10 @@ export interface EditRequests {getWorkspaceFiles: (request: WorkspaceFilesRequest,) => Promise<WorkspaceFilesResponse>;- getRunningNotebooks: () => Promise<WorkspaceFilesResponse>;+ getRunningNotebooks: () => Promise<RunningNotebooksResponse>;shutdownSession: (request: ShutdownSessionRequest,- ) => Promise<WorkspaceFilesResponse>;+ ) => Promise<RunningNotebooksResponse>;exportAsHTML: (request: ExportAsHTMLRequest) => Promise<string>;exportAsMarkdown: (request: ExportAsMarkdownRequest) => Promise<string>;}diff --git a/frontend/src/hooks/useAsyncData.ts b/frontend/src/hooks/useAsyncData.tsindex 2ec62ff8da..67d4f54ab5 100644--- a/frontend/src/hooks/useAsyncData.ts+++ b/frontend/src/hooks/useAsyncData.ts@@ -7,19 +7,23 @@ interface AsyncDataResponse<T> {loading: boolean;error: Error | undefined;setData: Dispatch<SetStateAction<T | undefined>>;+ reload: () => void;}-export function combineAsyncData<T, U>(- a: AsyncDataResponse<T>,- b: AsyncDataResponse<U>,-): Omit<AsyncDataResponse<[T, U]>, "setData"> {+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export function combineAsyncData<T extends any[]>(+ ...responses: { [K in keyof T]: AsyncDataResponse<T[K]> }+): Omit<AsyncDataResponse<T>, "setData"> {return {- data:- a.data === undefined || b.data === undefined- ? undefined- : [a.data, b.data],- loading: a.loading || b.loading,- error: a.error || b.error,+ data: responses.every((response) => response.data !== undefined)+ ? (responses.map((response) => response.data) as T)+ : undefined,+ loading: responses.some((response) => response.loading),+ error:+ responses.find((response) => response.error !== null)?.error || undefined,+ reload: () => {+ responses.forEach((response) => response.reload());+ },};}@@ -44,6 +48,7 @@ export function useAsyncData<T>(const [data, setData] = useState<T | undefined>(undefined);const [loading, setLoading] = useState<boolean>(true);const [error, setError] = useState<Error | undefined>(undefined);+ const [nonce, setNonce] = useState(0);const asProps =typeof loaderOrProps === "function"@@ -88,7 +93,13 @@ export function useAsyncData<T>(isCancelled = true;};// eslint-disable-next-line react-hooks/exhaustive-deps- }, deps);+ }, [...deps, nonce]);- return { data, loading, error, setData };+ return {+ data,+ loading,+ error,+ setData,+ reload: () => setNonce(nonce + 1),+ };}diff --git a/frontend/src/utils/dates.ts b/frontend/src/utils/dates.tsindex f7930c550c..0f537cffe5 100644--- a/frontend/src/utils/dates.ts+++ b/frontend/src/utils/dates.ts@@ -17,3 +17,51 @@ export function prettyDate(value: string | number | null | undefined): string {return value.toString();}}++/**+ * If today, it should say "Today at 8:00 AM".+ *+ * If yesterday, it should say "Yesterday at 8:00 AM".+ *+ * If a date in the past, it should say "<date> at 8:00 AM".+ */+export function timeAgo(value: string | number | null | undefined): string {+ if (value == null) {+ return "";+ }+ if (value === 0) {+ return "";+ }++ try {+ const date = new Date(value);+ const today = new Date();+ const yesterday = new Date();+ yesterday.setDate(yesterday.getDate() - 1);++ if (date.toDateString() === today.toDateString()) {+ return `Today at ${date.toLocaleTimeString(undefined, {+ hour: "numeric",+ minute: "numeric",+ })}`;+ } else if (date.toDateString() === yesterday.toDateString()) {+ return `Yesterday at ${date.toLocaleTimeString(undefined, {+ hour: "numeric",+ minute: "numeric",+ })}`;+ } else {+ return `${date.toLocaleDateString(undefined, {+ year: "numeric",+ month: "short",+ day: "numeric",+ })} at ${date.toLocaleTimeString(undefined, {+ hour: "numeric",+ minute: "numeric",+ })}`;+ }+ } catch (error) {+ Logger.warn("Failed to parse date", error);+ }++ return value.toString();+}diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex d2d75839aa..94216bc20a 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -120,6 +120,7 @@ def _generate_schema() -> dict[str, Any]:files.FileUpdateRequest,files.FileUpdateResponse,home.RecentFilesResponse,+ home.RunningNotebooksResponse,home.ShutdownSessionRequest,home.WorkspaceFilesRequest,home.WorkspaceFilesResponse,diff --git a/marimo/_server/api/endpoints/home.py b/marimo/_server/api/endpoints/home.pyindex e963d8d1c3..e518ac96be 100644--- a/marimo/_server/api/endpoints/home.py+++ b/marimo/_server/api/endpoints/home.py@@ -14,6 +14,7 @@ from marimo._server.model import ConnectionStatefrom marimo._server.models.home import (MarimoFile,RecentFilesResponse,+ RunningNotebooksResponse,ShutdownSessionRequest,WorkspaceFilesRequest,WorkspaceFilesResponse,@@ -74,13 +75,18 @@ async def workspace_files(session_manager = AppState(request).session_manager# Maybe enable markdown+ root = ""if isinstance(session_manager.file_router, LazyListOfFilesAppFileRouter):+ # Mark stale in case new files are added+ session_manager.file_router.mark_stale()+ # Toggle markdownsession_manager.file_router = (session_manager.file_router.toggle_markdown(body.include_markdown))+ root = session_manager.file_router.directoryfiles = session_manager.file_router.files- return WorkspaceFilesResponse(files=files)+ return WorkspaceFilesResponse(files=files, root=root)def _get_active_sessions(app_state: AppState) -> List[MarimoFile]:@@ -108,7 +114,7 @@ def _get_active_sessions(app_state: AppState) -> List[MarimoFile]:async def running_notebooks(*,request: Request,-) -> WorkspaceFilesResponse:+) -> RunningNotebooksResponse:"""responses:200:@@ -116,10 +122,10 @@ async def running_notebooks(content:application/json:schema:- $ref: "#/components/schemas/WorkspaceFilesResponse"+ $ref: "#/components/schemas/RunningNotebooksResponse""""app_state = AppState(request)- return WorkspaceFilesResponse(files=_get_active_sessions(app_state))+ return RunningNotebooksResponse(files=_get_active_sessions(app_state))@router.post("/shutdown_session")@@ -127,7 +133,7 @@ async def running_notebooks(async def shutdown_session(*,request: Request,-) -> WorkspaceFilesResponse:+) -> RunningNotebooksResponse:"""requestBody:content:@@ -140,9 +146,9 @@ async def shutdown_session(content:application/json:schema:- $ref: "#/components/schemas/WorkspaceFilesResponse"+ $ref: "#/components/schemas/RunningNotebooksResponse""""app_state = AppState(request)body = await parse_request(request, cls=ShutdownSessionRequest)app_state.session_manager.close_session(body.session_id)- return WorkspaceFilesResponse(files=_get_active_sessions(app_state))+ return RunningNotebooksResponse(files=_get_active_sessions(app_state))diff --git a/marimo/_server/file_router.py b/marimo/_server/file_router.pyindex 337b79f25b..d981284b27 100644--- a/marimo/_server/file_router.py+++ b/marimo/_server/file_router.py@@ -9,6 +9,8 @@ from marimo import _loggersfrom marimo._config.config import WidthTypefrom marimo._server.api.status import HTTPException, HTTPStatusfrom marimo._server.file_manager import AppFileManager+from marimo._server.files.os_file_system import natural_sort_file+from marimo._server.models.files import FileInfofrom marimo._server.models.home import MarimoFilefrom marimo._utils.marimo_path import MarimoPath@@ -112,9 +114,9 @@ class AppFileRouter(abc.ABC):@property@abc.abstractmethod- def files(self) -> List[MarimoFile]:+ def files(self) -> List[FileInfo]:"""- Get all files.+ Get all files in a recursive tree."""pass@@ -127,7 +129,7 @@ class NewFileAppFileRouter(AppFileRouter):return None@property- def files(self) -> List[MarimoFile]:+ def files(self) -> List[FileInfo]:return []@@ -136,8 +138,18 @@ class ListOfFilesAppFileRouter(AppFileRouter):self._files = files@property- def files(self) -> List[MarimoFile]:- return self._files+ def files(self) -> List[FileInfo]:+ return [+ FileInfo(+ id=file.path,+ name=file.name,+ path=file.path,+ last_modified=file.last_modified,+ is_directory=False,+ is_marimo_file=True,+ )+ for file in self._files+ ]def get_unique_file_key(self) -> Optional[MarimoFileKey]:if len(self.files) == 1:@@ -146,7 +158,12 @@ class ListOfFilesAppFileRouter(AppFileRouter):def maybe_get_single_file(self) -> Optional[MarimoFile]:if len(self.files) == 1:- return self.files[0]+ file = self.files[0]+ return MarimoFile(+ name=file.name,+ path=file.path,+ last_modified=file.last_modified,+ )return None@@ -154,7 +171,7 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):def __init__(self, directory: str, include_markdown: bool) -> None:self.directory = directoryself.include_markdown = include_markdown- self._lazy_files: Optional[List[MarimoFile]] = None+ self._lazy_files: Optional[List[FileInfo]] = Nonedef toggle_markdown(self, include_markdown: bool@@ -166,60 +183,67 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):)return self+ def mark_stale(self) -> None:+ self._lazy_files = None+@property- def files(self) -> List[MarimoFile]:+ def files(self) -> List[FileInfo]:if self._lazy_files is None:self._lazy_files = self._load_files()return self._lazy_files- def _load_files(self) -> List[MarimoFile]:- directory = self.directory- # Recursively find all .py files that contain the string "marimo.App"- # Max depth of 5 to avoid searching the entire filesystem+ def _load_files(self) -> List[FileInfo]:+ def recurse(+ directory: str, depth: int = 0+ ) -> Optional[List[FileInfo]]:+ if depth > MAX_DEPTH:+ return None+ entries = os.listdir(directory)+ files: List[FileInfo] = []+ folders: List[FileInfo] = []+ for entry in entries:+ full_path = os.path.join(directory, entry)+ if os.path.isdir(full_path):+ if entry in skip_dirs or depth == MAX_DEPTH:+ continue+ children = recurse(full_path, depth + 1)+ if children:+ folders.append(+ FileInfo(+ id=full_path,+ path=full_path,+ name=entry,+ is_directory=True,+ is_marimo_file=False,+ children=children,+ )+ )+ else:+ if any(+ entry.endswith(ext) for ext in allowed_extensions+ ) and self._is_marimo_app(full_path):+ files.append(+ FileInfo(+ id=full_path,+ path=full_path,+ name=entry,+ is_directory=False,+ is_marimo_file=True,+ last_modified=os.path.getmtime(full_path),+ )+ )+ # Sort folders then files, based on natural sort (alpha, then num)+ return sorted(folders, key=natural_sort_file) + sorted(+ files, key=natural_sort_file+ )+MAX_DEPTH = 5- files: List[MarimoFile] = []skip_dirs = {".git", ".venv", "__pycache__", "node_modules"}allowed_extensions = ({".py", ".md"} if self.include_markdown else {".py"})- LOGGER.debug("Searching directory %s", directory)- cwd = os.getcwd()- for root, dirnames, filenames in os.walk(directory, topdown=True):- # Skip directories that are too deep- depth = root[len(directory) :].count(os.sep)- if depth >= MAX_DEPTH:- # mutating `dirnames` like this prunes all the dirs in it- # from the search- dirnames[:] = []- continue- # Skip directories that we don't want to search- root_name = os.path.basename(root)- if root_name in skip_dirs:- continue- # Iterate over all files in the directory- for filename in filenames:- if not any(- filename.endswith(ext) for ext in allowed_extensions- ):- continue- full_path = os.path.join(root, filename)- shortest_path = (- os.path.relpath(full_path, cwd)- if full_path.startswith(cwd)- else full_path- )- # Python files must contain "marimo.App", or markdown files- if self._is_marimo_app(full_path):- files.append(- MarimoFile(- name=filename,- path=shortest_path,- last_modified=os.path.getmtime(full_path),- )- )- LOGGER.debug("Found %d files in directory %s", len(files), directory)- return files+ return recurse(self.directory) or []def _is_marimo_app(self, full_path: str) -> bool:try:@@ -228,7 +252,7 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):if path.is_markdown():return "marimo-version:" in contentsif path.is_python():- return "marimo.App" in contents+ return "marimo.App" in contents and "import marimo" in contentsreturn Falseexcept Exception as e:LOGGER.debug("Error reading file %s: %s", full_path, e)diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pyindex 67c311a044..2ab2f64aaa 100644--- a/marimo/_server/files/os_file_system.py+++ b/marimo/_server/files/os_file_system.py@@ -51,7 +51,7 @@ class OSFileSystem(FileSystem):is_directory=is_directory,is_marimo_file=not is_directoryand self._is_marimo_file(entry.path),- last_modified_date=entry_stat.st_mtime,+ last_modified=entry_stat.st_mtime,)if is_directory:folders.append(info)@@ -71,7 +71,7 @@ class OSFileSystem(FileSystem):name=os.path.basename(path),is_directory=is_directory,is_marimo_file=not is_directory and self._is_marimo_file(path),- last_modified_date=stat.st_mtime,+ last_modified=stat.st_mtime,)def get_details(diff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.pyindex 28c2e9f235..a914b2d6d1 100644--- a/marimo/_server/models/files.py+++ b/marimo/_server/models/files.py@@ -14,7 +14,7 @@ class FileInfo:name: stris_directory: boolis_marimo_file: bool- last_modified_date: Optional[float] = None+ last_modified: Optional[float] = Nonechildren: List["FileInfo"] = field(default_factory=list)diff --git a/marimo/_server/models/home.py b/marimo/_server/models/home.pyindex 1ad66dcfb8..1249cf5455 100644--- a/marimo/_server/models/home.py+++ b/marimo/_server/models/home.py@@ -5,6 +5,7 @@ from dataclasses import dataclassfrom typing import List, Optionalfrom marimo._server.ids import SessionId+from marimo._server.models.files import FileInfo@dataclass@@ -14,7 +15,7 @@ class MarimoFile:# Absolute path to the filepath: str# Last modified time of the file- last_modified: float+ last_modified: Optional[float] = None# Session idsession_id: Optional[SessionId] = None# Session initialization id@@ -27,6 +28,11 @@ class RecentFilesResponse:files: List[MarimoFile]+@dataclass+class RunningNotebooksResponse:+ files: List[MarimoFile]++@dataclassclass WorkspaceFilesRequest:include_markdown: bool = False@@ -34,7 +40,8 @@ class WorkspaceFilesRequest:@dataclassclass WorkspaceFilesResponse:- files: List[MarimoFile]+ root: str+ files: List[FileInfo]@dataclassdiff --git a/marimo/_server/recents.py b/marimo/_server/recents.pyindex c648c5d0cc..2d8417152a 100644--- a/marimo/_server/recents.py+++ b/marimo/_server/recents.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import osimport pathlibfrom dataclasses import dataclass, field@@ -24,7 +26,7 @@ def _is_tmp_file(filename: str) -> bool:class RecentFilesManager:- MAX_FILES = 10+ MAX_FILES = 5LOCATION = "recent_files.toml"def __init__(self) -> None:@@ -70,7 +72,8 @@ class RecentFilesManager:files: List[MarimoFile] = []cwd = pathlib.Path.cwd()- for file in state.files:+ limited_files = state.files[: self.MAX_FILES]+ for file in limited_files:file_path = pathlib.Path(file)if _is_tmp_file(file) or cwd not in file_path.parents:continuediff --git a/openapi/api.yaml b/openapi/api.yamlindex 73354d2a6a..163f8505c9 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -6,12 +6,19 @@ components:type: stringincludeOtherCode:type: string+ language:+ enum:+ - python+ - markdown+ - sql+ type: stringprompt:type: stringrequired:- prompt- includeOtherCode- code+ - languagetype: objectAlert:properties:@@ -570,7 +577,7 @@ components:type: booleanisMarimoFile:type: boolean- lastModifiedDate:+ lastModified:nullable: truetype: numbername:@@ -1115,6 +1122,7 @@ components:nullable: truetype: stringlastModified:+ nullable: truetype: numbername:type: string@@ -1126,7 +1134,6 @@ components:required:- name- path- - lastModifiedtype: objectMarimoInterruptionError:properties:@@ -1406,6 +1413,15 @@ components:- cellIds- codestype: object+ RunningNotebooksResponse:+ properties:+ files:+ items:+ $ref: '#/components/schemas/MarimoFile'+ type: array+ required:+ - files+ type: objectSaveAppConfigurationRequest:properties:config:@@ -1673,14 +1689,17 @@ components:properties:files:items:- $ref: '#/components/schemas/MarimoFile'+ $ref: '#/components/schemas/FileInfo'type: array+ root:+ type: stringrequired:+ - root- filestype: objectinfo:title: marimo API- version: 0.6.25+ version: 0.7.1openapi: 3.1.0paths:/@file/{filename_and_length}:@@ -1889,7 +1908,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/WorkspaceFilesResponse'+ $ref: '#/components/schemas/RunningNotebooksResponse'description: Get the running files/api/home/shutdown_session:post:@@ -1903,7 +1922,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/WorkspaceFilesResponse'+ $ref: '#/components/schemas/RunningNotebooksResponse'description: Shutdown the current session/api/home/workspace_files:post:diff --git a/openapi/pnpm-lock.yaml b/openapi/pnpm-lock.yamlindex 8eebaecdfd..24e158d146 100644--- a/openapi/pnpm-lock.yaml+++ b/openapi/pnpm-lock.yaml@@ -6,8 +6,8 @@ settings:dependencies:openapi-fetch:- specifier: ^0.10.2- version: 0.10.2+ specifier: 0.9.7+ version: 0.9.7devDependencies:openapi-typescript:@@ -129,14 +129,14 @@ packages:picomatch: 2.3.1dev: true- resolution: {integrity: sha512-GCzgKIZchnxZRnztiOlRTKk9tQT0NHvs5MNXYFtOwG7xaj1iCJOGDsTLbn/2QUP37PjGTT890qERFjvmjxzQMg==}+ resolution: {integrity: sha512-NMp/GEmWSGO0b2d731IdGXcMP2PF85Rk1q+oy2Mx/DYMdP3pgTZTRamKxgZpkHhM4iOVsyD1iP5HKL9Fr6CH2Q==}dependencies:- openapi-typescript-helpers: 0.0.9+ openapi-typescript-helpers: 0.0.8dev: false- resolution: {integrity: sha512-BO2TvIDAO/FPVKz1Nj2gy+pUOHfaoENdK5UP3H0Jbh0VXBf3dwYMs58ZwOjiezrbHA2LamdquoyQgahTPvIxGA==}+ resolution: {integrity: sha512-1eNjQtbfNi5Z/kFhagDIaIRj6qqDzhjNJKz8cmMW0CVdGwT6e1GLbAfgI0d28VTJa1A8jz82jm/4dG8qNoNS8g==}dev: falsediff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 24c4b8ef9a..81f9ce56aa 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -269,7 +269,7 @@ export interface paths {/** @description Get the running files */200: {content: {- "application/json": components["schemas"]["WorkspaceFilesResponse"];+ "application/json": components["schemas"]["RunningNotebooksResponse"];};};};@@ -286,7 +286,7 @@ export interface paths {/** @description Shutdown the current session */200: {content: {- "application/json": components["schemas"]["WorkspaceFilesResponse"];+ "application/json": components["schemas"]["RunningNotebooksResponse"];};};};@@ -736,6 +736,8 @@ export interface components {AiCompletionRequest: {code: string;includeOtherCode: string;+ /** @enum {string} */+ language: "python" | "markdown" | "sql";prompt: string;};Alert: {@@ -962,7 +964,7 @@ export interface components {id: string;isDirectory: boolean;isMarimoFile: boolean;- lastModifiedDate?: number | null;+ lastModified?: number | null;name: string;path: string;};@@ -1176,7 +1178,7 @@ export interface components {};MarimoFile: {initializationId?: string | null;- lastModified: number;+ lastModified?: number | null;name: string;path: string;sessionId?: string | null;@@ -1308,6 +1310,9 @@ export interface components {cellIds: string[];codes: string[];};+ RunningNotebooksResponse: {+ files: components["schemas"]["MarimoFile"][];+ };SaveAppConfigurationRequest: {config: {[key: string]: unknown;@@ -1408,7 +1413,8 @@ export interface components {includeMarkdown: boolean;};WorkspaceFilesResponse: {- files: components["schemas"]["MarimoFile"][];+ files: components["schemas"]["FileInfo"][];+ root: string;};};responses: never;