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
fix: send app-config in kernel ready response (#1133)
Myles Scolnickf31dafd22395
diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.tsindex 4a3e3b0583..5c1e6b5a56 100644--- a/frontend/src/core/config/config.ts+++ b/frontend/src/core/config/config.ts@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import { atom, useAtom } from "jotai";+import { atom, useAtom, useSetAtom } from "jotai";import {AppConfig,UserConfig,@@ -40,6 +40,10 @@ export function useAppConfig() {return useAtom(appConfigAtom);}+export function useSetAppConfig() {+ return useSetAtom(appConfigAtom);+}+export function getAppConfig() {return store.get(appConfigAtom);}diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.tsindex c96b5a9a18..9efdf89102 100644--- a/frontend/src/core/kernel/messages.ts+++ b/frontend/src/core/kernel/messages.ts@@ -6,6 +6,7 @@ import { CellId, UIElementId } from "../cells/ids";import { VariableName } from "../variables/types";import { RequestId } from "../network/DeferredRequestRegistry";import { Seconds } from "@/utils/time";+import { AppConfig } from "../config/config-schema";export type OutputChannel =| "output"@@ -214,6 +215,10 @@ export type OperationMessage =* The last executed code*/last_executed_code: Record<CellId, string | undefined> | undefined;+ /**+ * App config+ */+ app_config: AppConfig;};}| {diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 6497d5c84b..0bd73016f1 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -35,6 +35,7 @@ import { useBannersActions } from "../errors/state";import { useAlertActions } from "../alerts/state";import { generateUUID } from "@/utils/uuid";import { createWsUrl } from "./createWsUrl";+import { useSetAppConfig } from "../config/config";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.@@ -50,6 +51,7 @@ export function useMarimoWebSocket(opts: {const { showBoundary } = useErrorBoundary();const { handleCellMessage } = useCellActions();+ const setAppConfig = useSetAppConfig();const { setVariables, setMetadata } = useVariablesActions();const { setLayoutData } = useLayoutActions();const [connStatus, setConnStatus] = useAtom(connectionAtom);@@ -72,6 +74,7 @@ export function useMarimoWebSocket(opts: {ui_values,cell_ids,last_executed_code = {},+ app_config,} = msg.data;// Set the layout, initial codes, cells@@ -108,6 +111,7 @@ export function useMarimoWebSocket(opts: {setLayoutData({ layoutView: layout.type, data: layoutData });}setCells(cells, layoutState);+ setAppConfig(app_config);// If resumed, we don't need to instantiate the UI elements,// and we should read in th existing values from the kernel.diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex 570592f8e2..87cce86dd3 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -49,6 +49,18 @@ class _AppConfig:# The file path of the layout file, relative to the app file.layout_file: Optional[str] = None+ @staticmethod+ def from_untrusted_dict(updates: dict[str, Any]) -> _AppConfig:+ config = _AppConfig()+ for key in updates:+ if hasattr(config, key):+ config.__setattr__(key, updates[key])+ else:+ LOGGER.warning(+ f"Unrecognized key '{key}' in app config. Ignoring."+ )+ return config+def asdict(self) -> dict[str, Any]:return asdict(self)@@ -110,10 +122,7 @@ class App:# Take `AppConfig` as kwargs for forward/backward compatibility;# unrecognized settings will just be dropped, instead of raising# a TypeError.- self._config = _AppConfig()- for key in asdict(self._config):- if key in kwargs:- self._config.__setattr__(key, kwargs.pop(key))+ self._config = _AppConfig.from_untrusted_dict(kwargs)self._cell_manager = CellManager()self._graph = dataflow.DirectedGraph()diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 134487093c..f30f39636d 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -24,6 +24,7 @@ from typing import ()from marimo import _loggers as loggers+from marimo._ast.app import _AppConfigfrom marimo._ast.cell import CellConfig, CellId_t, CellStatusTypefrom marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.completion_option import CompletionOption@@ -266,6 +267,8 @@ class KernelReady(Op):ui_values: Optional[Dict[str, JSONType]]# If the kernel was resumed, the last executed code for each celllast_executed_code: Optional[Dict[CellId_t, str]]+ # App config+ app_config: _AppConfig@dataclassdiff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex 55c2f19d70..9b85840f12 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -113,6 +113,7 @@ def create_session(resumed=False,ui_values={},last_executed_code={},+ app_config=app.config,)),)diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex f5214e0d65..b50053a4f8 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -163,6 +163,7 @@ class WebsocketHandler(SessionConsumer):resumed=resumed,ui_values=ui_values,last_executed_code=last_executed_code,+ app_config=app.config,)),)diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.pyindex fcc2d34970..a22de11bcb 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -5,7 +5,7 @@ from typing import Anyimport pytest-from marimo._ast.app import App+from marimo._ast.app import App, _AppConfigfrom marimo._ast.errors import (CycleError,DeleteNonlocalError,@@ -379,3 +379,19 @@ class TestApp:assert defs["x"] == 0assert defs["y"] == 1+++def test_app_config() -> None:+ config = _AppConfig.from_untrusted_dict({"width": "full"})+ assert config.width == "full"+ assert config.layout_file is None+ assert config.asdict() == {"width": "full", "layout_file": None}+++def test_app_config_extra_args_ignored() -> None:+ config = _AppConfig.from_untrusted_dict(+ {"width": "full", "fake_config": "foo"}+ )+ assert config.width == "full"+ assert config.layout_file is None+ assert config.asdict() == {"width": "full", "layout_file": None}diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.pyindex ee3eeb6fe4..2f1be06c6d 100644--- a/tests/_server/api/endpoints/test_files.py+++ b/tests/_server/api/endpoints/test_files.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import osimport random@@ -211,16 +213,16 @@ def test_save_app_config(client: TestClient) -> None:assert filenamefile_contents = open(filename).read()- assert 'marimo.App(width="full"' not in file_contents+ assert 'marimo.App(width="medium"' not in file_contentsresponse = client.post("/api/kernel/save_app_config",headers=HEADERS,json={- "config": {"width": "full"},+ "config": {"width": "medium"},},)assert response.status_code == 200, response.textassert response.json()["success"] is Truefile_contents = open(filename).read()- assert 'marimo.App(width="full"' in file_contents+ assert 'marimo.App(width="medium"' in file_contentsdiff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.pyindex 6d17af489d..68d1e8f2b8 100644--- a/tests/_server/api/endpoints/test_resume_session.py+++ b/tests/_server/api/endpoints/test_resume_session.py@@ -24,6 +24,7 @@ def create_response("ui_values": {},"last_executed_code": {},"configs": [{"disabled": False, "hide_code": False}],+ "app_config": {"width": "full"},}response.update(partial_response)return response@@ -53,6 +54,7 @@ def assert_kernel_ready_response(assert data.resumed == expected.resumedassert data.ui_values == expected.ui_valuesassert data.configs == expected.configs+ assert data.app_config == expected.app_configdef get_session(client: TestClient, session_id: str) -> Optional[Session]:diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex b6de33f0bf..c4a798fa90 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -29,6 +29,7 @@ def create_response("ui_values": {},"last_executed_code": {},"configs": [{"disabled": False, "hide_code": False}],+ "app_config": {"width": "full"},}response.update(partial_response)return response@@ -53,6 +54,7 @@ def assert_kernel_ready_response(assert data.resumed == expected.resumedassert data.ui_values == expected.ui_valuesassert data.configs == expected.configs+ assert data.app_config == expected.app_configdef assert_parse_ready_response(raw_data: dict[str, Any]) -> None:diff --git a/tests/_server/mocks.py b/tests/_server/mocks.pyindex 1ab80af78e..02669f04f8 100644--- a/tests/_server/mocks.py+++ b/tests/_server/mocks.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import tempfilefrom typing import Any, Callable, castfrom unittest.mock import MagicMock@@ -23,7 +25,7 @@ def get_mock_session_manager() -> SessionManager:import marimo__generated_with = "0.0.1"-app = marimo.App()+app = marimo.App(width="full")@app.cell