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: open the totutorials from the homepage (#2157)
Myles Scolnick05bf87340473
diff --git a/frontend/src/components/pages/home-page.tsx b/frontend/src/components/pages/home-page.tsxindex f8dc805f14..b4badd8e81 100644--- a/frontend/src/components/pages/home-page.tsx+++ b/frontend/src/components/pages/home-page.tsx@@ -4,18 +4,29 @@ import {getRecentFiles,getRunningNotebooks,shutdownSession,+ openTutorial,} from "@/core/network/requests";import { combineAsyncData, useAsyncData } from "@/hooks/useAsyncData";import type React from "react";import { Suspense, useContext, useEffect, useRef, useState } from "react";import { Spinner } from "../icons/spinner";import {+ ActivityIcon,+ BarChart2Icon,+ BookOpenIcon,BookTextIcon,ChevronDownIcon,ChevronRightIcon,ChevronsDownUpIcon,ClockIcon,+ DatabaseIcon,ExternalLinkIcon,+ FileIcon,+ FileTextIcon,+ GraduationCapIcon,+ GridIcon,+ LayoutIcon,+ OrbitIcon,PlayCircleIcon,PowerOffIcon,RefreshCcwIcon,@@ -35,7 +46,7 @@ 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 type { FileInfo, MarimoFile } from "@/core/network/types";+import type { FileInfo, MarimoFile, TutorialId } from "@/core/network/types";import { ConfigButton } from "../app-config/app-config-button";import { Checkbox } from "@/components/ui/checkbox";import { Label } from "@/components/ui/label";@@ -63,6 +74,14 @@ import {import { Maps } from "@/utils/maps";import { Input } from "../ui/input";import { Paths } from "@/utils/paths";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+} from "@/components/ui/dropdown-menu";+import { Objects } from "@/utils/objects";+import { CaretDownIcon } from "@radix-ui/react-icons";function tabTarget(path: string) {// Consistent tab target so we open in the same tab when clicking on the same notebook@@ -119,7 +138,8 @@ const HomePage: React.FC = () => {setRunningNotebooks: runningResponse.setData,}}>- <div className="absolute top-3 right-5 flex gap-2 z-10">+ <div className="absolute top-3 right-5 flex gap-2 z-50">+ <OpenTutorialDropDown /><ConfigButton showAppConfig={false} /><ShutdownButtondescription={`This will shutdown the notebook server and terminate all running notebooks (${running.size}). You'll lose all data that's in memory.`}@@ -516,4 +536,51 @@ const CreateNewNotebook: React.FC = () => {);};+const TUTORIALS: Record<+ TutorialId,+ [string, React.FC<React.SVGProps<SVGSVGElement>>]+> = {+ intro: ["Introduction", BookOpenIcon],+ dataflow: ["Dataflow", ActivityIcon],+ ui: ["UI Elements", LayoutIcon],+ markdown: ["Markdown", FileTextIcon],+ plots: ["Plots", BarChart2Icon],+ sql: ["SQL", DatabaseIcon],+ layout: ["Layout", GridIcon],+ fileformat: ["File format", FileIcon],+ "for-jupyter-users": ["For Jupyter users", OrbitIcon],+ "markdown-format": ["Markdown format", MarkdownIcon],+};++const OpenTutorialDropDown: React.FC = () => {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild={true}>+ <Button data-testid="open-tutorial-button" size="xs" variant="outline">+ <GraduationCapIcon className="w-4 h-4 mr-2" />+ Tutorials+ <CaretDownIcon className="w-3 h-3 ml-1" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent side="bottom" className="no-print">+ {Objects.entries(TUTORIALS).map(([tutorialId, [label, Icon]]) => (+ <DropdownMenuItem+ key={tutorialId}+ onSelect={async () => {+ const file = await openTutorial({ tutorialId });+ if (!file) {+ return;+ }+ window.open(asURL(`?file=${file.path}`).toString(), "_blank");+ }}+ >+ <Icon strokeWidth={1.5} className="w-4 h-4 mr-2" />+ {label}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+};+export default HomePage;diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.tsindex 8085dc68ac..d3bfe1f894 100644--- a/frontend/src/core/islands/bridge.ts+++ b/frontend/src/core/islands/bridge.ts@@ -148,6 +148,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {sendRenameFileOrFolder = throwNotImplemented;sendUpdateFile = throwNotImplemented;sendFileDetails = throwNotImplemented;+ openTutorial = throwNotImplemented;exportAsHTML = throwNotImplemented;exportAsMarkdown = throwNotImplemented;getRecentFiles = throwNotImplemented;diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.tsindex 3367d4a81a..b1cfa3bb9b 100644--- a/frontend/src/core/network/requests-network.ts+++ b/frontend/src/core/network/requests-network.ts@@ -207,6 +207,13 @@ export function createNetworkRequests(): EditRequests & RunRequests {}).then(handleResponse);},+ openTutorial: (request) => {+ return marimoClient+ .POST("/api/home/tutorial/open", {+ body: request,+ })+ .then(handleResponse);+ },getRecentFiles: () => {return marimoClient.POST("/api/home/recent_files").then(handleResponse);},diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.tsindex beef5e2dd1..1aaf22b20f 100644--- a/frontend/src/core/network/requests-static.ts+++ b/frontend/src/core/network/requests-static.ts@@ -57,6 +57,7 @@ export function createStaticRequests(): EditRequests & RunRequests {sendRenameFileOrFolder: throwNotInEditMode,sendUpdateFile: throwNotInEditMode,sendFileDetails: throwNotInEditMode,+ openTutorial: throwNotInEditMode,sendInstallMissingPackages: throwNotInEditMode,getRecentFiles: throwNotInEditMode,getWorkspaceFiles: throwNotInEditMode,diff --git a/frontend/src/core/network/requests-toasting.ts b/frontend/src/core/network/requests-toasting.tsindex b56b697247..035633b4df 100644--- a/frontend/src/core/network/requests-toasting.ts+++ b/frontend/src/core/network/requests-toasting.ts@@ -38,6 +38,7 @@ export function createErrorToastingRequests(sendRenameFileOrFolder: "Failed to rename file or folder",sendUpdateFile: "Failed to update file",sendFileDetails: "Failed to get file details",+ openTutorial: "Failed to open tutorial",sendInstallMissingPackages: "Failed to install missing packages",getRecentFiles: "Failed to get recent files",getWorkspaceFiles: "Failed to get workspace files",diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex 58c7dd8503..06d7bce9dc 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -56,6 +56,7 @@ export const {sendRenameFileOrFolder,sendUpdateFile,sendFileDetails,+ openTutorial,getRecentFiles,getWorkspaceFiles,getRunningNotebooks,diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex c78b596d71..9625c47c86 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -77,6 +77,8 @@ export type UsageResponse =export type WorkspaceFilesRequest = schemas["WorkspaceFilesRequest"];export type WorkspaceFilesResponse = schemas["WorkspaceFilesResponse"];export type RunningNotebooksResponse = schemas["RunningNotebooksResponse"];+export type OpenTutorialRequest = schemas["OpenTutorialRequest"];+export type TutorialId = OpenTutorialRequest["tutorialId"];/*** Requests sent to the BE during run/edit mode.@@ -128,6 +130,7 @@ export interface EditRequests {sendUpdateFile: (request: FileUpdateRequest) => Promise<FileUpdateResponse>;sendFileDetails: (request: { path: string }) => Promise<FileDetailsResponse>;// Homepage requests+ openTutorial: (request: OpenTutorialRequest) => Promise<MarimoFile>;getRecentFiles: () => Promise<RecentFilesResponse>;getWorkspaceFiles: (request: WorkspaceFilesRequest,diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.tsindex 0f71d4ac0b..6e6cd1ce44 100644--- a/frontend/src/core/wasm/bridge.ts+++ b/frontend/src/core/wasm/bridge.ts@@ -415,6 +415,7 @@ export class PyodideBridge implements RunRequests, EditRequests {};syncCellIds = () => Promise.resolve(null);getUsageStats = throwNotImplemented;+ openTutorial = throwNotImplemented;getRecentFiles = throwNotImplemented;getWorkspaceFiles = throwNotImplemented;getRunningNotebooks = throwNotImplemented;diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex 158ed6ecf9..cb8f847177 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -6,7 +6,7 @@ import osimport pathlibimport sysimport tempfile-from typing import Any, Optional, get_args+from typing import Any, Optionalimport click@@ -28,9 +28,8 @@ from marimo._server.model import SessionModefrom marimo._server.start import startfrom marimo._server.tokens import AuthTokenfrom marimo._tutorials import (- PythonTutorial,Tutorial,- get_tutorial_source,+ create_temp_tutorial_file,tutorial_order,)from marimo._utils.marimo_path import MarimoPath@@ -669,12 +668,8 @@ def tutorial(token_password: Optional[str],name: Tutorial,) -> None:- source = get_tutorial_source(name)- d = tempfile.TemporaryDirectory()- extension = "py" if name in get_args(PythonTutorial) else "md"- fname = os.path.join(d.name, f"{name}.{extension}")- path = MarimoPath(fname)- path.write_text(source)+ temp_dir = tempfile.TemporaryDirectory()+ path = create_temp_tutorial_file(name, temp_dir)start(file_router=AppFileRouter.from_filename(path),diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex 5258ed2af8..9169d61fef 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -132,6 +132,7 @@ def _generate_schema() -> dict[str, Any]:files.FileMoveResponse,files.FileUpdateRequest,files.FileUpdateResponse,+ home.OpenTutorialRequest,home.RecentFilesResponse,home.RunningNotebooksResponse,home.ShutdownSessionRequest,diff --git a/marimo/_server/api/endpoints/home.py b/marimo/_server/api/endpoints/home.pyindex e518ac96be..e4a9a75acc 100644--- a/marimo/_server/api/endpoints/home.py+++ b/marimo/_server/api/endpoints/home.py@@ -2,9 +2,11 @@from __future__ import annotationsimport os+import tempfilefrom typing import TYPE_CHECKING, Listfrom starlette.authentication import requires+from starlette.responses import JSONResponsefrom marimo import _loggersfrom marimo._server.api.deps import AppState@@ -13,6 +15,7 @@ from marimo._server.file_router import LazyListOfFilesAppFileRouterfrom marimo._server.model import ConnectionStatefrom marimo._server.models.home import (MarimoFile,+ OpenTutorialRequest,RecentFilesResponse,RunningNotebooksResponse,ShutdownSessionRequest,@@ -20,6 +23,7 @@ from marimo._server.models.home import (WorkspaceFilesResponse,)from marimo._server.router import APIRouter+from marimo._tutorials import create_temp_tutorial_filefrom marimo._utils.paths import pretty_pathif TYPE_CHECKING:@@ -152,3 +156,41 @@ async def shutdown_session(body = await parse_request(request, cls=ShutdownSessionRequest)app_state.session_manager.close_session(body.session_id)return RunningNotebooksResponse(files=_get_active_sessions(app_state))++[email protected]("/tutorial/open")+@requires("edit")+async def tutorial(+ *,+ request: Request,+) -> MarimoFile | JSONResponse:+ """+ requestBody:+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/OpenTutorialRequest"+ responses:+ 200:+ description: Open a new tutorial+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/MarimoFile"+ """+ # Create a new tutorial file and return the filepath+ try:+ body = await parse_request(request, cls=OpenTutorialRequest)+ except ValueError:+ return JSONResponse({"detail": "Tutorial not found"}, status_code=400)+ temp_dir = tempfile.TemporaryDirectory()+ path = create_temp_tutorial_file(body.tutorial_id, temp_dir)++ import atexit++ atexit.register(temp_dir.cleanup)++ return MarimoFile(+ name=os.path.basename(path.absolute_name),+ path=path.absolute_name,+ )diff --git a/marimo/_server/models/home.py b/marimo/_server/models/home.pyindex 1249cf5455..3381b6737e 100644--- a/marimo/_server/models/home.py+++ b/marimo/_server/models/home.py@@ -6,6 +6,7 @@ from typing import List, Optionalfrom marimo._server.ids import SessionIdfrom marimo._server.models.files import FileInfo+from marimo._tutorials import Tutorial@dataclass@@ -33,6 +34,11 @@ class RunningNotebooksResponse:files: List[MarimoFile]+@dataclass+class OpenTutorialRequest:+ tutorial_id: Tutorial++@dataclassclass WorkspaceFilesRequest:include_markdown: bool = Falsediff --git a/marimo/_server/router.py b/marimo/_server/router.pyindex 0eb2c685ff..779ed6292e 100644--- a/marimo/_server/router.py+++ b/marimo/_server/router.py@@ -62,6 +62,8 @@ class APIRouter(Router):return responseif isinstance(response, RedirectResponse):return response+ if isinstance(response, JSONResponse):+ return responseif dataclasses.is_dataclass(response):return JSONResponse(diff --git a/marimo/_tutorials/__init__.py b/marimo/_tutorials/__init__.pyindex 00b34b425f..d671853025 100644--- a/marimo/_tutorials/__init__.py+++ b/marimo/_tutorials/__init__.py@@ -3,8 +3,11 @@ from __future__ import annotationsimport inspectimport os+import tempfilefrom typing import get_args, Literal, Union+from marimo._utils.marimo_path import MarimoPath+PythonTutorial = Literal["intro",@@ -47,3 +50,11 @@ def get_tutorial_source(name: Tutorial) -> str:file = os.path.join(os.path.dirname(__file__), f"{name}.md")with open(file, "r", encoding="utf8") as f:return f.read()++def create_temp_tutorial_file(name: Tutorial, temp_dir: tempfile.TemporaryDirectory[str]) -> MarimoPath:+ source = get_tutorial_source(name)+ extension = "py" if name in get_args(PythonTutorial) else "md"+ fname = os.path.join(temp_dir.name, f"{name}.{extension}")+ path = MarimoPath(fname)+ path.write_text(source)+ return pathdiff --git a/openapi/api.yaml b/openapi/api.yamlindex a41107258f..1e5a19d544 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -1321,6 +1321,27 @@ components:required:- pathtype: object+ OpenTutorialRequest:+ properties:+ tutorialId:+ oneOf:+ - enum:+ - intro+ - dataflow+ - ui+ - markdown+ - plots+ - sql+ - layout+ - fileformat+ - for-jupyter-users+ type: string+ - enum:+ - markdown-format+ type: string+ required:+ - tutorialId+ type: objectPreviewDatasetColumnRequest:properties:columnName:@@ -1795,7 +1816,7 @@ components:type: objectinfo:title: marimo API- version: 0.8.3+ version: 0.8.4openapi: 3.1.0paths:/@file/{filename_and_length}:@@ -2020,6 +2041,20 @@ paths:schema:$ref: '#/components/schemas/RunningNotebooksResponse'description: Shutdown the current session+ /api/home/tutorial/open:+ post:+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/OpenTutorialRequest'+ responses:+ 200:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/MarimoFile'+ description: Open a new tutorial/api/home/workspace_files:post:requestBody:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 8c2bb3b42d..95c27d8994 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -646,6 +646,45 @@ export interface paths {patch?: never;trace?: never;};+ "/api/home/tutorial/open": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ post: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: {+ content: {+ "application/json": components["schemas"]["OpenTutorialRequest"];+ };+ };+ responses: {+ /** @description Open a new tutorial */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["MarimoFile"];+ };+ };+ };+ };+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/home/workspace_files": {parameters: {query?: never;@@ -2231,6 +2270,21 @@ export interface components {OpenFileRequest: {path: string;};+ OpenTutorialRequest: {+ tutorialId:+ | (+ | "intro"+ | "dataflow"+ | "ui"+ | "markdown"+ | "plots"+ | "sql"+ | "layout"+ | "fileformat"+ | "for-jupyter-users"+ )+ | "markdown-format";+ };PreviewDatasetColumnRequest: {columnName: string;source: string;diff --git a/tests/_server/api/endpoints/test_home.py b/tests/_server/api/endpoints/test_home.pyindex e6ed63fed1..eed083b147 100644--- a/tests/_server/api/endpoints/test_home.py+++ b/tests/_server/api/endpoints/test_home.py@@ -77,3 +77,27 @@ def test_shutdown_session(client: TestClient) -> None:assert response.status_code == 200assert response.json() == {"files": []}assert get_session_manager(client).get_session(SESSION_ID) is None+++@with_session(SESSION_ID)+def test_open_tutorial(client: TestClient) -> None:+ response = client.post(+ "/api/home/tutorial/open",+ headers=HEADERS,+ json={"tutorial_id": "intro"},+ )+ assert response.status_code == 200+ data = response.json()+ assert data["name"] == "intro.py"+ assert data["path"].endswith("intro.py")+++@with_session(SESSION_ID)+def test_cant_open_non_tutorial(client: TestClient) -> None:+ response = client.post(+ "/api/home/tutorial/open",+ headers=HEADERS,+ json={"tutorial_id": "non-tutorial"},+ )+ assert response.status_code == 400+ assert response.json() == {"detail": "Tutorial not found"}