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: move auto-download to app config (#2309)
Myles Scolnick02782cab2bbd
diff --git a/frontend/src/components/app-config/app-config-form.tsx b/frontend/src/components/app-config/app-config-form.tsxindex 4b815c16d9..40c843832c 100644--- a/frontend/src/components/app-config/app-config-form.tsx+++ b/frontend/src/components/app-config/app-config-form.tsx@@ -22,6 +22,9 @@ import { useAppConfig } from "@/core/config/config";import { saveAppConfig } from "@/core/network/requests";import { SettingTitle, SettingDescription } from "./common";import { useEffect } from "react";+import { Checkbox } from "../ui/checkbox";+import { arrayToggle } from "@/utils/arrays";+import { Kbd } from "../ui/kbd";export const AppConfigForm: React.FC = () => {const [config, setConfig] = useAppConfig();@@ -143,6 +146,54 @@ export const AppConfigForm: React.FC = () => {</div>)}/>+ <FormField+ control={form.control}+ name="auto_download"+ render={({ field }) => (+ <div className="flex flex-col gap-y-1">+ <FormItem className="flex flex-col gap-2">+ <FormControl>+ <div className="flex gap-2">+ <div className="flex items-center space-x-2">+ <Checkbox+ id="html-checkbox"+ checked={field.value.includes("html")}+ onCheckedChange={() => {+ field.onChange(arrayToggle(field.value, "html"));+ }}+ />+ <FormLabel htmlFor="html-checkbox">+ Auto-download HTML+ </FormLabel>+ </div>+ {/* Disable markdown until we save outputs in the exported markdown */}+ {/* <div className="flex items-center space-x-2">+ <Checkbox+ id="markdown-checkbox"+ checked={field.value.includes("markdown")}+ onCheckedChange={() => {+ field.onChange(arrayToggle(field.value, "markdown"));+ }}+ />+ <label+ htmlFor="markdown-checkbox"+ className="cursor-pointer"+ >+ Markdown+ </label>+ </div> */}+ </div>+ </FormControl>+ <FormMessage />+ </FormItem>+ <FormDescription>+ When enabled, marimo will periodically save this notebook as+ HTML to a folder <Kbd className="inline">.marimo</Kbd> in the+ notebook's directory.+ </FormDescription>+ </div>+ )}+ /></form></Form>);diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex d712429766..229ec7842e 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -30,7 +30,6 @@ import {EditIcon,LayoutTemplateIcon,Files,- FolderSyncIcon,} from "lucide-react";import { commandPaletteAtom } from "../controls/command-palette";import { useCellActions, useNotebook } from "@/core/cells/cells";@@ -65,11 +64,6 @@ import { useLayoutState, useLayoutActions } from "@/core/layout/layout";import { useTogglePresenting } from "@/core/layout/useTogglePresenting";import { useCopyNotebook } from "./useCopyNotebook";import { isWasm } from "@/core/wasm/utils";-import {- autoExportHTMLAtom,- autoExportMarkdownAtom,-} from "@/core/export/state";-import { Kbd } from "@/components/ui/kbd";const NOOP_HANDLER = (event?: Event) => {event?.preventDefault();@@ -96,10 +90,6 @@ export function useNotebookActions() {const { selectedLayout } = useLayoutState();const { setLayoutView } = useLayoutActions();const togglePresenting = useTogglePresenting();- const [autoExportHTML, setAutoExportHTML] = useAtom(autoExportHTMLAtom);- const [autoExportMarkdown, setAutoExportMarkdown] = useAtom(- autoExportMarkdownAtom,- );const renderCheckboxElement = (checked: boolean) => (<div className="w-8 flex justify-end">@@ -231,65 +221,6 @@ export function useNotebookActions() {],},- {- icon: <FolderSyncIcon size={14} strokeWidth={1.5} />,- label: "Auto-download",- hidden: isWasm(),- handle: NOOP_HANDLER,- dropdown: [- {- label: "",- labelElement: (- <span className="text-muted-foreground text-sm block w-[18rem]">- When enabled, the notebook will automatically download the HTML or- Markdown snapshot to a folder{" "}- <Kbd className="inline">.marimo</Kbd> in the notebook's directory.- </span>- ),- variant: "disabled",- handle: NOOP_HANDLER,- disableClick: true,- },- {- divider: true,- icon: <FolderDownIcon size={14} strokeWidth={1.5} />,- label: "Auto-download HTML on changes",- rightElement: renderCheckboxElement(autoExportHTML),- handle: async () => {- if (!filename) {- toast({- variant: "danger",- title: "Error",- description: "Notebooks must be named to be exported.",- });- return;- }-- setAutoExportHTML((val) => !val);- },- },- {- icon: (- <MarkdownIcon strokeWidth={1.5} style={{ width: 14, height: 14 }} />- ),- label: "Auto-download Markdown on changes",- rightElement: renderCheckboxElement(autoExportMarkdown),- handle: async () => {- if (!filename) {- toast({- variant: "danger",- title: "Error",- description: "Notebooks must be named to be exported.",- });- return;- }-- setAutoExportMarkdown((val) => !val);- },- },- ],- },-{divider: true,icon: <PanelLeftIcon size={14} strokeWidth={1.5} />,diff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.tsindex c6e47072fd..6bff4bcebf 100644--- a/frontend/src/core/config/__tests__/config-schema.test.ts+++ b/frontend/src/core/config/__tests__/config-schema.test.ts@@ -5,9 +5,10 @@ import { AppConfigSchema, UserConfigSchema } from "../config-schema";test("default AppConfig", () => {const defaultConfig = AppConfigSchema.parse({});expect(defaultConfig).toMatchInlineSnapshot(`- {- "width": "medium",- }+ {+ "auto_download": [],+ "width": "medium",+ }`);});@@ -19,6 +20,7 @@ test("another AppConfig", () => {expect(config).toMatchInlineSnapshot(`{"app_title": null,+ "auto_download": [],"width": "medium",}`);diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 6066bbfe86..b41f0f1f13 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -151,8 +151,9 @@ export const AppConfigSchema = z}),app_title: AppTitleSchema.nullish(),css_file: z.string().nullish(),+ auto_download: z.array(z.string()).default([]),})- .default({ width: "medium" });+ .default({ width: "medium", auto_download: [] });export type AppConfig = z.infer<typeof AppConfigSchema>;export function parseAppConfig() {diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.tsindex eb9277fef1..a89d1f8692 100644--- a/frontend/src/core/config/config.ts+++ b/frontend/src/core/config/config.ts@@ -51,7 +51,7 @@ export function isAiEnabled(config: UserConfig) {/*** Atom for storing the app config.*/-const appConfigAtom = atom<AppConfig>(parseAppConfig());+export const appConfigAtom = atom<AppConfig>(parseAppConfig());/*** Returns the app config.diff --git a/frontend/src/core/export/hooks.ts b/frontend/src/core/export/hooks.tsindex a51a671599..f9a9e53972 100644--- a/frontend/src/core/export/hooks.ts+++ b/frontend/src/core/export/hooks.ts@@ -1,19 +1,21 @@/* Copyright 2024 Marimo. All rights reserved. */import { useAtomValue } from "jotai";-import { autoExportHTMLAtom, autoExportMarkdownAtom } from "./state";import { useInterval } from "@/hooks/useInterval";import { autoExportAsHTML, autoExportAsMarkdown } from "../network/requests";import { VirtualFileTracker } from "../static/virtual-file-tracker";import { connectionAtom } from "../network/connection";import { WebSocketState } from "../websocket/types";+import { appConfigAtom } from "@/core/config/config";const DELAY = 5000; // 5 seconds;export function useAutoExport() {- const markdownEnabled = useAtomValue(autoExportMarkdownAtom);- const htmlEnabled = useAtomValue(autoExportHTMLAtom);+ const appConfig = useAtomValue(appConfigAtom);const { state } = useAtomValue(connectionAtom);+ const markdownEnabled = appConfig.auto_download.includes("markdown");+ const htmlEnabled = appConfig.auto_download.includes("html");+const markdownDisabled = !markdownEnabled || state !== WebSocketState.OPEN;const htmlDisabled = !htmlEnabled || state !== WebSocketState.OPEN;diff --git a/frontend/src/core/export/state.ts b/frontend/src/core/export/state.tsdeleted file mode 100644index 7516cac6a7..0000000000--- a/frontend/src/core/export/state.ts+++ /dev/null@@ -1,6 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */--import { atom } from "jotai";--export const autoExportMarkdownAtom = atom(false);-export const autoExportHTMLAtom = atom(false);diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.tsindex 3f4e848cf0..67f6c3d2b7 100644--- a/frontend/src/core/kernel/handlers.ts+++ b/frontend/src/core/kernel/handlers.ts@@ -14,7 +14,7 @@ import type {OperationMessageData,} from "./messages";import type { LayoutType } from "@/components/editor/renderers/types";-import type { AppConfig } from "../config/config-schema";+import { AppConfigSchema, type AppConfig } from "../config/config-schema";import { type CellData, createCell } from "../cells/types";import { VirtualFileTracker } from "../static/virtual-file-tracker";import type { CellId, UIElementId } from "../cells/ids";@@ -95,9 +95,10 @@ export function handleKernelReady(setLayoutData({ layoutView: layoutType, data: layoutData });}setCells(cells, layoutState);- setAppConfig({- ...app_config,- } as AppConfig);+ const parsedAppConfig = AppConfigSchema.safeParse(app_config);+ if (parsedAppConfig.success) {+ setAppConfig(parsedAppConfig.data);+ }setCapabilities({...capabilities,// always enable sql if wasmdiff --git a/frontend/src/utils/arrays.ts b/frontend/src/utils/arrays.tsindex 2464506edb..a13042056e 100644--- a/frontend/src/utils/arrays.ts+++ b/frontend/src/utils/arrays.ts@@ -44,3 +44,10 @@ export const Arrays = {return result;},};++export function arrayToggle<T>(arr: T[], item: T): T[] {+ if (!arr) {+ return [item];+ }+ return arr.includes(item) ? arr.filter((i) => i !== item) : [...arr, item];+}diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex d49a6d5498..88986625b3 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -3,13 +3,15 @@ from __future__ import annotationsimport randomimport string-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, fieldfrom typing import (TYPE_CHECKING,Any,Callable,Iterable,Iterator,+ List,+ Literal,Mapping,Optional,)@@ -68,6 +70,11 @@ class _AppConfig:# CSS file, relative to the app filecss_file: Optional[str] = None+ # Whether to automatically download the app as HTML and Markdown+ auto_download: List[Literal["html", "markdown"]] = field(+ default_factory=list+ )+@staticmethoddef from_untrusted_dict(updates: dict[str, Any]) -> _AppConfig:config = _AppConfig()diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex ea92d0a91a..e1076687b3 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -125,6 +125,8 @@ def generate_app_constructor(config: Optional[_AppConfig]) -> str:def _format_arg(arg: Any) -> str:if isinstance(arg, str):return f'"{arg}"'.replace("\\", "\\\\")+ elif isinstance(arg, list):+ return "[" + ", ".join([_format_arg(item) for item in arg]) + "]"else:return str(arg)diff --git a/marimo/_cli/convert/markdown.py b/marimo/_cli/convert/markdown.pyindex c1c1173c95..194920ba72 100644--- a/marimo/_cli/convert/markdown.py+++ b/marimo/_cli/convert/markdown.py@@ -60,8 +60,6 @@ def app_config_from_root(root: Element) -> _AppConfig:# Extract meta data from root attributes.config_keys = {"title": "app_title",- "marimo-layout": "layout_file",- "marimo-css": "css_file",}config = {config_keys[key]: value@@ -72,6 +70,7 @@ def app_config_from_root(root: Element) -> _AppConfig:config.update({k: v for k, v in root.items() if k not in config_keys})# Remove values particular to markdown saves.config.pop("marimo-version", None)+return _AppConfig.from_untrusted_dict(config)diff --git a/marimo/_runtime/functions.py b/marimo/_runtime/functions.pyindex bdae3fbf23..e98507e731 100644--- a/marimo/_runtime/functions.py+++ b/marimo/_runtime/functions.py@@ -7,7 +7,7 @@ import dataclassesfrom typing import Any, Callable, Coroutine, Generic, Type, TypeVarfrom marimo._ast.cell import CellId_t-from marimo._utils.parse_dataclass import build_dataclass+from marimo._utils.parse_dataclass import parse_rawS = TypeVar("S")T = TypeVar("T")@@ -53,7 +53,7 @@ class Function(Generic[S, T]):self.cell_id = Nonedef __call__(self, args: dict[Any, Any]) -> T | Coroutine[Any, Any, T]:- return self.function(build_dataclass(args, self.arg_cls))+ return self.function(parse_raw(args, self.arg_cls))@dataclasses.dataclassdiff --git a/marimo/_server/api/endpoints/config.py b/marimo/_server/api/endpoints/config.pyindex bb1446e476..bf6f5b02cc 100644--- a/marimo/_server/api/endpoints/config.py+++ b/marimo/_server/api/endpoints/config.py@@ -46,7 +46,10 @@ async def save_user_config($ref: "#/components/schemas/SuccessResponse"""" # noqa: E501app_state = AppState(request)- body = await parse_request(request, cls=SaveUserConfigurationRequest)+ # Allow unknown keys to handle backward/forward compatibility+ body = await parse_request(+ request, cls=SaveUserConfigurationRequest, allow_unknown_keys=True+ )config = app_state.config_manager.save_config(body.config)# Update the server's view of the configdiff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.pyindex 04215da7ce..6497d81ca6 100644--- a/marimo/_server/api/endpoints/export.py+++ b/marimo/_server/api/endpoints/export.py@@ -5,7 +5,7 @@ from typing import TYPE_CHECKINGfrom starlette.authentication import requiresfrom starlette.exceptions import HTTPException-from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse+from starlette.responses import HTMLResponse, PlainTextResponsefrom marimo import _loggersfrom marimo._server.api.deps import AppState@@ -86,7 +86,7 @@ async def export_as_html(async def auto_export_as_html(*,request: Request,-) -> SuccessResponse | JSONResponse:+) -> SuccessResponse | PlainTextResponse:"""requestBody:content:@@ -111,10 +111,7 @@ async def auto_export_as_html(# If we have already exported to HTML, don't do it againif session_view.has_auto_exported_html:LOGGER.debug("Already auto-exported to HTML")- return JSONResponse(- status_code=HTTPStatus.NOT_MODIFIED,- content={},- )+ return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)# Reload the file manager to get the latest statesession.app_file_manager.reload()@@ -235,7 +232,7 @@ async def export_as_markdown(async def auto_export_as_markdown(*,request: Request,-) -> SuccessResponse | JSONResponse:+) -> SuccessResponse | PlainTextResponse:"""requestBody:content:@@ -259,10 +256,7 @@ async def auto_export_as_markdown(# If we have already exported to Markdown, don't do it againif session_view.has_auto_exported_md:LOGGER.debug("Already auto-exported to Markdown")- return JSONResponse(- status_code=HTTPStatus.NOT_MODIFIED,- content={},- )+ return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)# Reload the file manager to get the latest statesession.app_file_manager.reload()diff --git a/marimo/_server/api/utils.py b/marimo/_server/api/utils.pyindex 125afdaa08..1c6cbf93d2 100644--- a/marimo/_server/api/utils.py+++ b/marimo/_server/api/utils.py@@ -30,9 +30,13 @@ def require_header(header: list[str] | None) -> str:return header[0]-async def parse_request(request: Request, cls: Type[T]) -> T:+async def parse_request(+ request: Request, cls: Type[T], allow_unknown_keys: bool = False+) -> T:"""Parse the request body as a dataclass of type `cls`"""- return parse_raw(await request.body(), cls=cls)+ return parse_raw(+ await request.body(), cls=cls, allow_unknown_keys=allow_unknown_keys+ )def parse_title(filename: Optional[str]) -> str:diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex f86d964c8c..2e895d5e72 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -5,7 +5,7 @@ import base64import ioimport mimetypesimport os-from typing import cast+from typing import Optional, castfrom marimo import __version__from marimo._ast.cell import Cell, CellConfig, CellImpl@@ -177,25 +177,35 @@ class Exporter:# documents are executable.# Put data from AppFileManager into the yaml header.- ignored_keys = {"app_title", "layout_file", "css_file"}- metadata = {+ ignored_keys = {"app_title"}+ metadata: dict[str, str | list[str]] = {"title": get_app_title(file_manager),"marimo-version": __version__,- "marimo-layout": file_manager.app.config.layout_file,- "marimo-css": file_manager.app.config.css_file,}++ def _format_value(v: Optional[str | list[str]]) -> str | list[str]:+ if isinstance(v, list):+ return v+ return str(v)++ default_config = _AppConfig().asdict()+# Get values defined in _AppConfig without explicitly extracting keys,# as long as it isn't the default.metadata.update({- k: str(v)+ k: _format_value(v)for k, v in file_manager.app.config.asdict().items()- if k not in ignored_keys and v != _AppConfig.__dict__[k]+ if k not in ignored_keys and v != default_config.get(k)})header = yaml.dump(- {k: v for k, v in metadata.items() if v is not None},+ {+ k: v+ for k, v in metadata.items()+ if v is not None and v != "" and v != []+ },sort_keys=False,)document = ["---", header.strip(), "---", ""]diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex 7a0a144826..b98059055c 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -58,7 +58,7 @@ def notebook_page_template(else app_config.app_title,)html = html.replace(- "{{ app_config }}", json.dumps(_del_none(app_config.asdict()))+ "{{ app_config }}", json.dumps(_del_none_or_empty(app_config.asdict())))html = html.replace("{{ filename }}", filename or "")html = html.replace(@@ -114,7 +114,7 @@ def static_notebook_template()html = html.replace("{{ app_config }}",- json.dumps(_del_none(app_config.asdict()), sort_keys=True),+ json.dumps(_del_none_or_empty(app_config.asdict()), sort_keys=True),)html = html.replace("{{ filename }}", filename or "")html = html.replace("{{ mode }}", "read")@@ -195,9 +195,11 @@ def _serialize_list_to_base64(value: list[str]) -> list[str]:return [_serialize_to_base64(v) for v in value]-def _del_none(d: Any) -> Any:+def _del_none_or_empty(d: Any) -> Any:return {- key: _del_none(cast(Any, value)) if isinstance(value, dict) else value+ key: _del_none_or_empty(cast(Any, value))+ if isinstance(value, dict)+ else valuefor key, value in d.items()- if value is not None+ if value is not None and value != []}diff --git a/marimo/_smoke_tests/quak-demo.py b/marimo/_smoke_tests/quak-demo.pyindex 322980f96c..b93f8a2198 100644--- a/marimo/_smoke_tests/quak-demo.py+++ b/marimo/_smoke_tests/quak-demo.py@@ -2,10 +2,10 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "polars",# "marimo",-# "quak",-# "vega-datasets",+# "polars==1.5.0",+# "quak==0.1.8",+# "vega-datasets==0.9.0",# ]# ///diff --git a/marimo/_utils/config/config.py b/marimo/_utils/config/config.pyindex 4e899386e9..9749461f05 100644--- a/marimo/_utils/config/config.py+++ b/marimo/_utils/config/config.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import osfrom dataclasses import asdictfrom tempfile import TemporaryDirectory@@ -33,7 +35,7 @@ class ConfigReader:try:with open(self.filepath, "r") as file:data = tomlkit.parse(file.read())- return parse_raw(data, cls)+ return parse_raw(data, cls, allow_unknown_keys=True)except FileNotFoundError:return fallbackdiff --git a/marimo/_utils/parse_dataclass.py b/marimo/_utils/parse_dataclass.pyindex ec9b5dc671..b5188d73bb 100644--- a/marimo/_utils/parse_dataclass.py+++ b/marimo/_utils/parse_dataclass.py@@ -27,93 +27,114 @@ def to_snake(string: str) -> str:).lstrip("_")-def _build_value(value: Any, cls: Type[T]) -> T:- # origin_cls is not None if cls is a container (such as list, tuple, set,- # ...)- origin_cls = get_origin(cls)- if origin_cls is Optional:- (arg_type,) = get_args(cls)- if value is None:- return None # type: ignore[return-value]- else:- return _build_value(value, arg_type) # type: ignore # noqa: E501- elif origin_cls in (list, set):- (arg_type,) = get_args(cls)- return origin_cls(_build_value(v, arg_type) for v in value) # type: ignore # noqa: E501- elif origin_cls is tuple:- arg_types = get_args(cls)- if len(arg_types) == 2 and isinstance(arg_types[1], type(Ellipsis)):- return origin_cls(_build_value(v, arg_types[0]) for v in value) # type: ignore # noqa: E501- else:- return origin_cls( # type: ignore # noqa: E501- _build_value(v, t) for v, t in zip(value, arg_types)+class DataclassParser:+ def __init__(self, allow_unknown_keys: bool = False):+ self.allow_unknown_keys = allow_unknown_keys++ def _build_value(self, value: Any, cls: Type[T]) -> T:+ # origin_cls is not None if cls is a container (such as list,+ # tuple, set, ...)+ origin_cls = get_origin(cls)+ if origin_cls is Optional:+ (arg_type,) = get_args(cls)+ if value is None:+ return None # type: ignore[return-value]+ else:+ return self._build_value(value, arg_type) # type: ignore # noqa: E501+ elif origin_cls in (list, set):+ (arg_type,) = get_args(cls)+ return origin_cls(self._build_value(v, arg_type) for v in value) # type: ignore # noqa: E501+ elif origin_cls is tuple:+ arg_types = get_args(cls)+ if len(arg_types) == 2 and isinstance(+ arg_types[1], type(Ellipsis)+ ):+ return origin_cls( # type: ignore+ self._build_value(v, arg_types[0]) for v in value+ )+ else:+ return origin_cls( # type: ignore # noqa: E501+ self._build_value(v, t) for v, t in zip(value, arg_types)+ )+ elif origin_cls is dict:+ key_type, value_type = get_args(cls)+ return origin_cls( # type: ignore[no-any-return]+ **{+ self._build_value(k, key_type): self._build_value(+ v, value_type+ )+ for k, v in value.items()+ })- elif origin_cls is dict:- key_type, value_type = get_args(cls)- return origin_cls( # type: ignore[no-any-return]- **{- _build_value(k, key_type): _build_value(v, value_type)- for k, v in value.items()- }- )- elif origin_cls == Union:- arg_types = get_args(cls)- for arg_type in arg_types:- try:- return _build_value(value, arg_type) # type: ignore # noqa: E501- # catch expected exceptions when conversion fails- except (TypeError, ValueError):- continue- except:- raise- raise ValueError(f"Value '{value}' does not fit any type of the union")- elif origin_cls is Literal:- # if its a single Literal of an enum, we can just return the enum- arg_types = get_args(cls)- first_arg_type = arg_types[0]- if (- len(arg_types) == 1- and isinstance(first_arg_type, Enum)- and first_arg_type.value == value- ):- return first_arg_type # type: ignore[return-value]- if value not in arg_types:+ elif origin_cls == Union:+ arg_types = get_args(cls)+ for arg_type in arg_types:+ try:+ return self._build_value(value, arg_type) # type: ignore # noqa: E501+ # catch expected exceptions when conversion fails+ except (TypeError, ValueError):+ continue+ except:+ raiseraise ValueError(- f"Value '{value}' does not fit any type of the literal"+ f"Value '{value}' does not fit any type of the union")- return value # type: ignore[no-any-return]- elif type(cls) is type(Enum) and issubclass(cls, Enum):- return cls(value) # type: ignore[return-value]- elif dataclasses.is_dataclass(cls):- return build_dataclass(value, cls) # type: ignore[return-value]- else:- return value # type: ignore[no-any-return]-+ elif origin_cls is Literal:+ # if its a single Literal of an enum, we can just return the enum+ arg_types = get_args(cls)+ first_arg_type = arg_types[0]+ if (+ len(arg_types) == 1+ and isinstance(first_arg_type, Enum)+ and first_arg_type.value == value+ ):+ return first_arg_type # type: ignore[return-value]+ if value not in arg_types:+ raise ValueError(+ f"Value '{value}' does not fit any type of the literal"+ )+ return value # type: ignore[no-any-return]+ elif type(cls) is type(Enum) and issubclass(cls, Enum):+ return cls(value) # type: ignore[return-value]+ elif dataclasses.is_dataclass(cls):+ return self.build_dataclass(value, cls) # type: ignore[return-value]+ else:+ return value # type: ignore[no-any-return]-def build_dataclass(values: dict[Any, Any], cls: Type[T]) -> T:- """Returns instance of dataclass [cls] instantiated from [values]."""+ def build_dataclass(self, values: dict[Any, Any], cls: Type[T]) -> T:+ """Returns instance of dataclass [cls] instantiated from [values]."""- if not isinstance(values, dict):- raise ValueError(- "value passed to build_dataclass needs to be a dictionary"- )+ if not isinstance(values, dict):+ raise ValueError(+ "value passed to build_dataclass needs to be a dictionary"+ )- types = get_type_hints(cls)+ types = get_type_hints(cls)- snake_cased_values = {to_snake(k): v for k, v in values.items()}- if not snake_cased_values.keys() <= types.keys():- raise ValueError(- "values in build_dataclass do not match arguments for constructor"- )+ snake_cased_values = {to_snake(k): v for k, v in values.items()}+ if (+ not self.allow_unknown_keys+ and not snake_cased_values.keys() <= types.keys()+ ):+ raise ValueError(+ "values in build_dataclass do not match arguments "+ "for constructor"+ )- transformed = {- k: _build_value(v, types[k]) for k, v in snake_cased_values.items()- }+ transformed = {+ k: self._build_value(v, types[k])+ for k, v in snake_cased_values.items()+ if k in types+ }- return cls(**transformed)+ return cls(**transformed)-def parse_raw(message: Union[bytes, dict[Any, Any]], cls: Type[T]) -> T:+def parse_raw(+ message: Union[bytes, dict[Any, Any]],+ cls: Type[T],+ allow_unknown_keys: bool = False,+) -> T:"""Utility to parse a message as JSON, and instantiate into supplied type.`cls` must be a dataclass.@@ -133,6 +154,8 @@ def parse_raw(message: Union[bytes, dict[Any, Any]], cls: Type[T]) -> T:# If it is a dict, it is already parsed and we can just build the# dataclass.if isinstance(message, dict):- return build_dataclass(message, cls)+ return DataclassParser(allow_unknown_keys).build_dataclass(+ message, cls+ )parsed = json.loads(message)- return build_dataclass(parsed, cls)+ return DataclassParser(allow_unknown_keys).build_dataclass(parsed, cls)diff --git a/pyproject.toml b/pyproject.tomlindex 3b61ecaa0b..42f368a5c3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -98,6 +98,7 @@ dev = ["pillow~=10.4.0","types-Pillow~=10.2.0.20240520","polars~=1.5.0",+ "hypothesis~=6.102.1","pytest~=8.3.2","pytest-codecov~=0.5.1","pytest-asyncio~=0.23.8",diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.pyindex 8364bbf4bf..a6b14f34ae 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -312,6 +312,7 @@ class TestApp:"css_file": None,"width": "full","layout_file": None,+ "auto_download": [],}@staticmethod@@ -460,6 +461,36 @@ class TestApp:assert isinstance(outputs[1], Axes)assert outputs[0] != outputs[1]+ @staticmethod+ def test_app_config_auto_download():+ # Test default value+ config = _AppConfig()+ assert config.auto_download == []++ # Test setting auto_download+ config = _AppConfig(auto_download=["html", "markdown"])+ assert config.auto_download == ["html", "markdown"]++ # Test updating auto_download+ config.update({"auto_download": ["html"]})+ assert config.auto_download == ["html"]++ # Test setting empty list+ config.update({"auto_download": []})+ assert config.auto_download == []++ # Test from_untrusted_dict+ config = _AppConfig.from_untrusted_dict({"auto_download": ["markdown"]})+ assert config.auto_download == ["markdown"]++ # Test asdict+ config_dict = config.asdict()+ assert config_dict["auto_download"] == ["markdown"]++ # Test invalid values are allowed for forward compatibility+ config = _AppConfig(auto_download=["invalid"])+ assert config.auto_download == ["invalid"]+def test_app_config() -> None:config = _AppConfig.from_untrusted_dict({"width": "full"})@@ -470,6 +501,7 @@ def test_app_config() -> None:"css_file": None,"width": "full","layout_file": None,+ "auto_download": [],}@@ -484,6 +516,7 @@ def test_app_config_extra_args_ignored() -> None:"css_file": None,"width": "full","layout_file": None,+ "auto_download": [],}diff --git a/tests/_ast/test_app_config.py b/tests/_ast/test_app_config.pynew file mode 100644index 0000000000..24f9fcce6a--- /dev/null+++ b/tests/_ast/test_app_config.py@@ -0,0 +1,81 @@+from __future__ import annotations++from typing import Any++import pytest++from marimo._ast.app import _AppConfig+++def test_app_config_default():+ config = _AppConfig()+ assert config.width == "compact"+ assert config.app_title is None+ assert config.css_file is None+ assert config.auto_download == []+++def test_app_config_from_untrusted_dict():+ updates = {+ "width": "full",+ "app_title": "My App",+ "css_file": "custom.css",+ "auto_download": ["html", "markdown"],+ "invalid_key": "should be ignored",+ }+ config = _AppConfig.from_untrusted_dict(updates)+ assert config.width == "full"+ assert config.app_title == "My App"+ assert config.css_file == "custom.css"+ assert config.auto_download == ["html", "markdown"]+ assert not hasattr(config, "invalid_key")+++def test_app_config_asdict():+ config = _AppConfig(+ width="medium",+ app_title="Test App",+ css_file="style.css",+ auto_download=["html"],+ )+ config_dict = config.asdict()+ assert config_dict == {+ "width": "medium",+ "app_title": "Test App",+ "css_file": "style.css",+ "auto_download": ["html"],+ "layout_file": None,+ }+++def test_app_config_update():+ config = _AppConfig()+ updates = {+ "width": "full",+ "app_title": "Updated App",+ "auto_download": ["markdown"],+ }+ updated_config = config.update(updates)+ assert updated_config.width == "full"+ assert updated_config.app_title == "Updated App"+ assert updated_config.auto_download == ["markdown"]+ assert updated_config.css_file is None+++ ("auto_download", "expected"),+ [+ ([], []),+ (["html"], ["html"]),+ (["markdown"], ["markdown"]),+ (["html", "markdown"], ["html", "markdown"]),+ # Invalid values should be left+ # so it forwards-compatible+ (["invalid"], ["invalid"]),+ ],+)+def test_app_config_auto_download(+ auto_download: list[Any], expected: list[str]+) -> None:+ config = _AppConfig(auto_download=auto_download)+ assert config.auto_download == expecteddiff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.pyindex 10c85ead18..c55b89df54 100644--- a/tests/_ast/test_codegen.py+++ b/tests/_ast/test_codegen.py@@ -232,6 +232,37 @@ class TestGeneration:"test_generate_filecontents_shadowed_builtin")+ @staticmethod+ def test_generate_app_constructor_with_auto_download() -> None:+ config = _AppConfig(+ width="full",+ app_title="Test App",+ css_file="custom.css",+ auto_download=["html", "markdown"],+ )+ result = codegen.generate_app_constructor(config)+ expected = (+ "app = marimo.App(\n"+ ' width="full",\n'+ ' app_title="Test App",\n'+ ' css_file="custom.css",\n'+ ' auto_download=["html", "markdown"],\n'+ ")"+ )+ assert result == expected++ @staticmethod+ def test_generate_app_constructor_with_empty_auto_download() -> None:+ config = _AppConfig(auto_download=[])+ result = codegen.generate_app_constructor(config)+ assert result == "app = marimo.App()"++ @staticmethod+ def test_generate_app_constructor_with_single_auto_download() -> None:+ config = _AppConfig(auto_download=["html"])+ result = codegen.generate_app_constructor(config)+ assert result == 'app = marimo.App(auto_download=["html"])'+class TestGetCodes:@staticmethoddiff --git a/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py b/tests/_plugins/ui/_impl/utils/test_dataframe_utils.pyindex d257e79496..c6f77a6a12 100644--- a/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py+++ b/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py@@ -9,6 +9,7 @@ from marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins.ui._impl.tables.utils import get_table_managerHAS_PANDAS = DependencyManager.pandas.has()+HAS_NARWHALS = DependencyManager.narwhals.has()def _get_row_headers(@@ -58,7 +59,8 @@ def test_get_row_headers_list() -> None:@pytest.mark.skipif(- not HAS_PANDAS, reason="optional dependencies not installed"+ not HAS_PANDAS or not HAS_NARWHALS,+ reason="optional dependencies not installed",)def test_get_table_manager() -> None:import narwhals as nwdiff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.pyindex 1e13835bd0..e612edb2ef 100644--- a/tests/_server/api/endpoints/test_export.py+++ b/tests/_server/api/endpoints/test_export.py@@ -197,7 +197,6 @@ def test_auto_export_html(client: TestClient, temp_marimo_file: str) -> None:)# Not modified responseassert response.status_code == 304- assert response.json() == {}# Assert .marimo file is createdassert os.path.exists(@@ -236,7 +235,6 @@ def test_auto_export_html_no_code()# Not modified responseassert response.status_code == 304- assert response.json() == {}# Assert .marimo file is createdassert os.path.exists(@@ -271,7 +269,6 @@ def test_auto_export_markdown()# Not modified responseassert response.status_code == 304- assert response.json() == {}# Assert .marimo file is createdassert os.path.exists(diff --git a/tests/_utils/test_parse_dataclass.py b/tests/_utils/test_parse_dataclass.pyindex ef5c70c8c6..a2bab0e0f8 100644--- a/tests/_utils/test_parse_dataclass.py+++ b/tests/_utils/test_parse_dataclass.py@@ -9,7 +9,7 @@ from typing import Any, Dict, List, Literal, Optional, Tuple, Unionimport pytestfrom marimo._runtime.requests import SetCellConfigRequest-from marimo._utils.parse_dataclass import build_dataclass, parse_raw+from marimo._utils.parse_dataclass import parse_raw@dataclass@@ -230,10 +230,10 @@ def test_build_optional() -> None:class TestOptional:x: Optional[str] = None- parsed = build_dataclass({}, TestOptional)+ parsed = parse_raw({}, TestOptional)assert parsed == TestOptional(x=None)- parsed = build_dataclass({"x": "hello"}, TestOptional)+ parsed = parse_raw({"x": "hello"}, TestOptional)assert parsed == TestOptional(x="hello")@@ -241,5 +241,13 @@ def test_build_empty_dataclass() -> None:@dataclassclass Empty: ...- parsed = build_dataclass({}, Empty)+ parsed = parse_raw({}, Empty)+ assert parsed == Empty()+++def test_with_unknown_keys() -> None:+ @dataclass+ class Empty: ...++ parsed = parse_raw({"key": "value"}, Empty, allow_unknown_keys=True)assert parsed == Empty()