Skip to content

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.

vscode: theming for vscode, return code on save (#1628)

Myles Scolnick279ecfe8cd7b
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index b189950cb4..eb1016704c 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -162,6 +162,7 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
filename,
configs,
layout: getSerializedLayout(),
+ persist: true,
}).then(() => {
if (userInitiated) {
toast({ title: "Notebook saved" });
diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.ts
index 1dc0ebe8fc..ccf7650f44 100644
--- a/frontend/src/core/islands/main.ts
+++ b/frontend/src/core/islands/main.ts
@@ -37,6 +37,9 @@ import { RequestId } from "../network/DeferredRequestRegistry";
* Initialize the Marimo app.
*/
export async function initialize() {
+ // This will display all the static HTML content.
+ initializePlugins();
+
// Add 'marimo' class name to all `marimo-island` elements.
const islands = document.querySelectorAll<HTMLElement>(
MarimoIslandElement.tagName,
@@ -51,9 +54,6 @@ export async function initialize() {
island.classList.add(MarimoIslandElement.styleNamespace);
}
- // This will display all the static HTML content.
- initializePlugins();
-
const actions = createNotebookActions((action) => {
store.set(notebookAtom, (state) => notebookReducer(state, action));
});
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index 0d711cb158..9547bc8b12 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -29,6 +29,7 @@ export function createNetworkRequests(): EditRequests & RunRequests {
return marimoClient
.POST("/api/kernel/save", {
body: request,
+ parseAs: "text",
})
.then(handleResponseReturnNull);
},
@@ -88,6 +89,7 @@ export function createNetworkRequests(): EditRequests & RunRequests {
return marimoClient
.POST("/api/kernel/save_app_config", {
body: request,
+ parseAs: "text",
})
.then(handleResponseReturnNull);
},
diff --git a/frontend/src/theme/useTheme.ts b/frontend/src/theme/useTheme.ts
index 7d9141b314..c083eba845 100644
--- a/frontend/src/theme/useTheme.ts
+++ b/frontend/src/theme/useTheme.ts
@@ -22,7 +22,9 @@ const themeAtom = atom((get) => {
// If it has data-theme=dark or data-mode=dark on the body, use dark mode.
if (
document.body.dataset.theme === "dark" ||
- document.body.dataset.mode === "dark"
+ document.body.dataset.mode === "dark" ||
+ document.body.dataset.vscodeThemeKind === "vscode-dark" ||
+ document.body.dataset.vscodeThemeKind === "vscode-high-contrast"
) {
return "dark";
}
diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.py
index b1e5027b39..bc7a3a9c82 100644
--- a/marimo/_server/api/endpoints/files.py
+++ b/marimo/_server/api/endpoints/files.py
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING
from starlette.authentication import requires
from starlette.exceptions import HTTPException
+from starlette.responses import PlainTextResponse
from marimo import _loggers
from marimo._ast import codegen
@@ -154,7 +155,7 @@ async def open_file(
async def save(
*,
request: Request,
-) -> BaseResponse:
+) -> PlainTextResponse:
"""
requestBody:
content:
@@ -165,16 +166,16 @@ async def save(
200:
description: Save the current app
content:
- application/json:
+ text/plain:
schema:
- $ref: "#/components/schemas/SuccessResponse"
+ type: string
"""
app_state = AppState(request)
body = await parse_request(request, cls=SaveNotebookRequest)
session = app_state.require_current_session()
- session.app_file_manager.save(body)
+ contents = session.app_file_manager.save(body)
- return SuccessResponse()
+ return PlainTextResponse(content=contents)
@router.post("/save_app_config")
@@ -182,7 +183,7 @@ async def save(
async def save_app_config(
*,
request: Request,
-) -> BaseResponse:
+) -> PlainTextResponse:
"""
requestBody:
content:
@@ -193,13 +194,13 @@ async def save_app_config(
200:
description: Save the app configuration
content:
- application/json:
+ text/plain:
schema:
- $ref: "#/components/schemas/SuccessResponse"
+ type: string
"""
app_state = AppState(request)
body = await parse_request(request, cls=SaveAppConfigurationRequest)
session = app_state.require_current_session()
- session.app_file_manager.save_app_config(body.config)
+ contents = session.app_file_manager.save_app_config(body.config)
- return SuccessResponse()
+ return PlainTextResponse(content=contents)
diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.py
index 52c9fcc4dd..0d83ea9b75 100644
--- a/marimo/_server/file_manager.py
+++ b/marimo/_server/file_manager.py
@@ -91,7 +91,9 @@ class AppFileManager:
names: list[str],
configs: list[CellConfig],
app_config: _AppConfig,
- ) -> None:
+ # Whether or not to persist the app to the file system
+ persist: bool,
+ ) -> str:
LOGGER.debug("Saving app to %s", filename)
if filename.endswith(".md"):
# TODO: Remember just proof of concept, potentially needs
@@ -112,11 +114,15 @@ class AppFileManager:
config=app_config,
header_comments=header_comments,
)
- self._create_file(filename, contents)
+
+ if persist:
+ self._create_file(filename, contents)
if self._is_unnamed():
self.rename(filename)
+ return contents
+
def _load_app(self, path: Optional[str]) -> InternalApp:
"""Read the app from the file."""
app = codegen.get_app(path)
@@ -164,6 +170,7 @@ class AppFileManager:
list(self.app.cell_manager.names()),
list(self.app.cell_manager.configs()),
self.app.config,
+ persist=True,
)
def read_layout_config(self) -> Optional[LayoutConfig]:
@@ -185,22 +192,24 @@ class AppFileManager:
except AttributeError:
return None
- def save_app_config(self, config: Dict[str, Any]) -> None:
+ def save_app_config(self, config: Dict[str, Any]) -> str:
"""Save the app configuration."""
# Update the file with the latest app config
# TODO(akshayka): Only change the `app = marimo.App` line (at top level
# of file), instead of overwriting the whole file.
new_config = self.app.update_config(config)
if self.filename is not None:
- self._save_file(
+ return self._save_file(
self.filename,
list(self.app.cell_manager.codes()),
list(self.app.cell_manager.names()),
list(self.app.cell_manager.configs()),
new_config,
+ persist=True,
)
+ return ""
- def save(self, request: SaveNotebookRequest) -> None:
+ def save(self, request: SaveNotebookRequest) -> str:
"""Save the current app."""
cell_ids, codes, configs, names, filename, layout = (
request.cell_ids,
@@ -238,7 +247,12 @@ class AppFileManager:
# deleting state that the user might want to keep
self.app.update_config({"layout_file": None})
return self._save_file(
- filename, codes, names, configs, self.app.config
+ filename,
+ codes,
+ names,
+ configs,
+ self.app.config,
+ persist=request.persist,
)
def to_code(self) -> str:
diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.py
index 47f7e07994..d8b11aee36 100644
--- a/marimo/_server/models/models.py
+++ b/marimo/_server/models/models.py
@@ -100,6 +100,8 @@ class SaveNotebookRequest:
filename: str
# layout of app
layout: Optional[Dict[str, Any]] = None
+ # persist the file to disk
+ persist: bool = True
# Validate same length
def __post_init__(self) -> None:
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 4a7ec20800..e5fe4c744b 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -1401,12 +1401,15 @@ components:
items:
type: string
type: array
+ persist:
+ type: boolean
required:
- cellIds
- codes
- names
- configs
- filename
+ - persist
type: object
SaveUserConfigurationRequest:
properties:
@@ -2014,9 +2017,9 @@ paths:
responses:
200:
content:
- application/json:
+ text/plain:
schema:
- $ref: '#/components/schemas/SuccessResponse'
+ type: string
description: Save the current app
/api/kernel/save_app_config:
post:
@@ -2028,9 +2031,9 @@ paths:
responses:
200:
content:
- application/json:
+ text/plain:
schema:
- $ref: '#/components/schemas/SuccessResponse'
+ type: string
description: Save the app configuration
/api/kernel/save_user_config:
post:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index 75b6f0fdca..2a589f4ef5 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -517,7 +517,7 @@ export interface paths {
/** @description Save the current app */
200: {
content: {
- "application/json": components["schemas"]["SuccessResponse"];
+ "text/plain": string;
};
};
};
@@ -534,7 +534,7 @@ export interface paths {
/** @description Save the app configuration */
200: {
content: {
- "application/json": components["schemas"]["SuccessResponse"];
+ "text/plain": string;
};
};
};
@@ -990,7 +990,7 @@ export interface components {
function_call_id: string;
/** @enum {string} */
name: "function-call-result";
- return_value: components["schemas"]["JSONType"];
+ return_value?: components["schemas"]["JSONType"];
status: components["schemas"]["HumanReadableStatus"];
};
HumanReadableStatus: {
@@ -1285,6 +1285,7 @@ export interface components {
[key: string]: unknown;
} | null;
names: string[];
+ persist: boolean;
};
SaveUserConfigurationRequest: {
config: components["schemas"]["MarimoConfig"];
diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.py
index 6319344e91..30de8990d5 100644
--- a/tests/_server/api/endpoints/test_files.py
+++ b/tests/_server/api/endpoints/test_files.py
@@ -77,7 +77,7 @@ def test_save_file(client: TestClient) -> None:
},
)
assert response.status_code == 200, response.text
- assert response.json()["success"] is True
+ assert "import marimo" in response.text
file_contents = open(filename).read()
assert "import marimo as mo" in file_contents
assert "@app.cell(hide_code=True)" in file_contents
@@ -133,7 +133,7 @@ def test_save_with_header(client: TestClient) -> None:
)
assert response.status_code == 200, response.text
- assert response.json()["success"] is True
+ assert "import marimo" in response.text
file_contents = open(filename).read()
assert "import marimo as mo" in file_contents
assert file_contents.startswith(header.rstrip()), "Header was removed"
@@ -176,7 +176,7 @@ def test_save_with_invalid_file(client: TestClient) -> None:
)
assert response.status_code == 200, response.text
- assert response.json()["success"] is True
+ assert "import marimo" in response.text
file_contents = open(filename).read()
assert file_contents.startswith("import marimo"), "Header was not removed"
assert "@app.cell(hide_code=True)" in file_contents
@@ -223,6 +223,6 @@ def test_save_app_config(client: TestClient) -> None:
},
)
assert response.status_code == 200, response.text
- assert response.json()["success"] is True
+ assert "import marimo" in response.text
file_contents = open(filename).read()
assert 'marimo.App(width="medium"' in file_contents