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
improvment: consistent error toasting on all request (#969)
Myles Scolnick5259a07ac8d2
diff --git a/frontend/src/components/app-config/app-config-form.tsx b/frontend/src/components/app-config/app-config-form.tsxindex 0a40535c93..0799bd112d 100644--- a/frontend/src/components/app-config/app-config-form.tsx+++ b/frontend/src/components/app-config/app-config-form.tsx@@ -15,7 +15,6 @@ import {APP_WIDTHS,} from "../../core/config/config-schema";import { NativeSelect } from "../ui/native-select";-import { toast } from "../ui/use-toast";import { useAppConfig } from "@/core/config/config";import { saveAppConfig } from "@/core/network/requests";import { SettingTitle, SettingDescription } from "./common";@@ -37,7 +36,6 @@ export const AppConfigForm: React.FC = () => {}).catch(() => {setConfig(values);- toast({ title: "Failed to save" });});};diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 467fe3737e..d89fedb553 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -13,7 +13,6 @@ import {import { UserConfig, UserConfigSchema } from "../../core/config/config-schema";import { Checkbox } from "../ui/checkbox";import { Input } from "../ui/input";-import { toast } from "../ui/use-toast";import { saveUserConfig } from "../../core/network/requests";import { useUserConfig } from "../../core/config/config";import { NativeSelect } from "../ui/native-select";@@ -34,13 +33,9 @@ export const UserConfigForm: React.FC = () => {});const onSubmit = async (values: UserConfig) => {- await saveUserConfig({ config: values })- .then(() => {- setConfig(values);- })- .catch(() => {- toast({ title: "Failed to save" });- });+ await saveUserConfig({ config: values }).then(() => {+ setConfig(values);+ });};const isWasm = isPyodide();diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsxindex f1e5349be7..4f4dae189e 100644--- a/frontend/src/components/editor/file-tree/file-explorer.tsx+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx@@ -41,6 +41,7 @@ import { cn } from "@/utils/cn";import { FileViewer } from "./file-viewer";import { treeAtom, openStateAtom } from "./state";import { useFileExplorerUpload } from "./upload";+import { isPyodide } from "@/core/pyodide/utils";export const FileExplorer: React.FC<{height: number;@@ -281,7 +282,8 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {onClick={(e) => e.stopPropagation()}onCloseAutoFocus={(e) => e.preventDefault()}>- {!node.data.isDirectory && (+ {/* Not shown in Pyodide */}+ {!node.data.isDirectory && !isPyodide() && (<DropdownMenuItem onSelect={() => node.select()}><ViewIcon className="mr-2" size={14} strokeWidth={1.5} />Open filediff --git a/frontend/src/components/editor/file-tree/upload.tsx b/frontend/src/components/editor/file-tree/upload.tsxindex ba3c69ac8e..305a5eb930 100644--- a/frontend/src/components/editor/file-tree/upload.tsx+++ b/frontend/src/components/editor/file-tree/upload.tsx@@ -49,13 +49,6 @@ export function useFileExplorerUpload(options: DropzoneOptions = {}) {type: "file",name: file.name,contents: base64,- }).catch((error) => {- console.error(error);- toast({- title: "File upload failed",- description: error.message,- variant: "danger",- });});}await refreshRoot();diff --git a/frontend/src/core/App.tsx b/frontend/src/core/App.tsxindex 81c3e774dc..33a181d592 100644--- a/frontend/src/core/App.tsx+++ b/frontend/src/core/App.tsx@@ -154,24 +154,20 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {filename,configs,layout: getSerializedLayout(),- })- .then(() => {- if (userInitiated) {- toast({ title: "Notebook saved" });- if (userConfig.save.format_on_save) {- formatAll(updateCellCode);- }+ }).then(() => {+ if (userInitiated) {+ toast({ title: "Notebook saved" });+ if (userConfig.save.format_on_save) {+ formatAll(updateCellCode);}- setLastSavedNotebook({- names: cellNames,- codes,- configs,- layout: layoutData,- });- })- .catch((error) => {- openAlert(error.message);+ }+ setLastSavedNotebook({+ names: cellNames,+ codes,+ configs,+ layout: layoutData,});+ });});// Save the notebook with the current filename, only if the filename existsdiff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.tsindex 1354c4237d..89296471de 100644--- a/frontend/src/core/network/api.ts+++ b/frontend/src/core/network/api.ts@@ -4,11 +4,6 @@ import { Logger } from "../../utils/Logger";import { getMarimoServerToken } from "../dom/marimo-tag";import { getSessionId } from "../kernel/session";-export function getXsrfCookie(): string {- const r = document.cookie.match("\\b_xsrf=([^;]*)\\b");- return r ? r[1] : "";-}-const getServerTokenOnce = once(() => {return getMarimoServerToken();});@@ -49,7 +44,6 @@ export const API = {},headers() {return {- "X-Xsrftoken": getXsrfCookie(),"Marimo-Session-Id": getSessionId(),"Marimo-Server-Token": getServerTokenOnce(),};diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.tsnew file mode 100644index 0000000000..c3848cd460--- /dev/null+++ b/frontend/src/core/network/requests-network.ts@@ -0,0 +1,183 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { CellId } from "../cells/ids";+import { API } from "./api";+import { sendRestart } from "./requests";+import {+ CodeCompletionRequest,+ DeleteRequest,+ FormatResponse,+ FormatRequest,+ InstantiateRequest,+ RenameRequest,+ RunRequest,+ SaveKernelRequest,+ SetComponentValuesRequest,+ SaveUserConfigRequest,+ SaveAppConfigRequest,+ SaveCellConfigRequest,+ SendFunctionRequest,+ RunRequests,+ EditRequests,+ SendStdin,+ SendInstallMissingPackages,+ FileListResponse,+ FileCreateRequest,+ FileOperationResponse,+ FileDeleteRequest,+ FileUpdateRequest,+ FileDetailsResponse,+} from "./types";+import { invariant } from "@/utils/invariant";++export function createNetworkRequests(): EditRequests & RunRequests {+ return {+ sendComponentValues: (valueUpdates) => {+ const objectIds: string[] = [];+ const values: unknown[] = [];+ for (const update of valueUpdates) {+ objectIds.push(update.objectId);+ values.push(update.value);+ }++ return API.post<SetComponentValuesRequest>(+ "/kernel/set_ui_element_value",+ {+ objectIds: objectIds,+ values: values,+ },+ );+ },+ sendRestart: () => {+ return API.post("/kernel/restart_session", {});+ },+ sendRename: (filename: string | null) => {+ return API.post<RenameRequest>("/kernel/rename", {+ filename: filename,+ });+ },+ sendSave: (request: SaveKernelRequest) => {+ // Validate same length+ invariant(+ request.cellIds.length === request.codes.length,+ "cell ids and codes must be the same length",+ );+ invariant(+ request.codes.length === request.names.length,+ "cell ids and names must be the same length",+ );+ invariant(+ request.codes.length === request.configs.length,+ "cell ids and configs must be the same length",+ );++ return API.post<SaveKernelRequest>("/kernel/save", request);+ },+ sendFormat: (request: FormatRequest) => {+ return API.post<FormatRequest, FormatResponse>(+ "/kernel/format",+ request,+ ).then((res) => res.codes);+ },+ sendInterrupt: () => {+ return API.post("/kernel/interrupt", {});+ },+ sendShutdown: () => {+ return API.post("/kernel/shutdown", {});+ },+ sendRun: (cellIds: CellId[], codes: string[]) => {+ // Validate same length+ invariant(cellIds.length === codes.length, "must be the same length");++ return API.post<RunRequest>("/kernel/run", {+ cellIds: cellIds,+ codes: codes,+ });+ },+ sendInstantiate: (request: InstantiateRequest) => {+ // Validate same length+ invariant(+ request.objectIds.length === request.values.length,+ "must be the same length",+ );++ return API.post<InstantiateRequest>("/kernel/instantiate", request);+ },+ sendDeleteCell: (cellId) => {+ return API.post<DeleteRequest>("/kernel/delete", {+ cellId: cellId,+ });+ },+ sendCodeCompletionRequest: (request) => {+ return API.post<CodeCompletionRequest>(+ "/kernel/code_autocomplete",+ request,+ );+ },+ saveUserConfig: (request) => {+ return API.post<SaveUserConfigRequest>(+ "/kernel/save_user_config",+ request,+ );+ },+ saveAppConfig: (request) => {+ return API.post<SaveAppConfigRequest>("/kernel/save_app_config", request);+ },+ saveCellConfig: (request) => {+ return API.post<SaveCellConfigRequest>(+ "/kernel/set_cell_config",+ request,+ );+ },+ sendFunctionRequest: (request) => {+ return API.post<SendFunctionRequest>("/kernel/function_call", request);+ },+ sendStdin: (request) => {+ return API.post<SendStdin>("/kernel/stdin", request);+ },+ sendInstallMissingPackages: (request) => {+ return API.post<SendInstallMissingPackages>(+ "/kernel/install_missing_packages",+ request,+ );+ },+ readCode: () => {+ return API.post<{}, { contents: string }>("/kernel/read_code", {});+ },+ openFile: async (request) => {+ await API.post<{ path: string }>("/kernel/open", request);+ await sendRestart();+ window.location.reload();+ return null;+ },+ sendListFiles: (request) => {+ return API.post<{ path: string | undefined }, FileListResponse>(+ "/files/list_files",+ request,+ );+ },+ sendCreateFileOrFolder: (request) => {+ return API.post<FileCreateRequest, FileOperationResponse>(+ "/files/create",+ request,+ );+ },+ sendDeleteFileOrFolder: (request) => {+ return API.post<FileDeleteRequest, FileOperationResponse>(+ "/files/delete",+ request,+ );+ },+ sendRenameFileOrFolder: (request) => {+ return API.post<FileUpdateRequest, FileOperationResponse>(+ "/files/update",+ request,+ );+ },+ sendFileDetails: (request: { path: string }) => {+ return API.post<{ path: string }, FileDetailsResponse>(+ "/files/file_details",+ request,+ );+ },+ };+}diff --git a/frontend/src/core/network/static-requests.ts b/frontend/src/core/network/requests-static.tssimilarity index 100%rename from frontend/src/core/network/static-requests.tsrename to frontend/src/core/network/requests-static.tsdiff --git a/frontend/src/core/network/requests-toasting.ts b/frontend/src/core/network/requests-toasting.tsnew file mode 100644index 0000000000..3e8cbf6cef--- /dev/null+++ b/frontend/src/core/network/requests-toasting.ts@@ -0,0 +1,59 @@+/* Copyright 2024 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/no-explicit-any */+import { toast } from "@/components/ui/use-toast";+import { EditRequests, RequestKey, RunRequests } from "./types";+import { Logger } from "@/utils/Logger";+import { prettyError } from "@/utils/errors";++export function createErrorToastingRequests(+ delegate: EditRequests & RunRequests,+): EditRequests & RunRequests {+ const MESSAGES: Record<RequestKey, string> = {+ sendComponentValues: "Failed update value",+ sendInstantiate: "Failed to instantiate",+ sendFunctionRequest: "Failed to send function request",+ sendRestart: "Failed to restart",+ sendRun: "Failed to run",+ sendRename: "Failed to rename",+ sendSave: "Failed to save",+ sendInterrupt: "Failed to interrupt",+ sendShutdown: "Failed to shutdown",+ sendFormat: "Failed to format",+ sendDeleteCell: "Failed to delete cell",+ sendCodeCompletionRequest: "Failed to complete code",+ saveUserConfig: "Failed to save user config",+ saveAppConfig: "Failed to save app config",+ saveCellConfig: "Failed to save cell config",+ sendStdin: "Failed to send stdin",+ readCode: "Failed to read code",+ openFile: "Failed to open file",+ sendListFiles: "Failed to list files",+ sendCreateFileOrFolder: "Failed to create file or folder",+ sendDeleteFileOrFolder: "Failed to delete file or folder",+ sendRenameFileOrFolder: "Failed to rename file or folder",+ sendFileDetails: "Failed to get file details",+ sendInstallMissingPackages: "Failed to install missing packages",+ };++ const handlers = {} as EditRequests & RunRequests;+ for (const [key, handler] of Object.entries(delegate)) {+ const keyString = key as RequestKey;+ handlers[keyString] = async (...args: any[]) => {+ try {+ return await handler(...args);+ } catch (error) {+ const message = prettyError(error);+ toast({+ title: MESSAGES[keyString],+ description: message,+ variant: "danger",+ });+ Logger.error(`Failed to handle request: ${key}`, error);+ // Rethrow the error so that the caller can handle it+ throw error;+ }+ };+ }++ return handlers;+}diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex cae8f7ddec..9f9d97a046 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -1,188 +1,19 @@/* Copyright 2024 Marimo. All rights reserved. */-import { CellId } from "../cells/ids";import { PyodideBridge } from "../pyodide/bridge";import { isPyodide } from "../pyodide/utils";import { isStaticNotebook } from "../static/static-state";-import { API } from "./api";-import { createStaticRequests } from "./static-requests";-import {- CodeCompletionRequest,- DeleteRequest,- FormatResponse,- FormatRequest,- InstantiateRequest,- RenameRequest,- RunRequest,- SaveKernelRequest,- SetComponentValuesRequest,- SaveUserConfigRequest,- SaveAppConfigRequest,- SaveCellConfigRequest,- SendFunctionRequest,- RunRequests,- EditRequests,- SendStdin,- SendInstallMissingPackages,- FileListResponse,- FileCreateRequest,- FileOperationResponse,- FileDeleteRequest,- FileUpdateRequest,- FileDetailsResponse,-} from "./types";-import { invariant } from "@/utils/invariant";+import { createNetworkRequests } from "./requests-network";+import { createStaticRequests } from "./requests-static";+import { createErrorToastingRequests } from "./requests-toasting";-function createNetworkRequests(): EditRequests & RunRequests {- return {- sendComponentValues: (valueUpdates) => {- const objectIds: string[] = [];- const values: unknown[] = [];- for (const update of valueUpdates) {- objectIds.push(update.objectId);- values.push(update.value);- }+function getRequest() {+ const base = isPyodide()+ ? PyodideBridge.INSTANCE+ : isStaticNotebook()+ ? createStaticRequests()+ : createNetworkRequests();- return API.post<SetComponentValuesRequest>(- "/kernel/set_ui_element_value",- {- objectIds: objectIds,- values: values,- },- );- },- sendRestart: () => {- return API.post("/kernel/restart_session", {});- },- sendRename: (filename: string | null) => {- return API.post<RenameRequest>("/kernel/rename", {- filename: filename,- });- },- sendSave: (request: SaveKernelRequest) => {- // Validate same length- invariant(- request.cellIds.length === request.codes.length,- "cell ids and codes must be the same length",- );- invariant(- request.codes.length === request.names.length,- "cell ids and names must be the same length",- );- invariant(- request.codes.length === request.configs.length,- "cell ids and configs must be the same length",- );-- return API.post<SaveKernelRequest>("/kernel/save", request);- },- sendFormat: (request: FormatRequest) => {- return API.post<FormatRequest, FormatResponse>(- "/kernel/format",- request,- ).then((res) => res.codes);- },- sendInterrupt: () => {- return API.post("/kernel/interrupt", {});- },- sendShutdown: () => {- return API.post("/kernel/shutdown", {});- },- sendRun: (cellIds: CellId[], codes: string[]) => {- // Validate same length- invariant(cellIds.length === codes.length, "must be the same length");-- return API.post<RunRequest>("/kernel/run", {- cellIds: cellIds,- codes: codes,- });- },- sendInstantiate: (request: InstantiateRequest) => {- // Validate same length- invariant(- request.objectIds.length === request.values.length,- "must be the same length",- );-- return API.post<InstantiateRequest>("/kernel/instantiate", request);- },- sendDeleteCell: (cellId) => {- return API.post<DeleteRequest>("/kernel/delete", {- cellId: cellId,- });- },- sendCodeCompletionRequest: (request) => {- return API.post<CodeCompletionRequest>(- "/kernel/code_autocomplete",- request,- );- },- saveUserConfig: (request) => {- return API.post<SaveUserConfigRequest>(- "/kernel/save_user_config",- request,- );- },- saveAppConfig: (request) => {- return API.post<SaveAppConfigRequest>("/kernel/save_app_config", request);- },- saveCellConfig: (request) => {- return API.post<SaveCellConfigRequest>(- "/kernel/set_cell_config",- request,- );- },- sendFunctionRequest: (request) => {- return API.post<SendFunctionRequest>("/kernel/function_call", request);- },- sendStdin: (request) => {- return API.post<SendStdin>("/kernel/stdin", request);- },- sendInstallMissingPackages: (request) => {- return API.post<SendInstallMissingPackages>(- "/kernel/install_missing_packages",- request,- );- },- readCode: () => {- return API.post<{}, { contents: string }>("/kernel/read_code", {});- },- openFile: async (request) => {- await API.post<{ path: string }>("/kernel/open", request);- await sendRestart();- window.location.reload();- return null;- },- sendListFiles: (request) => {- return API.post<{ path: string | undefined }, FileListResponse>(- "/files/list_files",- request,- );- },- sendCreateFileOrFolder: (request) => {- return API.post<FileCreateRequest, FileOperationResponse>(- "/files/create",- request,- );- },- sendDeleteFileOrFolder: (request) => {- return API.post<FileDeleteRequest, FileOperationResponse>(- "/files/delete",- request,- );- },- sendRenameFileOrFolder: (request) => {- return API.post<FileUpdateRequest, FileOperationResponse>(- "/files/update",- request,- );- },- sendFileDetails: (request: { path: string }) => {- return API.post<{ path: string }, FileDetailsResponse>(- "/files/file_details",- request,- );- },- };+ return createErrorToastingRequests(base);}export const {@@ -210,8 +41,4 @@ export const {sendDeleteFileOrFolder,sendRenameFileOrFolder,sendFileDetails,-} = isPyodide()- ? PyodideBridge.INSTANCE- : isStaticNotebook()- ? createStaticRequests()- : createNetworkRequests();+} = getRequest();diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 03599c6df4..f03b4d1eb8 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -195,3 +195,5 @@ export interface EditRequests {) => Promise<FileOperationResponse>;sendFileDetails: (request: { path: string }) => Promise<FileDetailsResponse>;}++export type RequestKey = keyof (EditRequests & RunRequests);diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.tsindex 6d490e12af..16d0f900dd 100644--- a/frontend/src/core/pyodide/bridge.ts+++ b/frontend/src/core/pyodide/bridge.ts@@ -28,7 +28,6 @@ import {import { IReconnectingWebSocket } from "../websocket/types";import { fallbackFileStore, notebookFileStore } from "./store";import { isPyodide } from "./utils";-import { RawBridge } from "./worker/types";import { Deferred } from "@/utils/Deferred";import { UserConfigLocalStorage } from "../config/config-schema";import { createShareableLink } from "./share";@@ -37,13 +36,6 @@ import { Paths } from "@/utils/paths";import { getMarimoVersion } from "../dom/marimo-tag";import { getWorkerRPC } from "./rpc";-export type BridgeFunctionAndPayload = {- [P in keyof RawBridge]: {- functionName: P;- payload: Parameters<RawBridge[P]>[0];- };-}[keyof RawBridge];-export class PyodideBridge implements RunRequests, EditRequests {static INSTANCE = new PyodideBridge();diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.tsindex 4bf2f22200..167634f658 100644--- a/frontend/src/core/static/download-html.ts+++ b/frontend/src/core/static/download-html.ts@@ -7,7 +7,6 @@ import { StaticVirtualFiles } from "./types";import { serializeJsonToBase64 } from "@/utils/json/base64";import { readCode } from "../network/requests";import { downloadBlob } from "@/utils/download";-import { toast } from "@/components/ui/use-toast";import { Paths } from "@/utils/paths";// For Testing:@@ -29,14 +28,7 @@ export async function createStaticHTMLNotebook() {? window.location.origin: `https://cdn.jsdelivr.net/npm/@marimo-team/frontend@${version}/dist`;- const codeResponse = await readCode().catch((error) => {- toast({- variant: "danger",- title: "Error",- description: error.message,- });- throw error;- });+ const codeResponse = await readCode();const html = constructHTML({notebookState: notebook,diff --git a/frontend/src/custom.d.ts b/frontend/src/custom.d.tsindex e14f112343..ebf84d8aab 100644--- a/frontend/src/custom.d.ts+++ b/frontend/src/custom.d.ts@@ -7,7 +7,7 @@ declare module "*.svg" {// Stricter lib typesinterface Body {- json(): Promise<unknown>;+ json<T = unknown>(): Promise<T>;}// Stricter lib types