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.

chore: move frontend to generated api types and fetcher (#1596)

Myles Scolnickab31644669da
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index ff7af0048f..e55ccdf9ab 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -55,7 +55,7 @@ jobs:
run: pnpm turbo typecheck
- name: 🧪 Test
- run: pnpm turbo test
+ run: pnpm test
- name: 📦 Build
run: pnpm turbo build
diff --git a/frontend/package.json b/frontend/package.json
index 68071ed296..ef88cfa851 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -35,6 +35,7 @@
"@lezer/common": "^1.2.1",
"@lezer/highlight": "^1.2.0",
"@lezer/lr": "^1.4.1",
+ "@marimo-team/marimo-api": "file:../openapi",
"@marimo-team/react-slotz": "^0.1.8",
"@open-rpc/client-js": "^1.8.1",
"@paralleldrive/cuid2": "^2.2.2",
@@ -199,10 +200,11 @@
"stylelint": "^16.6.1",
"stylelint-config-standard": "^36.0.0",
"tailwindcss": "^3.4.3",
- "turbo": "^1.13.3",
+ "turbo": "^2.0.3",
"typescript": "^5.4.5",
"vite": "^5.2.12",
"vite-tsconfig-paths": "^4.3.2",
"vitest": "^1.6.0"
- }
+ },
+ "packageManager": "[email protected]"
}
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 3bef98fa1b..173d34aabf 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -71,6 +71,9 @@ dependencies:
'@lezer/lr':
specifier: ^1.4.1
version: 1.4.1
+ '@marimo-team/marimo-api':
+ specifier: file:../openapi
+ version: file:../openapi
'@marimo-team/react-slotz':
specifier: ^0.1.8
version: 0.1.8([email protected])
@@ -488,8 +491,8 @@ devDependencies:
specifier: ^3.4.3
version: 3.4.3
turbo:
- specifier: ^1.13.3
- version: 1.13.3
+ specifier: ^2.0.3
+ version: 2.0.3
typescript:
specifier: ^5.4.5
version: 5.4.5
@@ -14931,6 +14934,16 @@ packages:
is-wsl: 2.2.0
dev: true
+ resolution: {integrity: sha512-NMp/GEmWSGO0b2d731IdGXcMP2PF85Rk1q+oy2Mx/DYMdP3pgTZTRamKxgZpkHhM4iOVsyD1iP5HKL9Fr6CH2Q==}
+ dependencies:
+ openapi-typescript-helpers: 0.0.8
+ dev: false
+
+ resolution: {integrity: sha512-1eNjQtbfNi5Z/kFhagDIaIRj6qqDzhjNJKz8cmMW0CVdGwT6e1GLbAfgI0d28VTJa1A8jz82jm/4dG8qNoNS8g==}
+ dev: false
+
resolution: {integrity: sha512-TCx0dXQzVtSCg2OgY/bO9hjM9cV4XYx09TVK+s3+FhkjT6LovsLe+pPMzpWf+6yXK/hUizs2gUoTw3jHM0VaTQ==}
dependencies:
@@ -18180,64 +18193,64 @@ packages:
safe-buffer: 5.2.1
dev: false
- resolution: {integrity: sha512-glup8Qx1qEFB5jerAnXbS8WrL92OKyMmg5Hnd4PleLljAeYmx+cmmnsmLT7tpaVZIN58EAAwu8wHC6kIIqhbWA==}
+ resolution: {integrity: sha512-v7ztJ8sxdHw3SLfO2MhGFeeU4LQhFii1hIGs9uBiXns/0YTGOvxLeifnfGqhfSrAIIhrCoByXO7nR9wlm10n3Q==}
cpu: [x64]
os: [darwin]
requiresBuild: true
dev: true
optional: true
- resolution: {integrity: sha512-/np2xD+f/+9qY8BVtuOQXRq5f9LehCFxamiQnwdqWm5iZmdjygC5T3uVSYuagVFsZKMvX3ycySwh8dylGTl6lg==}
+ resolution: {integrity: sha512-LUcqvkV9Bxtng6QHbevp8IK8zzwbIxM6HMjCE7FEW6yJBN1KwvTtRtsGBwwmTxaaLO0wD1Jgl3vgkXAmQ4fqUw==}
cpu: [arm64]
os: [darwin]
requiresBuild: true
dev: true
optional: true
- resolution: {integrity: sha512-G+HGrau54iAnbXLfl+N/PynqpDwi/uDzb6iM9hXEDG+yJnSJxaHMShhOkXYJPk9offm9prH33Khx2scXrYVW1g==}
+ resolution: {integrity: sha512-xpdY1suXoEbsQsu0kPep2zrB8ijv/S5aKKrntGuQ62hCiwDFoDcA/Z7FZ8IHQ2u+dpJARa7yfiByHmizFE0r5Q==}
cpu: [x64]
os: [linux]
requiresBuild: true
dev: true
optional: true
- resolution: {integrity: sha512-qWwEl5VR02NqRyl68/3pwp3c/olZuSp+vwlwrunuoNTm6JXGLG5pTeme4zoHNnk0qn4cCX7DFrOboArlYxv0wQ==}
+ resolution: {integrity: sha512-MBACTcSR874L1FtLL7gkgbI4yYJWBUCqeBN/iE29D+8EFe0d3fAyviFlbQP4K/HaDYet1i26xkkOiWr0z7/V9A==}
cpu: [arm64]
os: [linux]
requiresBuild: true
dev: true
optional: true
- resolution: {integrity: sha512-Nudr4bRChfJzBPzEmpVV85VwUYRCGKecwkBFpbp2a4NtrJ3+UP1VZES653ckqCu2FRyRuS0n03v9euMbAvzH+Q==}
+ resolution: {integrity: sha512-zi3YuKPkM9JxMTshZo3excPk37hUrj5WfnCqh4FjI26ux6j/LJK+Dh3SebMHd9mR7wP9CMam4GhmLCT+gDfM+w==}
cpu: [x64]
os: [win32]
requiresBuild: true
dev: true
optional: true
- resolution: {integrity: sha512-ouJCgsVLd3icjRLmRvHQDDZnmGzT64GBupM1Y+TjtYn2LVaEBoV6hicFy8x5DUpnqdLy+YpCzRMkWlwhmkX7sQ==}
+ resolution: {integrity: sha512-wmed4kkenLvRbidi7gISB4PU77ujBuZfgVGDZ4DXTFslE/kYpINulwzkVwJIvNXsJtHqyOq0n6jL8Zwl3BrwDg==}
cpu: [arm64]
os: [win32]
requiresBuild: true
dev: true
optional: true
- resolution: {integrity: sha512-n17HJv4F4CpsYTvKzUJhLbyewbXjq1oLCi90i5tW1TiWDz16ML1eDG7wi5dHaKxzh5efIM56SITnuVbMq5dk4g==}
+ resolution: {integrity: sha512-jF1K0tTUyryEWmgqk1V0ALbSz3VdeZ8FXUo6B64WsPksCMCE48N5jUezGOH2MN0+epdaRMH8/WcPU0QQaVfeLA==}
hasBin: true
optionalDependencies:
- turbo-darwin-64: 1.13.3
- turbo-darwin-arm64: 1.13.3
- turbo-linux-64: 1.13.3
- turbo-linux-arm64: 1.13.3
- turbo-windows-64: 1.13.3
- turbo-windows-arm64: 1.13.3
+ turbo-darwin-64: 2.0.3
+ turbo-darwin-arm64: 2.0.3
+ turbo-linux-64: 2.0.3
+ turbo-linux-arm64: 2.0.3
+ turbo-windows-64: 2.0.3
+ turbo-windows-arm64: 2.0.3
dev: true
@@ -19668,3 +19681,10 @@ packages:
react: 18.3.1
use-sync-external-store: 1.2.0([email protected])
dev: false
+
+ file:../openapi:
+ resolution: {directory: ../openapi, type: directory}
+ name: '@marimo-team/marimo-api'
+ dependencies:
+ openapi-fetch: 0.9.7
+ dev: false
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 8bb3629005..81040c4b90 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { zodResolver } from "@hookform/resolvers/zod";
-import { DefaultValues, useForm } from "react-hook-form";
+import { useForm } from "react-hook-form";
import {
Form,
FormControl,
@@ -44,7 +44,7 @@ export const UserConfigForm: React.FC = () => {
// Create form
const form = useForm<UserConfig>({
resolver: zodResolver(UserConfigSchema),
- defaultValues: config as DefaultValues<UserConfig>,
+ defaultValues: config,
});
const onSubmit = async (values: UserConfig) => {
diff --git a/frontend/src/components/data-table/__test__/columns.test.ts b/frontend/src/components/data-table/__test__/columns.test.ts
index 03f61714f7..99cfeed291 100644
--- a/frontend/src/components/data-table/__test__/columns.test.ts
+++ b/frontend/src/components/data-table/__test__/columns.test.ts
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { expect, test } from "vitest";
-import { uniformSample } from "../columns";
+import { uniformSample } from "../uniformSample";
test("uniformSample", () => {
const items = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index 49f1cde2a0..56c9397205 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -7,6 +7,7 @@ import {
import { Checkbox } from "../ui/checkbox";
import { MimeCell } from "./mime-cell";
import { TableColumnSummary } from "./column-summary";
+import { uniformSample } from "./uniformSample";
interface ColumnInfo {
key: string;
@@ -177,21 +178,3 @@ function isPrimitiveOrNullish(value: unknown): boolean {
const isObject = typeof value === "object";
return !isObject;
}
-
-/**
- * Uniformly sample n items from an array
- */
-export function uniformSample<T>(items: T[], n: number): T[] {
- if (items.length <= n) {
- return items;
- }
- const sample: T[] = [];
- const step = items.length / n;
- for (let i = 0; i < n - 1; i++) {
- const idx = Math.floor(i * step);
- sample.push(items[idx]);
- }
- const last = items.at(-1) as T;
- sample.push(last);
- return sample;
-}
diff --git a/frontend/src/components/data-table/uniformSample.tsx b/frontend/src/components/data-table/uniformSample.tsx
new file mode 100644
index 0000000000..a3281d8920
--- /dev/null
+++ b/frontend/src/components/data-table/uniformSample.tsx
@@ -0,0 +1,19 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+/**
+ * Uniformly sample n items from an array
+ */
+export function uniformSample<T>(items: T[], n: number): T[] {
+ if (items.length <= n) {
+ return items;
+ }
+ const sample: T[] = [];
+ const step = items.length / n;
+ for (let i = 0; i < n - 1; i++) {
+ const idx = Math.floor(i * step);
+ sample.push(items[idx]);
+ }
+ const last = items.at(-1) as T;
+ sample.push(last);
+ return sample;
+}
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index da41f8d21a..2969a2bd52 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -204,7 +204,7 @@ const CellComponent = (
const code = prepareToRunEffects();
- await sendRun([cellId], [code]).catch((error) => {
+ await sendRun({ cellIds: [cellId], codes: [code] }).catch((error) => {
Logger.error("Error running cell", error);
});
});
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index dfcff9d2bc..30223ac770 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -336,7 +336,7 @@ const CellEditorInternal = ({
const showCode = async () => {
if (hidden) {
- await saveCellConfig({ configs: { [cellId]: { hide_code: false } } });
+ await saveCellConfig({ configs: { [cellId]: { hideCode: false } } });
updateCellConfig({ cellId, config: { hide_code: false } });
// Focus on the editor view
editorViewRef.current?.focus();
diff --git a/frontend/src/components/editor/cell/useDeleteCell.tsx b/frontend/src/components/editor/cell/useDeleteCell.tsx
index 550475ce0d..bdd7354728 100644
--- a/frontend/src/components/editor/cell/useDeleteCell.tsx
+++ b/frontend/src/components/editor/cell/useDeleteCell.tsx
@@ -19,7 +19,7 @@ export function useDeleteCellCallback() {
const { cellId } = opts;
// Optimistic update
deleteCell({ cellId });
- sendDeleteCell(cellId).catch(() => {
+ sendDeleteCell({ cellId: cellId }).catch(() => {
// Fall back on failure
undoDeleteCell();
});
diff --git a/frontend/src/components/editor/cell/useRunCells.ts b/frontend/src/components/editor/cell/useRunCells.ts
index 76cc964ae7..9741ae65af 100644
--- a/frontend/src/components/editor/cell/useRunCells.ts
+++ b/frontend/src/components/editor/cell/useRunCells.ts
@@ -51,7 +51,7 @@ function useRunCells() {
ref.registerRun();
}
- await sendRun(cellIds, codes).catch((error) => {
+ await sendRun({ cellIds: cellIds, codes: codes }).catch((error) => {
Logger.error(error);
});
});
diff --git a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
index 424428b724..3d4de0ca38 100644
--- a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
@@ -6,7 +6,6 @@ import {
PlusSquareIcon,
XIcon,
} from "lucide-react";
-import type { DataTable, DataTableColumn } from "@/core/network/types";
import { Command, CommandInput, CommandItem } from "@/components/ui/command";
import { CommandList } from "cmdk";
@@ -32,7 +31,11 @@ import {
maybeAddMarimoImport,
} from "@/core/cells/add-missing-import";
import { autoInstantiateAtom } from "@/core/config/config";
-import { DataColumnPreview } from "@/core/kernel/messages";
+import {
+ DataColumnPreview,
+ DataTable,
+ DataTableColumn,
+} from "@/core/kernel/messages";
export const DataSourcesPanel: React.FC = () => {
const [searchValue, setSearchValue] = React.useState<string>("");
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index 05e58e030f..1fae8464b2 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -51,6 +51,7 @@ import { useAsyncData } from "@/hooks/useAsyncData";
import { ErrorBanner } from "@/plugins/impl/common/error-banner";
import { Spinner } from "@/components/icons/spinner";
import type { RequestingTree } from "./requesting-tree";
+import { FilePath } from "@/utils/paths";
const RequestingTreeContext = React.createContext<RequestingTree | null>(null);
@@ -249,7 +250,9 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
const handleOpenMarimoFile = async (evt: Event) => {
evt.stopPropagation();
evt.preventDefault();
- const path = tree ? tree.relativeFromRoot(node.data.path) : node.data.path;
+ const path = tree
+ ? tree.relativeFromRoot(node.data.path as FilePath)
+ : node.data.path;
window.open(`/?file=${path}`, "_blank");
};
diff --git a/frontend/src/components/editor/file-tree/requesting-tree.tsx b/frontend/src/components/editor/file-tree/requesting-tree.tsx
index 49482a925f..9f3eb96ff1 100644
--- a/frontend/src/components/editor/file-tree/requesting-tree.tsx
+++ b/frontend/src/components/editor/file-tree/requesting-tree.tsx
@@ -6,7 +6,7 @@ import type {
sendDeleteFileOrFolder,
sendRenameFileOrFolder,
} from "@/core/network/requests";
-import { FileInfo, FileOperationResponse } from "@/core/network/types";
+import { FileInfo, FileUpdateResponse } from "@/core/network/types";
import { prettyError } from "@/utils/errors";
import { Functions } from "@/utils/functions";
import { FilePath, PathBuilder } from "@/utils/paths";
@@ -34,7 +34,7 @@ export class RequestingTree {
try {
const data = await this.callbacks.listFiles({ path: this.rootPath });
this.delegate = new SimpleTree(data.files);
- this.rootPath = data.root;
+ this.rootPath = data.root as FilePath;
this.path = PathBuilder.guessDeliminator(data.root);
} catch (error) {
toast({
@@ -74,7 +74,7 @@ export class RequestingTree {
if (!node) {
return;
}
- const currentPath = node.data.path;
+ const currentPath = node.data.path as FilePath;
const newPath = this.path.join(this.path.dirname(currentPath), name);
await this.callbacks
.renameFileOrFolder({
@@ -100,7 +100,7 @@ export class RequestingTree {
}
const newPath = this.path.join(
parentPath,
- this.path.basename(node.data.path),
+ this.path.basename(node.data.path as FilePath),
);
this.delegate.update({ id, changes: { path: newPath } });
return this.callbacks
@@ -167,7 +167,7 @@ export class RequestingTree {
return path;
};
- private handleResponse = (response: FileOperationResponse): void => {
+ private handleResponse = (response: FileUpdateResponse): void => {
if (!response.success) {
toast({
title: "Failed",
diff --git a/frontend/src/components/editor/package-alert.tsx b/frontend/src/components/editor/package-alert.tsx
index 7bae0454b1..1247edd62e 100644
--- a/frontend/src/components/editor/package-alert.tsx
+++ b/frontend/src/components/editor/package-alert.tsx
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { zodResolver } from "@hookform/resolvers/zod";
-import { DefaultValues, useForm } from "react-hook-form";
+import { useForm } from "react-hook-form";
import {
Form,
FormControl,
@@ -276,7 +276,7 @@ export const PackageManagerForm: React.FC = () => {
// Create form
const form = useForm<UserConfig>({
resolver: zodResolver(UserConfigSchema),
- defaultValues: config as DefaultValues<UserConfig>,
+ defaultValues: config,
});
const onSubmit = async (values: UserConfig) => {
diff --git a/frontend/src/components/pages/home-page.tsx b/frontend/src/components/pages/home-page.tsx
index 4c11337ec7..fcd7eb3c9b 100644
--- a/frontend/src/components/pages/home-page.tsx
+++ b/frontend/src/components/pages/home-page.tsx
@@ -24,7 +24,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 { RunningNotebooksResponse } from "@/core/network/types";
+import { WorkspaceFilesResponse } from "@/core/network/types";
import { ConfigButton } from "../app-config/app-config-button";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
@@ -40,7 +40,7 @@ const HomePage: React.FC = () => {
const fileResponse = useAsyncData(async () => {
const [workspace, recents] = await Promise.all([
- getWorkspaceFiles({ includeMarkdown }),
+ getWorkspaceFiles({ includeMarkdown: includeMarkdown }),
getRecentFiles(),
]);
return { workspace, recents };
@@ -78,7 +78,7 @@ const HomePage: React.FC = () => {
[
file.path,
{
- sessionId: file.sessionId,
+ sessionId: file.sessionId as SessionId,
initializationId: file.initializationId,
},
],
@@ -143,8 +143,8 @@ const NotebookList: React.FC<{
files: Array<{
name: string;
path: string;
- sessionId?: string;
- initializationId?: string;
+ sessionId?: string | null;
+ initializationId?: string | null;
}>;
runningNotebooks: Map<
string,
@@ -153,7 +153,7 @@ const NotebookList: React.FC<{
initializationId: string;
}
>;
- setRunningNotebooks: (data: RunningNotebooksResponse) => void;
+ setRunningNotebooks: (data: WorkspaceFilesResponse) => void;
}> = ({ control, header, files, runningNotebooks, setRunningNotebooks }) => {
const { openConfirm, closeModal } = useImperativeModal();
diff --git a/frontend/src/core/cells/add-missing-import.ts b/frontend/src/core/cells/add-missing-import.ts
index 64487d5d11..57d1f9c7df 100644
--- a/frontend/src/core/cells/add-missing-import.ts
+++ b/frontend/src/core/cells/add-missing-import.ts
@@ -57,7 +57,7 @@ export function maybeAddMarimoImport(
autoFocus: false,
});
if (autoRun) {
- void sendRun([newCellId], [importStatement]);
+ void sendRun({ cellIds: [newCellId], codes: [importStatement] });
}
});
}
@@ -78,7 +78,7 @@ export function maybeAddAltairImport(
autoFocus: false,
});
if (autoRun) {
- void sendRun([newCellId], [importStatement]);
+ void sendRun({ cellIds: [newCellId], codes: [importStatement] });
}
});
}
diff --git a/frontend/src/core/codemirror/format.ts b/frontend/src/core/codemirror/format.ts
index c83c4a9993..099a1180e8 100644
--- a/frontend/src/core/codemirror/format.ts
+++ b/frontend/src/core/codemirror/format.ts
@@ -36,7 +36,10 @@ export async function formatEditorViews(
lineLength: getUserConfig().formatting.line_length,
});
- for (const [cellId, formattedCode] of Objects.entries(formatResponse)) {
+ for (const [_cellId, formattedCode] of Objects.entries(
+ formatResponse.codes,
+ )) {
+ const cellId = _cellId as CellId;
const originalCode = codes[cellId];
const view = views[cellId];
diff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.ts
index 0caa6a0e24..af1b7f663a 100644
--- a/frontend/src/core/config/__tests__/config-schema.test.ts
+++ b/frontend/src/core/config/__tests__/config-schema.test.ts
@@ -60,6 +60,7 @@ test("default UserConfig - empty", () => {
"autosave_delay": 1000,
"format_on_save": false,
},
+ "server": {},
}
`);
});
@@ -108,6 +109,7 @@ test("default UserConfig - one level", () => {
"autosave_delay": 1000,
"format_on_save": false,
},
+ "server": {},
}
`);
diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.ts
index 92c1a76ff1..f0c4982f4a 100644
--- a/frontend/src/core/config/config-schema.ts
+++ b/frontend/src/core/config/config-schema.ts
@@ -2,6 +2,7 @@
import { z } from "zod";
import { Logger } from "@/utils/Logger";
import { getMarimoAppConfig, getMarimoUserConfig } from "../dom/marimo-tag";
+import { MarimoConfig } from "../network/types";
// This has to be defined in the same file as the zod schema to satisfy zod
export const PackageManagerNames = [
@@ -100,6 +101,7 @@ export const UserConfigSchema = z
// Pass through so that we don't remove any extra keys that the user has added.
.passthrough()
.default({}),
+ server: z.object({}).passthrough().default({}),
})
// Pass through so that we don't remove any extra keys that the user has added
.passthrough()
@@ -111,8 +113,9 @@ export const UserConfigSchema = z
runtime: {},
display: {},
experimental: {},
+ server: {},
});
-export type UserConfig = z.infer<typeof UserConfigSchema>;
+export type UserConfig = MarimoConfig;
export type SaveConfig = UserConfig["save"];
export type CompletionConfig = UserConfig["completion"];
export type KeymapConfig = UserConfig["keymap"];
@@ -157,7 +160,7 @@ export function parseUserConfig(): UserConfig {
Logger.log(`🧪 Experimental feature "${key}" is enabled.`);
}
}
- return parsed;
+ return parsed as UserConfig;
} catch (error) {
Logger.error(
`Marimo got an unexpected value in the configuration file: ${error}`,
@@ -167,5 +170,5 @@ export function parseUserConfig(): UserConfig {
}
export function defaultUserConfig(): UserConfig {
- return UserConfigSchema.parse({});
+ return UserConfigSchema.parse({}) as UserConfig;
}
diff --git a/frontend/src/core/config/feature-flag.ts b/frontend/src/core/config/feature-flag.ts
index b06c23f083..80aaf0cbf1 100644
--- a/frontend/src/core/config/feature-flag.ts
+++ b/frontend/src/core/config/feature-flag.ts
@@ -18,7 +18,10 @@ const defaultValues: ExperimentalFeatures = {
export function getFeatureFlag<T extends keyof ExperimentalFeatures>(
feature: T,
): ExperimentalFeatures[T] {
- return getUserConfig().experimental?.[feature] ?? defaultValues[feature];
+ return (
+ (getUserConfig().experimental?.[feature] as ExperimentalFeatures[T]) ??
+ defaultValues[feature]
+ );
}
function setFeatureFlag(
diff --git a/frontend/src/core/datasets/types.ts b/frontend/src/core/datasets/types.ts
index 9179a94602..bb683cc79f 100644
--- a/frontend/src/core/datasets/types.ts
+++ b/frontend/src/core/datasets/types.ts
@@ -1,6 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import type { DataTable } from "../network/types";
-import { DataColumnPreview } from "../kernel/messages";
+import { DataColumnPreview, DataTable } from "../kernel/messages";
/**
* A qualified column name, e.g. `table:column`.
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index 591e00388c..b189950cb4 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -101,7 +101,7 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
sessionId: getSessionId(),
});
- const handleFilenameChange = useEvent(async (name: string | null) => {
+ const handleFilenameChange = useEvent(async (name: string) => {
if (connection.state !== WebSocketState.OPEN) {
alertSaveFailed();
return null;
@@ -115,7 +115,7 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
}
});
- return sendRename(name)
+ return sendRename({ filename: name })
.then(() => {
setFilename(name);
// Set document title: app_title takes precedence, then filename, then default
diff --git a/frontend/src/core/functions/FunctionRegistry.ts b/frontend/src/core/functions/FunctionRegistry.ts
index 97de03ddc6..9490d125a8 100644
--- a/frontend/src/core/functions/FunctionRegistry.ts
+++ b/frontend/src/core/functions/FunctionRegistry.ts
@@ -3,10 +3,10 @@
import { sendFunctionRequest } from "@/core/network/requests";
import type { FunctionCallResultMessage } from "../kernel/messages";
import { DeferredRequestRegistry } from "../network/DeferredRequestRegistry";
-import type { SendFunctionRequest } from "../network/types";
+import type { FunctionCallRequest } from "../network/types";
export const FUNCTIONS_REGISTRY = new DeferredRequestRegistry<
- Omit<SendFunctionRequest, "functionCallId">,
+ Omit<FunctionCallRequest, "functionCallId">,
FunctionCallResultMessage
>("function-call-result", async (requestId, req) => {
// RPC counts as a kernel invocation
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index 99033babc4..c7d9e69c5d 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -1,18 +1,11 @@
/* Copyright 2024 Marimo. All rights reserved. */
/* eslint-disable @typescript-eslint/no-explicit-any */
-import {
- EditRequests,
- InstantiateRequest,
- RunRequests,
- SendFunctionRequest,
- ValueUpdate,
-} from "../network/types";
+import { EditRequests, RunRequests } from "../network/types";
import { Deferred } from "@/utils/Deferred";
import { getMarimoVersion } from "../dom/marimo-tag";
import { getWorkerRPC } from "@/core/pyodide/rpc";
import { OperationMessage } from "../kernel/messages";
import { JsonString } from "@/utils/json/base64";
-import { CellId } from "@/core/cells/ids";
import { throwNotImplemented } from "@/utils/functions";
import type { WorkerSchema } from "./worker/worker";
import workerUrl from "./worker/worker.tsx?worker&url";
@@ -103,31 +96,29 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
this.rpc.proxy.send.consumerReady({});
}
- sendComponentValues = async (valueUpdates: ValueUpdate[]): Promise<null> => {
- await this.putControlRequest({
- ids_and_values: valueUpdates.map((update) => [
- update.objectId,
- update.value,
- ]),
- });
+ sendComponentValues: RunRequests["sendComponentValues"] = async (
+ request,
+ ): Promise<null> => {
+ await this.putControlRequest(request);
return null;
};
- sendInstantiate = async (request: InstantiateRequest): Promise<null> => {
+
+ sendInstantiate: RunRequests["sendInstantiate"] = async (
+ request,
+ ): Promise<null> => {
return null;
};
- sendFunctionRequest = async (request: SendFunctionRequest): Promise<null> => {
+
+ sendFunctionRequest: RunRequests["sendFunctionRequest"] = async (
+ request,
+ ): Promise<null> => {
await this.putControlRequest(request);
return null;
};
- sendRun = async (cellIds: CellId[], codes: string[]): Promise<null> => {
- await this.rpc.proxy.request.loadPackages(codes.join("\n"));
-
- await this.putControlRequest({
- execution_requests: cellIds.map((cellId, index) => ({
- cell_id: cellId,
- code: codes[index],
- })),
- });
+
+ sendRun: EditRequests["sendRun"] = async (request): Promise<null> => {
+ await this.rpc.proxy.request.loadPackages(request.codes.join("\n"));
+ await this.putControlRequest(request);
return null;
};
diff --git a/frontend/src/core/islands/components/output-wrapper.tsx b/frontend/src/core/islands/components/output-wrapper.tsx
index 12f5f08efe..3a297e4fa0 100644
--- a/frontend/src/core/islands/components/output-wrapper.tsx
+++ b/frontend/src/core/islands/components/output-wrapper.tsx
@@ -110,7 +110,10 @@ export const MarimoOutputWrapper: React.FC<Props> = ({
tooltip="Re-run cell"
icon={<PlayIcon className="size-3" />}
action={async () => {
- await sendRun([cellId], [codeCallback()]).catch((error) => {
+ await sendRun({
+ cellIds: [cellId],
+ codes: [codeCallback()],
+ }).catch((error) => {
Logger.error(error);
});
}}
diff --git a/frontend/src/core/kernel/RuntimeState.ts b/frontend/src/core/kernel/RuntimeState.ts
index 756307dc95..00e444c27d 100644
--- a/frontend/src/core/kernel/RuntimeState.ts
+++ b/frontend/src/core/kernel/RuntimeState.ts
@@ -56,7 +56,10 @@ export class RuntimeState {
const value = this.uiElementRegistry.lookupValue(objectId);
if (value !== undefined) {
- this.sendComponentValues([{ objectId: objectId, value: value }]).catch(
+ this.sendComponentValues({
+ objectIds: [objectId],
+ values: [value],
+ }).catch(
// This happens if the run failed to register (401, 403, network
// error, etc.) A run may fail if the kernel is restarted or the
// notebook is closed.
diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.ts
index 71f28d6108..2b3c117707 100644
--- a/frontend/src/core/kernel/handlers.ts
+++ b/frontend/src/core/kernel/handlers.ts
@@ -102,7 +102,7 @@ export function handleKernelReady(
// Send the instantiate message
if (autoInstantiate) {
// Start the run
- sendInstantiate({ objectIds, values }).catch((error) => {
+ sendInstantiate({ objectIds: objectIds, values }).catch((error) => {
onError(new Error("Failed to instantiate", { cause: error }));
});
}
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index 6c99837039..c81e3db765 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -7,10 +7,26 @@ import type { VariableName } from "../variables/types";
import type { RequestId } from "../network/DeferredRequestRegistry";
import type { Seconds } from "@/utils/time";
import type { AppConfig } from "../config/config-schema";
-import type { DataTable } from "../network/types";
import type { ColumnPreviewSummary } from "../datasets/types";
import type { JsonString } from "@/utils/json/base64";
+export interface DataTableColumn {
+ name: string;
+ type: "string" | "boolean" | "integer" | "number" | "date" | "unknown";
+}
+
+export interface DataTable {
+ name: string;
+ source: string;
+ /**
+ * The variable name if this is a variable in the notebook.
+ */
+ variable_name: VariableName | null;
+ num_rows: number;
+ num_columns: number;
+ columns: DataTableColumn[];
+}
+
export type OutputChannel =
| "output"
| "media"
diff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.ts
index 36c9798dad..6385fabba9 100644
--- a/frontend/src/core/network/api.ts
+++ b/frontend/src/core/network/api.ts
@@ -3,6 +3,7 @@ import { once } from "@/utils/once";
import { Logger } from "../../utils/Logger";
import { getMarimoServerToken } from "../dom/marimo-tag";
import { getSessionId } from "../kernel/session";
+import { createMarimoClient } from "@marimo-team/marimo-api";
const getServerTokenOnce = once(() => {
return getMarimoServerToken();
@@ -92,4 +93,37 @@ export const API = {
"Marimo-Server-Token": getServerTokenOnce(),
};
},
+ handleResponse: <T>(response: {
+ data?: T | undefined;
+ error?: Error;
+ response: Response;
+ }): Promise<T> => {
+ if (response.error) {
+ return Promise.reject(response.error);
+ }
+ return Promise.resolve(response.data as T);
+ },
+ handleResponseReturnNull: (response: {
+ error?: Error;
+ response: Response;
+ }): Promise<null> => {
+ if (response.error) {
+ return Promise.reject(response.error);
+ }
+ return Promise.resolve(null);
+ },
};
+
+export const marimoClient = createMarimoClient({
+ // eslint-disable-next-line ssr-friendly/no-dom-globals-in-module-scope
+ baseUrl: typeof document === "undefined" ? undefined : document.baseURI,
+});
+
+marimoClient.use({
+ onRequest: (req) => {
+ for (const [key, value] of Object.entries(API.headers())) {
+ req.headers.set(key, value);
+ }
+ return req;
+ },
+});
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index fb3fb58fe0..0d711cb158 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -1,241 +1,239 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import type { CellId } from "../cells/ids";
-import { API } from "./api";
-import type {
- CodeCompletionRequest,
- DeleteRequest,
- FormatResponse,
- FormatRequest,
- InstantiateRequest,
- RenameRequest,
- RunRequest,
- SaveKernelRequest,
- SetComponentValuesRequest,
- SaveUserConfigRequest,
- SaveAppConfigRequest,
- SaveCellConfigRequest,
- SendFunctionRequest,
- RunRequests,
- EditRequests,
- SendStdin,
- SendInstallMissingPackages,
- FileListResponse,
- FileCreateRequest,
- FileOperationResponse,
- FileDeleteRequest,
- FileUpdateRequest,
- FileDetailsResponse,
- FileMoveRequest,
- SnippetsResponse,
- RecentFilesResponse,
- WorkspaceFilesResponse,
- RunningNotebooksResponse,
- ShutdownSessionRequest,
- ExportAsHTMLRequest,
- UsageResponse,
- ExportAsMarkdownRequest,
- WorkspaceFilesRequest,
- PreviewDatasetColumnRequest,
-} from "./types";
-import { invariant } from "@/utils/invariant";
+import { API, marimoClient } from "./api";
+import type { RunRequests, EditRequests } from "./types";
+
+const { handleResponse, handleResponseReturnNull } = API;
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,
- },
- );
+ sendComponentValues: (request) => {
+ return marimoClient
+ .POST("/api/kernel/set_ui_element_value", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
},
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);
+ return marimoClient
+ .POST("/api/kernel/restart_session")
+ .then(handleResponseReturnNull);
+ },
+ sendRename: (request) => {
+ return marimoClient
+ .POST("/api/kernel/rename", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
+ },
+ sendSave: (request) => {
+ return marimoClient
+ .POST("/api/kernel/save", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
+ },
+ sendFormat: (request) => {
+ return marimoClient
+ .POST("/api/kernel/format", {
+ body: request,
+ })
+ .then(handleResponse);
},
sendInterrupt: () => {
- return API.post("/kernel/interrupt", {});
+ return marimoClient
+ .POST("/api/kernel/interrupt")
+ .then(handleResponseReturnNull);
},
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,
- });
+ return marimoClient
+ .POST("/api/kernel/shutdown")
+ .then(handleResponseReturnNull);
+ },
+ sendRun: (request) => {
+ return marimoClient
+ .POST("/api/kernel/run", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
+ },
+ sendInstantiate: (request) => {
+ return marimoClient
+ .POST("/api/kernel/instantiate", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
+ },
+ sendDeleteCell: (request) => {
+ return marimoClient
+ .POST("/api/kernel/delete", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
},
sendCodeCompletionRequest: (request) => {
- return API.post<CodeCompletionRequest>(
- "/kernel/code_autocomplete",
- request,
- );
+ return marimoClient
+ .POST("/api/kernel/code_autocomplete", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
},
saveUserConfig: (request) => {
- return API.post<SaveUserConfigRequest>(
- "/kernel/save_user_config",
- request,
- );
+ return marimoClient
+ .POST("/api/kernel/save_user_config", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
},
saveAppConfig: (request) => {
- return API.post<SaveAppConfigRequest>("/kernel/save_app_config", request);
+ return marimoClient
+ .POST("/api/kernel/save_app_config", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
},
saveCellConfig: (request) => {
- return API.post<SaveCellConfigRequest>(
- "/kernel/set_cell_config",
- request,
- );
+ return marimoClient
+ .POST("/api/kernel/set_cell_config", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
},
sendFunctionRequest: (request) => {
- return API.post<SendFunctionRequest>("/kernel/function_call", request);
+ return marimoClient
+ .POST("/api/kernel/function_call", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
},
sendStdin: (request) => {
- return API.post<SendStdin>("/kernel/stdin", request);
+ return marimoClient
+ .POST("/api/kernel/stdin", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
},
sendInstallMissingPackages: (request) => {
- return API.post<SendInstallMissingPackages>(
- "/kernel/install_missing_packages",
- request,
- );
+ return marimoClient
+ .POST("/api/kernel/install_missing_packages", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
},
readCode: () => {
- return API.post<{}, { contents: string }>("/kernel/read_code", {});
+ return marimoClient.POST("/api/kernel/read_code").then(handleResponse);
},
readSnippets: () => {
- return API.get<SnippetsResponse>("/documentation/snippets", {});
+ return marimoClient
+ .GET("/api/documentation/snippets")
+ .then(handleResponse);
},
- previewDatasetColumn: (request: PreviewDatasetColumnRequest) => {
- return API.post<PreviewDatasetColumnRequest>(
- "/datasources/preview_column",
- request,
- );
+ previewDatasetColumn: (request) => {
+ return marimoClient
+ .POST("/api/datasources/preview_column", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
},
openFile: async (request) => {
- await API.post<{ path: string }>("/kernel/open", request);
- await API.post("/kernel/restart_session", {});
+ await marimoClient
+ .POST("/api/kernel/open", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
+ await marimoClient
+ .POST("/api/kernel/restart_session")
+ .then(handleResponseReturnNull);
window.location.reload();
return null;
},
getUsageStats: () => {
- return API.get<UsageResponse>("/usage", {});
+ return marimoClient.GET("/api/usage").then(handleResponse);
},
sendListFiles: (request) => {
- return API.post<{ path: string | undefined }, FileListResponse>(
- "/files/list_files",
- request,
- );
+ return marimoClient
+ .POST("/api/files/list_files", {
+ body: request,
+ })
+ .then(handleResponse);
},
sendCreateFileOrFolder: (request) => {
- return API.post<FileCreateRequest, FileOperationResponse>(
- "/files/create",
- request,
- );
+ return marimoClient
+ .POST("/api/files/create", {
+ body: request,
+ })
+ .then(handleResponse);
},
sendDeleteFileOrFolder: (request) => {
- return API.post<FileDeleteRequest, FileOperationResponse>(
- "/files/delete",
- request,
- );
+ return marimoClient
+ .POST("/api/files/delete", {
+ body: request,
+ })
+ .then(handleResponse);
},
sendRenameFileOrFolder: (request) => {
- return API.post<FileMoveRequest, FileOperationResponse>(
- "/files/move",
- request,
- );
+ return marimoClient
+ .POST("/api/files/move", {
+ body: request,
+ })
+ .then(handleResponse);
},
sendUpdateFile: (request) => {
- return API.post<FileUpdateRequest, FileOperationResponse>(
- "/files/update",
- request,
- );
- },
- sendFileDetails: (request: { path: string }) => {
- return API.post<{ path: string }, FileDetailsResponse>(
- "/files/file_details",
- request,
- );
+ return marimoClient
+ .POST("/api/files/update", {
+ body: request,
+ })
+ .then(handleResponse);
+ },
+ sendFileDetails: (request) => {
+ return marimoClient
+ .POST("/api/files/file_details", {
+ body: request,
+ })
+ .then(handleResponse);
},
getRecentFiles: () => {
- return API.post<{}, RecentFilesResponse>("/home/recent_files", {});
+ return marimoClient.POST("/api/home/recent_files").then(handleResponse);
},
getWorkspaceFiles: (request) => {
- return API.post<WorkspaceFilesRequest, WorkspaceFilesResponse>(
- "/home/workspace_files",
- request,
- );
+ return marimoClient
+ .POST("/api/home/workspace_files", {
+ body: request,
+ })
+ .then(handleResponse);
},
getRunningNotebooks: () => {
- return API.post<{}, RunningNotebooksResponse>(
- "/home/running_notebooks",
- {},
- );
- },
- shutdownSession: (request: ShutdownSessionRequest) => {
- return API.post("/home/shutdown_session", request);
- },
- exportAsHTML: async (request: ExportAsHTMLRequest) => {
+ return marimoClient
+ .POST("/api/home/running_notebooks")
+ .then(handleResponse);
+ },
+ shutdownSession: (request) => {
+ return marimoClient
+ .POST("/api/home/shutdown_session", {
+ body: request,
+ })
+ .then(handleResponse);
+ },
+ exportAsHTML: async (request) => {
if (
process.env.NODE_ENV === "development" ||
process.env.NODE_ENV === "test"
) {
request.assetUrl = window.location.origin;
}
- return API.post("/export/html", request);
- },
- exportAsMarkdown: async (request: ExportAsMarkdownRequest) => {
- return API.post("/export/markdown", request);
+ return marimoClient
+ .POST("/api/export/html", {
+ body: request,
+ parseAs: "text",
+ })
+ .then(handleResponse);
+ },
+ exportAsMarkdown: async (request) => {
+ return marimoClient
+ .POST("/api/export/markdown", {
+ body: request,
+ parseAs: "text",
+ })
+ .then(handleResponse);
},
};
}
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index 0a4be3a0e1..fd61bf3869 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -1,11 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { toast } from "@/components/ui/use-toast";
-import {
- EditRequests,
- InstantiateRequest,
- RunRequests,
- SendFunctionRequest,
-} from "./types";
+import { EditRequests, RunRequests } from "./types";
import { Logger } from "@/utils/Logger";
export function createStaticRequests(): EditRequests & RunRequests {
@@ -14,7 +9,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
};
return {
- sendComponentValues: async (valueUpdates) => {
+ sendComponentValues: async () => {
toast({
title: "Static notebook",
description:
@@ -23,11 +18,11 @@ export function createStaticRequests(): EditRequests & RunRequests {
Logger.log("Updating UI elements is not supported in static mode");
return null;
},
- sendInstantiate: async (request: InstantiateRequest) => {
+ sendInstantiate: async () => {
Logger.log("Viewing as static notebook");
return null;
},
- sendFunctionRequest: async (request: SendFunctionRequest) => {
+ sendFunctionRequest: async () => {
toast({
title: "Static notebook",
description:
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index a96ef9db45..2ecc039fcc 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -1,284 +1,102 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import type { AppConfig, UserConfig } from "../config/config-schema";
-import type { LayoutType } from "@/components/editor/renderers/types";
-import type { CellId } from "../cells/ids";
-import type { CellConfig } from "../cells/types";
-import type { RequestId } from "./DeferredRequestRegistry";
-import type { FilePath } from "@/utils/paths";
-import type { PackageManagerName } from "../config/config-schema";
-import type { SessionId } from "@/core/kernel/session";
-import { VariableName } from "../variables/types";
-
-// Ideally this would be generated from server.py, but for now we just
-// manually keep them in sync.
-
-export interface DeleteRequest {
- cellId: CellId;
-}
-
-export interface InstantiateRequest {
- objectIds: string[];
- values: unknown[];
-}
-
-export interface FormatRequest {
- /**
- * mapping of cell ids to code
- */
- codes: Record<CellId, string>;
- /**
- * line-length
- */
- lineLength: number;
-}
-
-export interface FormatResponse {
- /**
- * mapping of formatted cell ids to code
- * response keys are a subset of request keys
- */
- codes: Record<CellId, string>;
-}
-
-export interface RenameRequest {
- filename: string | null;
-}
-
-export interface RunRequest {
- cellIds: CellId[];
- codes: string[];
-}
-
-export interface SaveKernelRequest {
- cellIds: CellId[];
- filename: string;
- codes: string[];
- names: string[];
- layout:
- | {
- type: LayoutType;
- data: unknown;
- }
- | undefined;
- configs: CellConfig[];
-}
-
-export interface SetComponentValuesRequest {
- objectIds: string[];
- values: unknown[];
-}
-
-export interface CodeCompletionRequest {
- id: RequestId;
- document: string;
- cellId: CellId;
-}
-
-export interface SaveUserConfigRequest {
- config: UserConfig;
-}
-
-export interface SaveAppConfigRequest {
- config: AppConfig;
-}
-
-export interface SaveCellConfigRequest {
+import { paths, type components } from "@marimo-team/marimo-api";
+import { CellId } from "../cells/ids";
+
+export type schemas = components["schemas"];
+export type AiCompletionRequest = schemas["AiCompletionRequest"];
+export type AppMetadata = schemas["AppMetadata"];
+export type BaseResponse = schemas["BaseResponse"];
+export type CellConfig = schemas["CellConfig"];
+export type CodeCompletionRequest = schemas["CodeCompletionRequest"];
+export type CreationRequest = schemas["CreationRequest"];
+export type DeleteRequest = schemas["DeleteRequest"];
+export type ExecuteMultipleRequest = schemas["ExecuteMultipleRequest"];
+export type ExecutionRequest = schemas["ExecutionRequest"];
+export type ExportAsHTMLRequest = schemas["ExportAsHTMLRequest"];
+export type ExportAsMarkdownRequest = schemas["ExportAsMarkdownRequest"];
+export type ExportAsScriptRequest = schemas["ExportAsScriptRequest"];
+export type FileCreateRequest = schemas["FileCreateRequest"];
+export type FileCreateResponse = schemas["FileCreateResponse"];
+export type FileDeleteRequest = schemas["FileDeleteRequest"];
+export type FileDeleteResponse = schemas["FileDeleteResponse"];
+export type FileDetailsRequest = schemas["FileDetailsRequest"];
+export type FileDetailsResponse = schemas["FileDetailsResponse"];
+export type FileInfo = schemas["FileInfo"];
+export type FileListRequest = schemas["FileListRequest"];
+export type FileListResponse = schemas["FileListResponse"];
+export type FileMoveRequest = schemas["FileMoveRequest"];
+export type FileMoveResponse = schemas["FileMoveResponse"];
+export type FileUpdateRequest = schemas["FileUpdateRequest"];
+export type FileUpdateResponse = schemas["FileUpdateResponse"];
+export type FormatRequest = schemas["FormatRequest"];
+export type FormatResponse = schemas["FormatResponse"];
+export type FunctionCallRequest = schemas["FunctionCallRequest"];
+export type InstallMissingPackagesRequest =
+ schemas["InstallMissingPackagesRequest"];
+export type InstantiateRequest = schemas["InstantiateRequest"];
+export type MarimoConfig = schemas["MarimoConfig"];
+export type MarimoFile = schemas["MarimoFile"];
+export type OpenFileRequest = schemas["OpenFileRequest"];
+export type PreviewDatasetColumnRequest =
+ schemas["PreviewDatasetColumnRequest"];
+export type ReadCodeResponse = schemas["ReadCodeResponse"];
+export type RecentFilesResponse = schemas["RecentFilesResponse"];
+export type RenameFileRequest = schemas["RenameFileRequest"];
+export type RunRequest = schemas["RunRequest"];
+export type SaveAppConfigurationRequest =
+ schemas["SaveAppConfigurationRequest"];
+export type SaveNotebookRequest = schemas["SaveNotebookRequest"];
+export type SaveUserConfigurationRequest =
+ schemas["SaveUserConfigurationRequest"];
+export interface SetCellConfigRequest {
configs: Record<CellId, CellConfig>;
}
-
-export interface SendFunctionRequest {
- functionCallId: RequestId;
- args: unknown;
- namespace: string;
- functionName: string;
-}
-
-export interface SendStdin {
- text: string;
-}
-
-// In the future may include things like package manager, index URL, ...
-export interface SendInstallMissingPackages {
- manager: PackageManagerName;
-}
-
-export interface ValueUpdate {
- objectId: string;
- value: unknown;
-}
-
-export interface FileInfo {
- id: string;
- path: FilePath;
- name: string;
- lastModified?: number;
- isDirectory: boolean;
- isMarimoFile: boolean;
- children: FileInfo[];
-}
-
-export interface FileListRequest {
- path: FilePath | undefined;
-}
-
-export interface FileListResponse {
- files: FileInfo[];
- root: FilePath;
-}
-
-export interface FileCreateRequest {
- path: FilePath;
- type: "file" | "directory";
- name: string;
- // base64 representation of contents
- contents: string | undefined;
-}
-
-export interface FileDeleteRequest {
- path: FilePath;
-}
-
-export interface FileMoveRequest {
- path: FilePath;
- newPath: FilePath;
-}
-
-export interface FileUpdateRequest {
- path: FilePath;
- contents: string;
-}
-
-export interface FileOperationResponse {
- success: boolean;
- message: string | undefined;
- info: FileInfo | undefined;
-}
-
-export interface FileDetailsResponse {
- file: FileInfo;
- mimeType: string | undefined;
- contents: string | undefined;
-}
-
-export interface Snippet {
- title: string;
- sections: Array<{
- id: string;
- html?: string;
- code?: string;
- }>;
-}
-
-export interface SnippetsResponse {
- snippets: Snippet[];
-}
-
-export interface PreviewDatasetColumnRequest {
- source: string;
- tableName: string;
- columnName: string;
-}
-
-export interface DataTableColumn {
- name: string;
- type: "string" | "boolean" | "integer" | "number" | "date" | "unknown";
-}
-
-export interface DataTable {
- name: string;
- source: string;
- /**
- * The variable name if this is a variable in the notebook.
- */
- variable_name: VariableName | null;
- num_rows: number;
- num_columns: number;
- columns: DataTableColumn[];
-}
-
-interface MarimoNotebook {
- name: string;
- path: string;
- lastModified?: number;
- sessionId?: SessionId;
- initializationId?: string;
-}
-
-export interface RecentFilesResponse {
- files: MarimoNotebook[];
-}
-
-export interface WorkspaceFilesRequest {
- includeMarkdown: boolean;
-}
-
-export interface WorkspaceFilesResponse {
- files: MarimoNotebook[];
-}
-
-export interface RunningNotebooksResponse {
- files: MarimoNotebook[];
-}
-
-export interface ShutdownSessionRequest {
- sessionId: SessionId;
-}
-
-export interface ExportAsHTMLRequest {
- assetUrl?: string;
- includeCode: boolean;
- files: string[];
- download: boolean;
-}
-
-export interface ExportAsMarkdownRequest {
- download: boolean;
-}
-
-export interface UsageResponse {
- memory: {
- total: number;
- available: number;
- percent: number;
- used: number;
- free: number;
- };
- cpu: {
- percent: number;
- };
-}
+export type SetUIElementValueRequest = schemas["SetUIElementValueRequest"];
+export type SetUserConfigRequest = schemas["SetUserConfigRequest"];
+export type ShutdownSessionRequest = schemas["ShutdownSessionRequest"];
+export type Snippet = schemas["Snippet"];
+export type SnippetSection = schemas["SnippetSection"];
+export type Snippets = schemas["Snippets"];
+export type StdinRequest = schemas["StdinRequest"];
+export type SuccessResponse = schemas["SuccessResponse"];
+export type UpdateComponentValuesRequest =
+ schemas["UpdateComponentValuesRequest"];
+export type UsageResponse =
+ paths["/api/usage"]["get"]["responses"]["200"]["content"]["application/json"];
+export type WorkspaceFilesRequest = schemas["WorkspaceFilesRequest"];
+export type WorkspaceFilesResponse = schemas["WorkspaceFilesResponse"];
/**
* Requests sent to the BE during run/edit mode.
*/
export interface RunRequests {
- sendComponentValues: (valueUpdates: ValueUpdate[]) => Promise<null>;
+ sendComponentValues: (request: UpdateComponentValuesRequest) => Promise<null>;
sendInstantiate: (request: InstantiateRequest) => Promise<null>;
- sendFunctionRequest: (request: SendFunctionRequest) => Promise<null>;
+ sendFunctionRequest: (request: FunctionCallRequest) => Promise<null>;
}
/**
* Requests sent to the BE during edit mode.
*/
export interface EditRequests {
- sendRename: (filename: string | null) => Promise<null>;
- sendSave: (request: SaveKernelRequest) => Promise<null>;
- sendStdin: (request: SendStdin) => Promise<null>;
- sendRun: (cellIds: CellId[], codes: string[]) => Promise<null>;
+ sendRename: (request: RenameFileRequest) => Promise<null>;
+ sendSave: (request: SaveNotebookRequest) => Promise<null>;
+ sendStdin: (request: StdinRequest) => Promise<null>;
+ sendRun: (request: RunRequest) => Promise<null>;
sendInterrupt: () => Promise<null>;
sendShutdown: () => Promise<null>;
- sendFormat: (request: FormatRequest) => Promise<Record<CellId, string>>;
- sendDeleteCell: (cellId: CellId) => Promise<null>;
+ sendFormat: (request: FormatRequest) => Promise<FormatResponse>;
+ sendDeleteCell: (request: DeleteRequest) => Promise<null>;
sendCodeCompletionRequest: (request: CodeCompletionRequest) => Promise<null>;
- saveUserConfig: (request: SaveUserConfigRequest) => Promise<null>;
- saveAppConfig: (request: SaveAppConfigRequest) => Promise<null>;
- saveCellConfig: (request: SaveCellConfigRequest) => Promise<null>;
+ saveUserConfig: (request: SaveUserConfigurationRequest) => Promise<null>;
+ saveAppConfig: (request: SaveAppConfigurationRequest) => Promise<null>;
+ saveCellConfig: (request: SetCellConfigRequest) => Promise<null>;
sendRestart: () => Promise<null>;
sendInstallMissingPackages: (
- request: SendInstallMissingPackages,
+ request: InstallMissingPackagesRequest,
) => Promise<null>;
readCode: () => Promise<{ contents: string }>;
- readSnippets: () => Promise<SnippetsResponse>;
+ readSnippets: () => Promise<Snippets>;
previewDatasetColumn: (request: PreviewDatasetColumnRequest) => Promise<null>;
openFile: (request: { path: string }) => Promise<null>;
getUsageStats: () => Promise<UsageResponse>;
@@ -286,26 +104,24 @@ export interface EditRequests {
sendListFiles: (request: FileListRequest) => Promise<FileListResponse>;
sendCreateFileOrFolder: (
request: FileCreateRequest,
- ) => Promise<FileOperationResponse>;
+ ) => Promise<FileCreateResponse>;
sendDeleteFileOrFolder: (
request: FileDeleteRequest,
- ) => Promise<FileOperationResponse>;
+ ) => Promise<FileDeleteResponse>;
sendRenameFileOrFolder: (
request: FileMoveRequest,
- ) => Promise<FileOperationResponse>;
- sendUpdateFile: (
- request: FileUpdateRequest,
- ) => Promise<FileOperationResponse>;
+ ) => Promise<FileMoveResponse>;
+ sendUpdateFile: (request: FileUpdateRequest) => Promise<FileUpdateResponse>;
sendFileDetails: (request: { path: string }) => Promise<FileDetailsResponse>;
// Homepage requests
getRecentFiles: () => Promise<RecentFilesResponse>;
getWorkspaceFiles: (
request: WorkspaceFilesRequest,
) => Promise<WorkspaceFilesResponse>;
- getRunningNotebooks: () => Promise<RunningNotebooksResponse>;
+ getRunningNotebooks: () => Promise<WorkspaceFilesResponse>;
shutdownSession: (
request: ShutdownSessionRequest,
- ) => Promise<RunningNotebooksResponse>;
+ ) => Promise<WorkspaceFilesResponse>;
exportAsHTML: (request: ExportAsHTMLRequest) => Promise<string>;
exportAsMarkdown: (request: ExportAsMarkdownRequest) => Promise<string>;
}
diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.ts
index 1d5183973a..035886282e 100644
--- a/frontend/src/core/pyodide/bridge.ts
+++ b/frontend/src/core/pyodide/bridge.ts
@@ -1,33 +1,19 @@
/* Copyright 2024 Marimo. All rights reserved. */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Logger } from "@/utils/Logger";
-import type { CellId } from "../cells/ids";
import type {
- CodeCompletionRequest,
EditRequests,
ExportAsHTMLRequest,
ExportAsMarkdownRequest,
- FileCreateRequest,
- FileDeleteRequest,
+ FileCreateResponse,
+ FileDeleteResponse,
FileDetailsResponse,
- FileListRequest,
FileListResponse,
- FileMoveRequest,
- FileOperationResponse,
- FileUpdateRequest,
- FormatRequest,
+ FileMoveResponse,
+ FileUpdateResponse,
FormatResponse,
- InstantiateRequest,
RunRequests,
- SaveAppConfigRequest,
- SaveCellConfigRequest,
- SaveKernelRequest,
- SaveUserConfigRequest,
- SendFunctionRequest,
- SendInstallMissingPackages,
- SendStdin,
- SnippetsResponse,
- ValueUpdate,
+ Snippets,
} from "../network/types";
import type { IReconnectingWebSocket } from "../websocket/types";
import { fallbackFileStore, notebookFileStore } from "./store";
@@ -37,7 +23,7 @@ import { createShareableLink } from "./share";
import { PyodideRouter } from "./router";
import { getMarimoVersion } from "../dom/marimo-tag";
import { getWorkerRPC } from "./rpc";
-import { API } from "../network/api";
+import { API, marimoClient } from "../network/api";
import { parseUserConfig } from "../config/config-schema";
import { throwNotImplemented } from "@/utils/functions";
import type { WorkerSchema } from "./worker/worker";
@@ -48,6 +34,8 @@ import { store } from "../state/jotai";
import { notebookIsRunningAtom } from "../cells/cells";
import { getInitialAppMode } from "../mode";
+const { handleResponseReturnNull } = API;
+
export class PyodideBridge implements RunRequests, EditRequests {
static INSTANCE = new PyodideBridge();
@@ -167,7 +155,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
this.rpc.proxy.send.consumerReady({});
}
- sendRename = async (filename: string | null): Promise<null> => {
+ sendRename: EditRequests["sendRename"] = async ({ filename }) => {
if (filename === null) {
return null;
}
@@ -182,7 +170,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendSave = async (request: SaveKernelRequest): Promise<null> => {
+ sendSave: EditRequests["sendSave"] = async (request) => {
await this.saveRpc.proxy.request.saveNotebook(request);
const code = await this.readCode();
if (code.contents) {
@@ -192,7 +180,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendStdin = async (request: SendStdin): Promise<null> => {
+ sendStdin: EditRequests["sendStdin"] = async (request) => {
await this.rpc.proxy.request.bridge({
functionName: "put_input",
payload: request.text,
@@ -200,52 +188,44 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendRun = async (cellIds: CellId[], codes: string[]): Promise<null> => {
- await this.rpc.proxy.request.loadPackages(codes.join("\n"));
+ sendRun: EditRequests["sendRun"] = async (request) => {
+ await this.rpc.proxy.request.loadPackages(request.codes.join("\n"));
- await this.putControlRequest({
- execution_requests: cellIds.map((cellId, index) => ({
- cell_id: cellId,
- code: codes[index],
- })),
- });
+ await this.putControlRequest(request);
return null;
};
- sendInterrupt = async (): Promise<null> => {
+ sendInterrupt: EditRequests["sendInterrupt"] = async () => {
if (this.interruptBuffer !== undefined) {
// 2 sends a SIGINT
this.interruptBuffer[0] = 2;
}
return null;
};
- sendShutdown = async (): Promise<null> => {
+ sendShutdown: EditRequests["sendShutdown"] = async () => {
window.close();
return null;
};
- sendFormat = async (
- request: FormatRequest,
- ): Promise<Record<CellId, string>> => {
+ sendFormat: EditRequests["sendFormat"] = async (request) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "format",
payload: request,
});
- return (response as FormatResponse).codes;
+ return response as FormatResponse;
};
- sendDeleteCell = async (cellId: CellId): Promise<null> => {
- await this.putControlRequest({
- cell_id: cellId,
- });
- return null;
- };
- sendInstallMissingPackages = async (
- request: SendInstallMissingPackages,
- ): Promise<null> => {
- this.putControlRequest(request);
+
+ sendDeleteCell: EditRequests["sendDeleteCell"] = async (request) => {
+ await this.putControlRequest(request);
return null;
};
- sendCodeCompletionRequest = async (
- request: CodeCompletionRequest,
- ): Promise<null> => {
+
+ sendInstallMissingPackages: EditRequests["sendInstallMissingPackages"] =
+ async (request) => {
+ this.putControlRequest(request);
+ return null;
+ };
+ sendCodeCompletionRequest: EditRequests["sendCodeCompletionRequest"] = async (
+ request,
+ ) => {
// Because the Pyodide worker is single-threaded, sending
// code completion requests while the kernel is running is useless
// and runs the risk of choking the kernel
@@ -259,20 +239,18 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- saveUserConfig = async (request: SaveUserConfigRequest): Promise<null> => {
+ saveUserConfig: EditRequests["saveUserConfig"] = async (request) => {
await this.rpc.proxy.request.bridge({
functionName: "save_user_config",
payload: request,
});
- return API.post<SaveUserConfigRequest>(
- "/kernel/save_user_config",
- request,
- { baseUrl: "/" },
- );
+ return marimoClient
+ .POST("/api/kernel/save_user_config", { body: request })
+ .then(handleResponseReturnNull);
};
- saveAppConfig = async (request: SaveAppConfigRequest): Promise<null> => {
+ saveAppConfig: EditRequests["saveAppConfig"] = async (request) => {
await this.rpc.proxy.request.bridge({
functionName: "save_app_config",
payload: request,
@@ -280,10 +258,8 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- saveCellConfig = async (request: SaveCellConfigRequest): Promise<null> => {
- await this.putControlRequest({
- configs: request.configs,
- });
+ saveCellConfig: EditRequests["saveCellConfig"] = async (request) => {
+ await this.putControlRequest(request);
return null;
};
@@ -298,20 +274,20 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- readCode = async (): Promise<{ contents: string }> => {
+ readCode: EditRequests["readCode"] = async () => {
const contents = await this.saveRpc.proxy.request.readNotebook();
return { contents };
};
- readSnippets = async (): Promise<SnippetsResponse> => {
+ readSnippets: EditRequests["readSnippets"] = async () => {
const response = await this.rpc.proxy.request.bridge({
functionName: "read_snippets",
payload: undefined,
});
- return response as SnippetsResponse;
+ return response as Snippets;
};
- openFile = async (request: { path: string }): Promise<null> => {
+ openFile: EditRequests["openFile"] = async ({ path }) => {
const url = createShareableLink({
code: null,
baseUrl: window.location.origin,
@@ -320,78 +296,69 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendListFiles = async (
- request: FileListRequest,
- ): Promise<FileListResponse> => {
+ sendListFiles: EditRequests["sendListFiles"] = async (request) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "list_files",
payload: request,
});
return response as FileListResponse;
};
- sendComponentValues = async (valueUpdates: ValueUpdate[]): Promise<null> => {
+ sendComponentValues: RunRequests["sendComponentValues"] = async (request) => {
await this.putControlRequest({
- ids_and_values: valueUpdates.map((update) => [
- update.objectId,
- update.value,
- ]),
+ ...request,
token: generateUUID(),
});
return null;
};
- sendInstantiate = async (request: InstantiateRequest): Promise<null> => {
+ sendInstantiate: RunRequests["sendInstantiate"] = async (request) => {
return null;
};
- sendFunctionRequest = async (request: SendFunctionRequest): Promise<null> => {
+ sendFunctionRequest: RunRequests["sendFunctionRequest"] = async (request) => {
await this.putControlRequest(request);
return null;
};
- sendCreateFileOrFolder = async (
- request: FileCreateRequest,
- ): Promise<FileOperationResponse> => {
+ sendCreateFileOrFolder: EditRequests["sendCreateFileOrFolder"] = async (
+ request,
+ ) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "create_file_or_directory",
payload: request,
});
- return response as FileOperationResponse;
+ return response as FileCreateResponse;
};
- sendDeleteFileOrFolder = async (
- request: FileDeleteRequest,
- ): Promise<FileOperationResponse> => {
+ sendDeleteFileOrFolder: EditRequests["sendDeleteFileOrFolder"] = async (
+ request,
+ ) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "delete_file_or_directory",
payload: request,
});
- return response as FileOperationResponse;
+ return response as FileDeleteResponse;
};
- sendRenameFileOrFolder = async (
- request: FileMoveRequest,
- ): Promise<FileOperationResponse> => {
+ sendRenameFileOrFolder: EditRequests["sendRenameFileOrFolder"] = async (
+ request,
+ ) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "move_file_or_directory",
payload: request,
});
- return response as FileOperationResponse;
+ return response as FileMoveResponse;
};
- sendUpdateFile = async (
- request: FileUpdateRequest,
- ): Promise<FileOperationResponse> => {
+ sendUpdateFile: EditRequests["sendUpdateFile"] = async (request) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "update_file",
payload: request,
});
- return response as FileOperationResponse;
+ return response as FileUpdateResponse;
};
- sendFileDetails = async (request: {
- path: string;
- }): Promise<FileDetailsResponse> => {
+ sendFileDetails: EditRequests["sendFileDetails"] = async (request) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "file_details",
payload: request,
@@ -399,7 +366,9 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FileDetailsResponse;
};
- exportAsHTML = async (request: ExportAsHTMLRequest): Promise<string> => {
+ exportAsHTML: EditRequests["exportAsHTML"] = async (
+ request: ExportAsHTMLRequest,
+ ) => {
if (
process.env.NODE_ENV === "development" ||
process.env.NODE_ENV === "test"
@@ -413,9 +382,9 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as string;
};
- exportAsMarkdown = async (
+ exportAsMarkdown: EditRequests["exportAsMarkdown"] = async (
request: ExportAsMarkdownRequest,
- ): Promise<string> => {
+ ) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "export_markdown",
payload: request,
@@ -423,7 +392,12 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as string;
};
- previewDatasetColumn = throwNotImplemented;
+ previewDatasetColumn: EditRequests["previewDatasetColumn"] = async (
+ request,
+ ) => {
+ await this.putControlRequest(request);
+ return null;
+ };
getUsageStats = throwNotImplemented;
getRecentFiles = throwNotImplemented;
getWorkspaceFiles = throwNotImplemented;
diff --git a/frontend/src/core/pyodide/worker/save-worker.ts b/frontend/src/core/pyodide/worker/save-worker.ts
index 04c10249aa..c99b2fba49 100644
--- a/frontend/src/core/pyodide/worker/save-worker.ts
+++ b/frontend/src/core/pyodide/worker/save-worker.ts
@@ -12,7 +12,7 @@ import { ParentSchema } from "../rpc";
import { Logger } from "../../../utils/Logger";
import { TRANSPORT_ID } from "./constants";
import { getPyodideVersion, importPyodide } from "./getPyodideVersion";
-import { SaveKernelRequest } from "@/core/network/types";
+import { SaveNotebookRequest } from "@/core/network/types";
import { WasmFileSystem } from "./fs";
import { getController } from "./getController";
@@ -66,7 +66,7 @@ const requestHandler = createRPCRequestHandler({
await pyodideReadyPromise; // Make sure loading is done
return WasmFileSystem.readNotebook(self.pyodide);
},
- saveNotebook: async (opts: SaveKernelRequest) => {
+ saveNotebook: async (opts: SaveNotebookRequest) => {
await pyodideReadyPromise; // Make sure loading is done
const saveFile = self.pyodide.runPython(`
from marimo._pyodide.bootstrap import save_file
diff --git a/frontend/src/core/pyodide/worker/types.ts b/frontend/src/core/pyodide/worker/types.ts
index a2efbbc8bc..9fc5609a75 100644
--- a/frontend/src/core/pyodide/worker/types.ts
+++ b/frontend/src/core/pyodide/worker/types.ts
@@ -4,19 +4,22 @@ import type {
CodeCompletionRequest,
ExportAsHTMLRequest,
FileCreateRequest,
+ FileCreateResponse,
FileDeleteRequest,
+ FileDeleteResponse,
FileDetailsResponse,
FileListRequest,
FileListResponse,
FileMoveRequest,
- FileOperationResponse,
+ FileMoveResponse,
FileUpdateRequest,
+ FileUpdateResponse,
FormatRequest,
FormatResponse,
- SaveAppConfigRequest,
- SaveKernelRequest,
- SaveUserConfigRequest,
- SnippetsResponse,
+ SaveAppConfigurationRequest,
+ SaveNotebookRequest,
+ SaveUserConfigurationRequest,
+ Snippets,
} from "../../network/types";
import { OperationMessage } from "@/core/kernel/messages";
import { JsonString } from "@/utils/json/base64";
@@ -60,24 +63,22 @@ export interface RawBridge {
put_input(input: string): Promise<string>;
code_complete(request: CodeCompletionRequest): Promise<string>;
read_code(): Promise<{ contents: string }>;
- read_snippets(): Promise<SnippetsResponse>;
+ read_snippets(): Promise<Snippets>;
format(request: FormatRequest): Promise<FormatResponse>;
- save(request: SaveKernelRequest): Promise<string>;
- save_app_config(request: SaveAppConfigRequest): Promise<string>;
- save_user_config(request: SaveUserConfigRequest): Promise<null>;
+ save(request: SaveNotebookRequest): Promise<string>;
+ save_app_config(request: SaveAppConfigurationRequest): Promise<string>;
+ save_user_config(request: SaveUserConfigurationRequest): Promise<null>;
rename_file(request: string): Promise<string>;
list_files(request: FileListRequest): Promise<FileListResponse>;
file_details(request: { path: string }): Promise<FileDetailsResponse>;
create_file_or_directory(
request: FileCreateRequest,
- ): Promise<FileOperationResponse>;
+ ): Promise<FileCreateResponse>;
delete_file_or_directory(
request: FileDeleteRequest,
- ): Promise<FileOperationResponse>;
- move_file_or_directory(
- request: FileMoveRequest,
- ): Promise<FileOperationResponse>;
- update_file(request: FileUpdateRequest): Promise<FileOperationResponse>;
+ ): Promise<FileDeleteResponse>;
+ move_file_or_directory(request: FileMoveRequest): Promise<FileMoveResponse>;
+ update_file(request: FileUpdateRequest): Promise<FileUpdateResponse>;
load_packages(request: string): Promise<string>;
read_file(request: string): Promise<string>;
set_interrupt_buffer(request: Uint8Array): Promise<string>;
diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsx
index 302f9c2e31..b8efb57a1a 100644
--- a/frontend/src/plugins/core/registerReactComponent.tsx
+++ b/frontend/src/plugins/core/registerReactComponent.tsx
@@ -151,8 +151,8 @@ function PluginSlotInternal<T>(
const methods: PluginFunctions = {};
for (const [key, schemas] of Objects.entries(plugin.functions)) {
const { input, output } = schemas as {
- input: ZodSchema<unknown>;
- output: ZodSchema<unknown>;
+ input: ZodSchema<Record<string, unknown>>;
+ output: ZodSchema<Record<string, unknown>>;
};
methods[key] = async (...args: unknown[]) => {
invariant(
diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsx
index adf067fb72..21d3ccb5ac 100644
--- a/frontend/src/stories/cell.stories.tsx
+++ b/frontend/src/stories/cell.stories.tsx
@@ -5,6 +5,7 @@ import { TooltipProvider } from "../components/ui/tooltip";
import { CellId } from "../core/cells/ids";
import { Logger } from "@/utils/Logger";
import { Milliseconds, Seconds } from "@/utils/time";
+import { defaultUserConfig } from "@/core/config/config-schema";
const meta: Meta<typeof Cell> = {
title: "Cell",
@@ -50,40 +51,7 @@ const props: CellProps = {
setStdinResponse: Logger.log,
clearSerializedEditorState: Logger.log,
config: {},
- userConfig: {
- completion: {
- activate_on_typing: true,
- copilot: false,
- },
- save: {
- autosave: "off",
- autosave_delay: 1000,
- format_on_save: false,
- },
- display: {
- theme: "light",
- code_editor_font_size: 14,
- cell_output: "above",
- default_width: "medium",
- },
- runtime: {
- auto_instantiate: true,
- on_cell_change: "autorun",
- auto_reload: "off",
- },
- keymap: {
- preset: "default",
- overrides: {},
- },
- formatting: {
- line_length: 79,
- },
- package_management: {
- manager: "pip",
- },
- ai: {},
- experimental: {},
- },
+ userConfig: defaultUserConfig(),
};
export const Primary: Story = {
diff --git a/frontend/turbo.json b/frontend/turbo.json
index 96d2c00324..17856752b0 100644
--- a/frontend/turbo.json
+++ b/frontend/turbo.json
@@ -1,6 +1,6 @@
{
"$schema": "https://turbo.build/schema.json",
- "pipeline": {
+ "tasks": {
"build": {
"outputs": ["dist/**"],
"env": ["VITE_MARIMO_ISLANDS", "NODE_ENV"]
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 16e83e9615..19c3a85d81 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -33,6 +33,7 @@ def _generate_schema() -> dict[str, Any]:
snippets.SnippetSection,
snippets.Snippet,
snippets.Snippets,
+ requests.SetUIElementValueRequest,
# Requests/responses
completion.AiCompletionRequest,
export.ExportAsHTMLRequest,
@@ -64,13 +65,13 @@ def _generate_schema() -> dict[str, Any]:
models.RenameFileRequest,
models.RunRequest,
models.SaveAppConfigurationRequest,
- models.SaveRequest,
+ models.SaveNotebookRequest,
models.SaveUserConfigurationRequest,
models.StdinRequest,
models.SuccessResponse,
models.SuccessResponse,
models.UpdateComponentValuesRequest,
- requests.CompletionRequest,
+ requests.CodeCompletionRequest,
requests.CreationRequest,
requests.DeleteRequest,
requests.ExecuteMultipleRequest,
@@ -80,11 +81,12 @@ def _generate_schema() -> dict[str, Any]:
requests.InstallMissingPackagesRequest,
requests.PreviewDatasetColumnRequest,
requests.SetCellConfigRequest,
- requests.SetUIElementValueRequest,
requests.SetUserConfigRequest,
requests.StopRequest,
]
+ dont_camel_case = {MarimoConfig}
+
processed_classes: Dict[Type[Any], str] = {}
component_schemas: Dict[str, Any] = {}
@@ -94,7 +96,7 @@ def _generate_schema() -> dict[str, Any]:
if cls in processed_classes:
del processed_classes[cls]
component_schemas[cls.__name__] = dataclass_to_openapi_spec(
- cls, processed_classes
+ cls, processed_classes, camel_case=cls not in dont_camel_case
)
schemas = SchemaGenerator(
diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.py
index bec853e35a..2409e8ac50 100644
--- a/marimo/_pyodide/bootstrap.py
+++ b/marimo/_pyodide/bootstrap.py
@@ -14,7 +14,7 @@ from marimo._runtime.requests import (
)
from marimo._server.file_manager import AppFileManager
from marimo._server.model import SessionMode
-from marimo._server.models.models import SaveRequest
+from marimo._server.models.models import SaveNotebookRequest
from marimo._utils.parse_dataclass import parse_raw
if TYPE_CHECKING:
@@ -33,7 +33,9 @@ def instantiate(session: PyodideSession) -> None:
session.put_control_request(
CreationRequest(
execution_requests=execution_requests,
- set_ui_element_value_request=SetUIElementValueRequest(list()),
+ set_ui_element_value_request=SetUIElementValueRequest(
+ object_ids=[], values=[]
+ ),
)
)
@@ -97,6 +99,6 @@ def save_file(
request: str,
filename: str,
) -> None:
- parsed = parse_raw(json.loads(request), SaveRequest)
+ parsed = parse_raw(json.loads(request), SaveNotebookRequest)
app_file_manager = AppFileManager(filename=filename)
app_file_manager.save(parsed)
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index c95b6dfa96..bb1a3243f8 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -24,7 +24,7 @@ from marimo._runtime.input_override import input_override
from marimo._runtime.marimo_pdb import MarimoPdb
from marimo._runtime.requests import (
AppMetadata,
- CompletionRequest,
+ CodeCompletionRequest,
ControlRequest,
SetUIElementValueRequest,
)
@@ -56,7 +56,7 @@ from marimo._server.models.models import (
FormatResponse,
ReadCodeResponse,
SaveAppConfigurationRequest,
- SaveRequest,
+ SaveNotebookRequest,
)
from marimo._server.session.session_view import SessionView
from marimo._snippets.snippets import read_snippets
@@ -80,7 +80,7 @@ class AsyncQueueManager:
]()
# Code completion requests are sent through a separate queue
- self.completion_queue = asyncio.Queue[requests.CompletionRequest]()
+ self.completion_queue = asyncio.Queue[requests.CodeCompletionRequest]()
# Input messages for the user's Python code are sent through the
# input queue
@@ -141,7 +141,7 @@ class PyodideSession:
self._queue_manager.set_ui_element_queue.put_nowait(request)
def put_completion_request(
- self, request: requests.CompletionRequest
+ self, request: requests.CodeCompletionRequest
) -> None:
self._queue_manager.completion_queue.put_nowait(request)
@@ -169,7 +169,7 @@ class PyodideBridge:
self.session.put_input(text)
def code_complete(self, request: str) -> None:
- parsed = parse_raw(json.loads(request), requests.CompletionRequest)
+ parsed = parse_raw(json.loads(request), requests.CodeCompletionRequest)
self.session.put_completion_request(parsed)
def read_code(self) -> str:
@@ -189,7 +189,7 @@ class PyodideBridge:
return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
def save(self, request: str) -> None:
- parsed = parse_raw(json.loads(request), SaveRequest)
+ parsed = parse_raw(json.loads(request), SaveNotebookRequest)
self.session.app_manager.save(parsed)
def save_app_config(self, request: str) -> None:
@@ -300,7 +300,7 @@ class PyodideBridge:
def launch_pyodide_kernel(
control_queue: asyncio.Queue[ControlRequest],
set_ui_element_queue: asyncio.Queue[SetUIElementValueRequest],
- completion_queue: asyncio.Queue[CompletionRequest],
+ completion_queue: asyncio.Queue[CodeCompletionRequest],
input_queue: asyncio.Queue[str],
on_message: Callable[[KernelMessage], None],
is_edit_mode: bool,
diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.py
index 07674dabc7..1d06598c7d 100644
--- a/marimo/_runtime/complete.py
+++ b/marimo/_runtime/complete.py
@@ -15,7 +15,7 @@ from marimo._messaging.ops import CompletionResult
from marimo._messaging.types import Stream
from marimo._output.md import _md
from marimo._runtime import dataflow
-from marimo._runtime.requests import CompletionRequest
+from marimo._runtime.requests import CodeCompletionRequest
from marimo._server.types import QueueType
from marimo._utils.format_signature import format_signature
from marimo._utils.rst_to_html import convert_rst_to_html
@@ -246,8 +246,8 @@ def _write_no_completions(stream: Stream, completion_id: str) -> None:
def _drain_queue(
- completion_queue: QueueType[CompletionRequest],
-) -> CompletionRequest:
+ completion_queue: QueueType[CodeCompletionRequest],
+) -> CodeCompletionRequest:
"""Drain the queue of completion requests, returning the most recent one"""
request = completion_queue.get()
@@ -307,7 +307,7 @@ def _get_completions(
def complete(
- request: CompletionRequest,
+ request: CodeCompletionRequest,
graph: dataflow.DirectedGraph,
glbls: dict[str, Any],
glbls_lock: threading.RLock,
@@ -440,7 +440,7 @@ def complete(
def completion_worker(
- completion_queue: QueueType[CompletionRequest],
+ completion_queue: QueueType[CodeCompletionRequest],
graph: dataflow.DirectedGraph,
glbls: dict[str, Any],
glbls_lock: threading.RLock,
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.py
index 275b85a926..292d997294 100644
--- a/marimo/_runtime/requests.py
+++ b/marimo/_runtime/requests.py
@@ -16,7 +16,7 @@ T = TypeVar("T")
ListOrValue = Union[T, List[T]]
SerializedQueryParams = Dict[str, ListOrValue[str]]
Primitive = Union[str, bool, int, float]
-SerializedCLIArgs = Dict[str, ListOrValue[Union[Primitive]]]
+SerializedCLIArgs = Dict[str, ListOrValue[Primitive]]
@dataclass
@@ -31,16 +31,51 @@ class ExecuteStaleRequest: ...
@dataclass
class ExecuteMultipleRequest:
- execution_requests: List[ExecutionRequest]
+ # ids of cells to run
+ cell_ids: List[CellId_t]
+ # code to register/run for each cell
+ codes: List[str]
+
+ @property
+ def execution_requests(self) -> List[ExecutionRequest]:
+ return [
+ ExecutionRequest(cell_id=cell_id, code=code)
+ for cell_id, code in zip(self.cell_ids, self.codes)
+ ]
+
+ def __post_init__(self) -> None:
+ assert len(self.cell_ids) == len(
+ self.codes
+ ), "Mismatched cell_ids and codes"
@dataclass
class SetUIElementValueRequest:
- # (object id, value) tuples
- ids_and_values: List[Tuple[UIElementId, Any]]
+ object_ids: List[UIElementId]
+ values: List[Any]
# uniquely identifies the request
token: str = field(default_factory=lambda: str(uuid4()))
+ def __post_init__(self) -> None:
+ assert len(self.object_ids) == len(
+ self.values
+ ), "Mismatched object_ids and values"
+
+ @staticmethod
+ def from_ids_and_values(
+ ids_and_values: List[Tuple[UIElementId, Any]],
+ ) -> SetUIElementValueRequest:
+ if not ids_and_values:
+ return SetUIElementValueRequest(object_ids=[], values=[])
+ object_ids, values = zip(*ids_and_values)
+ return SetUIElementValueRequest(
+ object_ids=list(object_ids), values=list(values)
+ )
+
+ @property
+ def ids_and_values(self) -> List[Tuple[UIElementId, Any]]:
+ return list(zip(self.object_ids, self.values))
+
@dataclass
class FunctionCallRequest:
@@ -63,7 +98,7 @@ class AppMetadata:
@dataclass
class SetCellConfigRequest:
# Map from Cell ID to (possibly partial) CellConfig
- configs: Dict[CellId_t, Dict[str, object]]
+ configs: Dict[CellId_t, Dict[str, Any]]
@dataclass
@@ -89,7 +124,7 @@ class StopRequest:
@dataclass
-class CompletionRequest:
+class CodeCompletionRequest:
id: CompletionRequestId
document: str
cell_id: CellId_t
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index ced3f04bf8..f3536f1baa 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -79,7 +79,7 @@ from marimo._runtime.reload.autoreload import ModuleReloader
from marimo._runtime.reload.module_watcher import ModuleWatcher
from marimo._runtime.requests import (
AppMetadata,
- CompletionRequest,
+ CodeCompletionRequest,
ControlRequest,
CreationRequest,
DeleteRequest,
@@ -408,7 +408,7 @@ class Kernel:
yield
def start_completion_worker(
- self, completion_queue: QueueType[CompletionRequest]
+ self, completion_queue: QueueType[CodeCompletionRequest]
) -> None:
"""Must be called after context is initialized"""
threading.Thread(
@@ -425,7 +425,7 @@ class Kernel:
self._completion_worker_started = True
def code_completion(
- self, request: CompletionRequest, docstrings_limit: int
+ self, request: CodeCompletionRequest, docstrings_limit: int
) -> None:
complete(
request,
@@ -1408,7 +1408,7 @@ class Kernel:
def launch_kernel(
control_queue: QueueType[ControlRequest],
set_ui_element_queue: QueueType[SetUIElementValueRequest],
- completion_queue: QueueType[CompletionRequest],
+ completion_queue: QueueType[CodeCompletionRequest],
input_queue: QueueType[str],
socket_addr: tuple[str, int],
is_edit_mode: bool,
diff --git a/marimo/_runtime/utils/set_ui_element_request_manager.py b/marimo/_runtime/utils/set_ui_element_request_manager.py
index e5e95a6b33..beace666ac 100644
--- a/marimo/_runtime/utils/set_ui_element_request_manager.py
+++ b/marimo/_runtime/utils/set_ui_element_request_manager.py
@@ -52,6 +52,7 @@ class SetUIElementRequestManager:
for ui_id, value in request.ids_and_values:
merged[ui_id] = value
return SetUIElementValueRequest(
- ids_and_values=[(ui_id, value) for ui_id, value in merged.items()],
+ object_ids=list(merged.keys()),
+ values=list(merged.values()),
token="",
)
diff --git a/marimo/_server/api/endpoints/config.py b/marimo/_server/api/endpoints/config.py
index 10d8db6990..bb1446e476 100644
--- a/marimo/_server/api/endpoints/config.py
+++ b/marimo/_server/api/endpoints/config.py
@@ -32,6 +32,11 @@ async def save_user_config(
request: Request,
) -> BaseResponse:
"""
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/SaveUserConfigurationRequest"
responses:
200:
description: Update the user config on disk and in the kernel. Only allowed in edit mode.
diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.py
index 1b466a2656..f7124e7bba 100644
--- a/marimo/_server/api/endpoints/editing.py
+++ b/marimo/_server/api/endpoints/editing.py
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING
from starlette.authentication import requires
from marimo._runtime.requests import (
- CompletionRequest,
+ CodeCompletionRequest,
DeleteRequest,
InstallMissingPackagesRequest,
SetCellConfigRequest,
@@ -38,7 +38,7 @@ async def code_complete(request: Request) -> BaseResponse:
content:
application/json:
schema:
- $ref: "#/components/schemas/CompletionRequest"
+ $ref: "#/components/schemas/CodeCompletionRequest"
responses:
200:
description: Complete a code fragment
@@ -48,7 +48,7 @@ async def code_complete(request: Request) -> BaseResponse:
$ref: "#/components/schemas/SuccessResponse"
"""
app_state = AppState(request)
- body = await parse_request(request, cls=CompletionRequest)
+ body = await parse_request(request, cls=CodeCompletionRequest)
app_state.require_current_session().put_completion_request(body)
return SuccessResponse()
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index 704b9cc297..2eebd3b62b 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -54,7 +54,9 @@ async def set_ui_element_values(
app_state = AppState(request)
body = await parse_request(request, cls=UpdateComponentValuesRequest)
app_state.require_current_session().put_control_request(
- SetUIElementValueRequest(body.zip(), token=str(uuid4()))
+ SetUIElementValueRequest(
+ object_ids=body.object_ids, values=body.values, token=str(uuid4())
+ )
)
return SuccessResponse()
diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.py
index 4346726e80..b1e5027b39 100644
--- a/marimo/_server/api/endpoints/files.py
+++ b/marimo/_server/api/endpoints/files.py
@@ -18,7 +18,7 @@ from marimo._server.models.models import (
ReadCodeResponse,
RenameFileRequest,
SaveAppConfigurationRequest,
- SaveRequest,
+ SaveNotebookRequest,
SuccessResponse,
)
from marimo._server.router import APIRouter
@@ -160,7 +160,7 @@ async def save(
content:
application/json:
schema:
- $ref: "#/components/schemas/SaveRequest"
+ $ref: "#/components/schemas/SaveNotebookRequest"
responses:
200:
description: Save the current app
@@ -170,7 +170,7 @@ async def save(
$ref: "#/components/schemas/SuccessResponse"
"""
app_state = AppState(request)
- body = await parse_request(request, cls=SaveRequest)
+ body = await parse_request(request, cls=SaveNotebookRequest)
session = app_state.require_current_session()
session.app_file_manager.save(body)
diff --git a/marimo/_server/api/endpoints/health.py b/marimo/_server/api/endpoints/health.py
index 6c57940d31..3bebbdab8a 100644
--- a/marimo/_server/api/endpoints/health.py
+++ b/marimo/_server/api/endpoints/health.py
@@ -122,11 +122,23 @@ async def usage(request: Request) -> JSONResponse:
type: integer
free:
type: integer
+ required:
+ - total
+ - available
+ - percent
+ - used
+ - free
cpu:
type: object
properties:
percent:
type: number
+ required:
+ - percent
+ required:
+ - memory
+ - cpu
+
""" # noqa: E501
del request
import psutil
diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.py
index 7795f70d80..52c9fcc4dd 100644
--- a/marimo/_server/file_manager.py
+++ b/marimo/_server/file_manager.py
@@ -15,7 +15,7 @@ from marimo._runtime.layout.layout import (
save_layout_config,
)
from marimo._server.api.status import HTTPException, HTTPStatus
-from marimo._server.models.models import SaveRequest
+from marimo._server.models.models import SaveNotebookRequest
from marimo._server.utils import canonicalize_filename
LOGGER = _loggers.marimo_logger()
@@ -200,7 +200,7 @@ class AppFileManager:
new_config,
)
- def save(self, request: SaveRequest) -> None:
+ def save(self, request: SaveNotebookRequest) -> None:
"""Save the current app."""
cell_ids, codes, configs, names, filename, layout = (
request.cell_ids,
diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.py
index d066b45ca5..47f7e07994 100644
--- a/marimo/_server/models/models.py
+++ b/marimo/_server/models/models.py
@@ -2,11 +2,11 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import Any, Dict, List, Optional, Union
+from typing import Any, Dict, List, Optional
from marimo._ast.cell import CellConfig, CellId_t
from marimo._config.config import MarimoConfig
-from marimo._runtime.requests import ExecuteMultipleRequest, ExecutionRequest
+from marimo._runtime.requests import ExecuteMultipleRequest
UIElementId = str
@@ -14,13 +14,19 @@ UIElementId = str
@dataclass
class UpdateComponentValuesRequest:
object_ids: List[UIElementId]
- values: List[Union[str, bool, int, float, None]]
+ values: List[Any]
def zip(
self,
- ) -> List[tuple[UIElementId, Union[str, bool, int, float, None]]]:
+ ) -> List[tuple[UIElementId, Any]]:
return list(zip(self.object_ids, self.values))
+ # Validate same length
+ def __post_init__(self) -> None:
+ assert len(self.object_ids) == len(
+ self.values
+ ), "Mismatched object_ids and values"
+
@dataclass
class InstantiateRequest(UpdateComponentValuesRequest):
@@ -71,16 +77,17 @@ class RunRequest:
codes: List[str]
def as_execution_request(self) -> ExecuteMultipleRequest:
- return ExecuteMultipleRequest(
- execution_requests=[
- ExecutionRequest(cell_id=cid, code=code)
- for cid, code in zip(self.cell_ids, self.codes)
- ]
- )
+ return ExecuteMultipleRequest(cell_ids=self.cell_ids, codes=self.codes)
+
+ # Validate same length
+ def __post_init__(self) -> None:
+ assert len(self.cell_ids) == len(
+ self.codes
+ ), "Mismatched cell_ids and codes"
@dataclass
-class SaveRequest:
+class SaveNotebookRequest:
# id of each cell
cell_ids: List[CellId_t]
# code for each cell
@@ -94,6 +101,18 @@ class SaveRequest:
# layout of app
layout: Optional[Dict[str, Any]] = None
+ # Validate same length
+ def __post_init__(self) -> None:
+ assert len(self.cell_ids) == len(
+ self.codes
+ ), "Mismatched cell_ids and codes"
+ assert len(self.cell_ids) == len(
+ self.names
+ ), "Mismatched cell_ids and names"
+ assert len(self.cell_ids) == len(
+ self.configs
+ ), "Mismatched cell_ids and configs"
+
@dataclass
class SaveAppConfigurationRequest:
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 9f25e0fdac..6b14c41843 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -86,7 +86,7 @@ class QueueManager:
] = context.Queue() if context is not None else queue.Queue()
# Code completion requests are sent through a separate queue
- self.completion_queue: QueueType[requests.CompletionRequest] = (
+ self.completion_queue: QueueType[requests.CodeCompletionRequest] = (
context.Queue() if context is not None else queue.Queue()
)
@@ -356,7 +356,7 @@ class Session:
self.session_view.add_control_request(request)
def put_completion_request(
- self, request: requests.CompletionRequest
+ self, request: requests.CodeCompletionRequest
) -> None:
self._queue_manager.completion_queue.put(request)
@@ -424,7 +424,9 @@ class Session:
CreationRequest(
execution_requests=execution_requests,
set_ui_element_value_request=SetUIElementValueRequest(
- request.zip(), token=str(uuid4())
+ object_ids=request.object_ids,
+ values=request.values,
+ token=str(uuid4()),
),
)
)
diff --git a/marimo/_utils/dataclass_to_openapi.py b/marimo/_utils/dataclass_to_openapi.py
index c9dc599033..2b584e71c2 100644
--- a/marimo/_utils/dataclass_to_openapi.py
+++ b/marimo/_utils/dataclass_to_openapi.py
@@ -16,6 +16,8 @@ from typing import (
get_type_hints,
)
+from marimo._server.models.base import to_camel_case
+
def _python_type_to_openapi_type(
py_type: Any, processed_classes: Dict[Type[Any], str]
@@ -106,7 +108,9 @@ def _python_type_to_openapi_type(
def dataclass_to_openapi_spec(
- cls: Type[Any], processed_classes: Optional[Dict[Type[Any], str]] = None
+ cls: Type[Any],
+ processed_classes: Optional[Dict[Type[Any], str]] = None,
+ camel_case: bool = False,
) -> Dict[str, Any]:
"""Convert a dataclass to an OpenAPI schema.
@@ -136,8 +140,9 @@ def dataclass_to_openapi_spec(
required: List[str] = []
for field in fields:
+ field_name = to_camel_case(field.name) if camel_case else field.name
field_type = get_type_hints(cls)[field.name]
- properties[field.name] = _python_type_to_openapi_type(
+ properties[field_name] = _python_type_to_openapi_type(
field_type, processed_classes
)
if (
@@ -145,7 +150,7 @@ def dataclass_to_openapi_spec(
and field.default_factory is dataclasses.MISSING
and not _is_optional(field_type)
):
- required.append(field.name)
+ required.append(field_name)
schema: Dict[str, Any] = {
"type": "object",
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 8449a69eeb..d0528dd327 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -4,18 +4,18 @@ components:
properties:
code:
type: string
- include_other_code:
+ includeOtherCode:
type: string
prompt:
type: string
required:
- prompt
- - include_other_code
+ - includeOtherCode
- code
type: object
AppMetadata:
properties:
- cli_args:
+ cliArgs:
additionalProperties:
oneOf:
- type: string
@@ -33,7 +33,7 @@ components:
filename:
nullable: true
type: string
- query_params:
+ queryParams:
additionalProperties:
oneOf:
- type: string
@@ -42,8 +42,8 @@ components:
type: array
type: object
required:
- - query_params
- - cli_args
+ - queryParams
+ - cliArgs
type: object
BaseResponse:
properties:
@@ -56,12 +56,12 @@ components:
properties:
disabled:
type: boolean
- hide_code:
+ hideCode:
type: boolean
type: object
- CompletionRequest:
+ CodeCompletionRequest:
properties:
- cell_id:
+ cellId:
type: string
document:
type: string
@@ -70,64 +70,57 @@ components:
required:
- id
- document
- - cell_id
+ - cellId
type: object
CreationRequest:
properties:
- execution_requests:
+ executionRequests:
items:
$ref: '#/components/schemas/ExecutionRequest'
type: array
- set_ui_element_value_request:
- properties:
- ids_and_values:
- items:
- prefixItems:
- - type: string
- - {}
- type: array
- type: array
- token:
- type: string
- required:
- - ids_and_values
- type: object
+ setUiElementValueRequest:
+ $ref: '#/components/schemas/SetUIElementValueRequest'
required:
- - execution_requests
- - set_ui_element_value_request
+ - executionRequests
+ - setUiElementValueRequest
type: object
DeleteRequest:
properties:
- cell_id:
+ cellId:
type: string
required:
- - cell_id
+ - cellId
type: object
ExecuteMultipleRequest:
properties:
- execution_requests:
+ cellIds:
items:
- $ref: '#/components/schemas/ExecutionRequest'
+ type: string
+ type: array
+ codes:
+ items:
+ type: string
type: array
required:
- - execution_requests
+ - cellIds
+ - codes
type: object
ExecuteStaleRequest:
properties: {}
type: object
ExecutionRequest:
properties:
- cell_id:
+ cellId:
type: string
code:
type: string
required:
- - cell_id
+ - cellId
- code
type: object
ExportAsHTMLRequest:
properties:
- asset_url:
+ assetUrl:
nullable: true
type: string
download:
@@ -136,12 +129,12 @@ components:
items:
type: string
type: array
- include_code:
+ includeCode:
type: boolean
required:
- download
- files
- - include_code
+ - includeCode
type: object
ExportAsMarkdownRequest:
properties:
@@ -217,7 +210,7 @@ components:
type: string
file:
$ref: '#/components/schemas/FileInfo'
- mime_type:
+ mimeType:
nullable: true
type: string
required:
@@ -231,11 +224,11 @@ components:
type: array
id:
type: string
- is_directory:
+ isDirectory:
type: boolean
- is_marimo_file:
+ isMarimoFile:
type: boolean
- last_modified_date:
+ lastModifiedDate:
nullable: true
type: number
name:
@@ -246,8 +239,8 @@ components:
- id
- path
- name
- - is_directory
- - is_marimo_file
+ - isDirectory
+ - isMarimoFile
type: object
FileListRequest:
properties:
@@ -269,13 +262,13 @@ components:
type: object
FileMoveRequest:
properties:
- new_path:
+ newPath:
type: string
path:
type: string
required:
- path
- - new_path
+ - newPath
type: object
FileMoveResponse:
properties:
@@ -319,11 +312,11 @@ components:
additionalProperties:
type: string
type: object
- line_length:
+ lineLength:
type: integer
required:
- codes
- - line_length
+ - lineLength
type: object
FormatResponse:
properties:
@@ -339,16 +332,16 @@ components:
args:
additionalProperties: {}
type: object
- function_call_id:
+ functionCallId:
type: string
- function_name:
+ functionName:
type: string
namespace:
type: string
required:
- - function_call_id
+ - functionCallId
- namespace
- - function_name
+ - functionName
- args
type: object
InstallMissingPackagesRequest:
@@ -360,21 +353,15 @@ components:
type: object
InstantiateRequest:
properties:
- object_ids:
+ objectIds:
items:
type: string
type: array
values:
- items:
- nullable: true
- oneOf:
- - type: string
- - type: boolean
- - type: integer
- - type: number
+ items: {}
type: array
required:
- - object_ids
+ - objectIds
- values
type: object
MarimoConfig:
@@ -528,22 +515,22 @@ components:
type: object
MarimoFile:
properties:
- initialization_id:
+ initializationId:
nullable: true
type: string
- last_modified:
+ lastModified:
type: number
name:
type: string
path:
type: string
- session_id:
+ sessionId:
nullable: true
type: string
required:
- name
- path
- - last_modified
+ - lastModified
type: object
OpenFileRequest:
properties:
@@ -554,16 +541,16 @@ components:
type: object
PreviewDatasetColumnRequest:
properties:
- column_name:
+ columnName:
type: string
source:
type: string
- table_name:
+ tableName:
type: string
required:
- source
- - table_name
- - column_name
+ - tableName
+ - columnName
type: object
ReadCodeResponse:
properties:
@@ -590,7 +577,7 @@ components:
type: object
RunRequest:
properties:
- cell_ids:
+ cellIds:
items:
type: string
type: array
@@ -599,7 +586,7 @@ components:
type: string
type: array
required:
- - cell_ids
+ - cellIds
- codes
type: object
SaveAppConfigurationRequest:
@@ -610,9 +597,9 @@ components:
required:
- config
type: object
- SaveRequest:
+ SaveNotebookRequest:
properties:
- cell_ids:
+ cellIds:
items:
type: string
type: array
@@ -635,7 +622,7 @@ components:
type: string
type: array
required:
- - cell_ids
+ - cellIds
- codes
- names
- configs
@@ -652,9 +639,7 @@ components:
properties:
configs:
additionalProperties:
- additionalProperties:
- additionalProperties: true
- type: object
+ additionalProperties: {}
type: object
type: object
required:
@@ -662,17 +647,18 @@ components:
type: object
SetUIElementValueRequest:
properties:
- ids_and_values:
+ objectIds:
items:
- prefixItems:
- - type: string
- - {}
- type: array
+ type: string
type: array
token:
type: string
+ values:
+ items: {}
+ type: array
required:
- - ids_and_values
+ - objectIds
+ - values
type: object
SetUserConfigRequest:
properties:
@@ -683,10 +669,10 @@ components:
type: object
ShutdownSessionRequest:
properties:
- session_id:
+ sessionId:
type: string
required:
- - session_id
+ - sessionId
type: object
Snippet:
properties:
@@ -739,26 +725,20 @@ components:
type: object
UpdateComponentValuesRequest:
properties:
- object_ids:
+ objectIds:
items:
type: string
type: array
values:
- items:
- nullable: true
- oneOf:
- - type: string
- - type: boolean
- - type: integer
- - type: number
+ items: {}
type: array
required:
- - object_ids
+ - objectIds
- values
type: object
WorkspaceFilesRequest:
properties:
- include_markdown:
+ includeMarkdown:
type: boolean
type: object
WorkspaceFilesResponse:
@@ -1017,7 +997,7 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/CompletionRequest'
+ $ref: '#/components/schemas/CodeCompletionRequest'
responses:
200:
content:
@@ -1175,7 +1155,7 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/SaveRequest'
+ $ref: '#/components/schemas/SaveNotebookRequest'
responses:
200:
content:
@@ -1199,6 +1179,11 @@ paths:
description: Save the app configuration
/api/kernel/save_user_config:
post:
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SaveUserConfigurationRequest'
responses:
200:
content:
@@ -1300,6 +1285,8 @@ paths:
properties:
percent:
type: number
+ required:
+ - percent
type: object
memory:
properties:
@@ -1313,7 +1300,16 @@ paths:
type: integer
used:
type: integer
+ required:
+ - total
+ - available
+ - percent
+ - used
+ - free
type: object
+ required:
+ - memory
+ - cpu
type: object
description: Get the current memory and CPU usage of the application
/api/version:
diff --git a/openapi/package.json b/openapi/package.json
index fcaadfb2b0..a4cf96f94c 100644
--- a/openapi/package.json
+++ b/openapi/package.json
@@ -7,10 +7,10 @@
"type": "module",
"license": "Apache-2.0",
"files": [
- "dist"
+ "src"
],
"scripts": {
- "codegen": "npx openapi-typescript ./api.yaml -o ./src/api.d.ts"
+ "codegen": "npx openapi-typescript ./api.yaml -o ./src/api.ts"
},
"devDependencies": {
"openapi-typescript": "^6.7.6",
diff --git a/openapi/src/api.d.ts b/openapi/src/api.ts
similarity index 92%
rename from openapi/src/api.d.ts
rename to openapi/src/api.ts
index 29f02869f0..520abb9594 100644
--- a/openapi/src/api.d.ts
+++ b/openapi/src/api.ts
@@ -302,7 +302,7 @@ export interface paths {
post: {
requestBody?: {
content: {
- "application/json": components["schemas"]["CompletionRequest"];
+ "application/json": components["schemas"]["CodeCompletionRequest"];
};
};
responses: {
@@ -499,7 +499,7 @@ export interface paths {
post: {
requestBody?: {
content: {
- "application/json": components["schemas"]["SaveRequest"];
+ "application/json": components["schemas"]["SaveNotebookRequest"];
};
};
responses: {
@@ -531,6 +531,11 @@ export interface paths {
};
"/api/kernel/save_user_config": {
post: {
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["SaveUserConfigurationRequest"];
+ };
+ };
responses: {
/** @description Update the user config on disk and in the kernel. Only allowed in edit mode. */
200: {
@@ -632,15 +637,15 @@ export interface paths {
200: {
content: {
"application/json": {
- cpu?: {
- percent?: number;
+ cpu: {
+ percent: number;
};
- memory?: {
- available?: number;
- free?: number;
- percent?: number;
- total?: number;
- used?: number;
+ memory: {
+ available: number;
+ free: number;
+ percent: number;
+ total: number;
+ used: number;
};
};
};
@@ -696,11 +701,11 @@ export interface components {
schemas: {
AiCompletionRequest: {
code: string;
- include_other_code: string;
+ includeOtherCode: string;
prompt: string;
};
AppMetadata: {
- cli_args: {
+ cliArgs: {
[key: string]:
| string
| boolean
@@ -708,7 +713,7 @@ export interface components {
| (string | boolean | number)[];
};
filename?: string | null;
- query_params: {
+ queryParams: {
[key: string]: string | string[];
};
};
@@ -717,36 +722,34 @@ export interface components {
};
CellConfig: {
disabled?: boolean;
- hide_code?: boolean;
+ hideCode?: boolean;
};
- CompletionRequest: {
- cell_id: string;
+ CodeCompletionRequest: {
+ cellId: string;
document: string;
id: string;
};
CreationRequest: {
- execution_requests: components["schemas"]["ExecutionRequest"][];
- set_ui_element_value_request: {
- ids_and_values: [string, unknown][];
- token?: string;
- };
+ executionRequests: components["schemas"]["ExecutionRequest"][];
+ setUiElementValueRequest: components["schemas"]["SetUIElementValueRequest"];
};
DeleteRequest: {
- cell_id: string;
+ cellId: string;
};
ExecuteMultipleRequest: {
- execution_requests: components["schemas"]["ExecutionRequest"][];
+ cellIds: string[];
+ codes: string[];
};
ExecuteStaleRequest: Record<string, never>;
ExecutionRequest: {
- cell_id: string;
+ cellId: string;
code: string;
};
ExportAsHTMLRequest: {
- asset_url?: string | null;
+ assetUrl?: string | null;
download: boolean;
files: string[];
- include_code: boolean;
+ includeCode: boolean;
};
ExportAsMarkdownRequest: {
download: boolean;
@@ -778,14 +781,14 @@ export interface components {
FileDetailsResponse: {
contents?: string | null;
file: components["schemas"]["FileInfo"];
- mime_type?: string | null;
+ mimeType?: string | null;
};
FileInfo: {
children?: components["schemas"]["FileInfo"][];
id: string;
- is_directory: boolean;
- is_marimo_file: boolean;
- last_modified_date?: number | null;
+ isDirectory: boolean;
+ isMarimoFile: boolean;
+ lastModifiedDate?: number | null;
name: string;
path: string;
};
@@ -797,7 +800,7 @@ export interface components {
root: string;
};
FileMoveRequest: {
- new_path: string;
+ newPath: string;
path: string;
};
FileMoveResponse: {
@@ -818,7 +821,7 @@ export interface components {
codes: {
[key: string]: string;
};
- line_length: number;
+ lineLength: number;
};
FormatResponse: {
codes: {
@@ -829,16 +832,16 @@ export interface components {
args: {
[key: string]: unknown;
};
- function_call_id: string;
- function_name: string;
+ functionCallId: string;
+ functionName: string;
namespace: string;
};
InstallMissingPackagesRequest: {
manager: string;
};
InstantiateRequest: {
- object_ids: string[];
- values: (string | boolean | number | null)[];
+ objectIds: string[];
+ values: unknown[];
};
MarimoConfig: {
ai: {
@@ -897,19 +900,19 @@ export interface components {
};
};
MarimoFile: {
- initialization_id?: string | null;
- last_modified: number;
+ initializationId?: string | null;
+ lastModified: number;
name: string;
path: string;
- session_id?: string | null;
+ sessionId?: string | null;
};
OpenFileRequest: {
path: string;
};
PreviewDatasetColumnRequest: {
- column_name: string;
+ columnName: string;
source: string;
- table_name: string;
+ tableName: string;
};
ReadCodeResponse: {
contents: string;
@@ -921,7 +924,7 @@ export interface components {
filename: string;
};
RunRequest: {
- cell_ids: string[];
+ cellIds: string[];
codes: string[];
};
SaveAppConfigurationRequest: {
@@ -929,8 +932,8 @@ export interface components {
[key: string]: unknown;
};
};
- SaveRequest: {
- cell_ids: string[];
+ SaveNotebookRequest: {
+ cellIds: string[];
codes: string[];
configs: components["schemas"]["CellConfig"][];
filename: string;
@@ -945,21 +948,20 @@ export interface components {
SetCellConfigRequest: {
configs: {
[key: string]: {
- [key: string]: {
- [key: string]: unknown;
- };
+ [key: string]: unknown;
};
};
};
SetUIElementValueRequest: {
- ids_and_values: [string, unknown][];
+ objectIds: string[];
token?: string;
+ values: unknown[];
};
SetUserConfigRequest: {
config: components["schemas"]["MarimoConfig"];
};
ShutdownSessionRequest: {
- session_id: string;
+ sessionId: string;
};
Snippet: {
sections: components["schemas"]["SnippetSection"][];
@@ -981,11 +983,11 @@ export interface components {
success?: boolean;
};
UpdateComponentValuesRequest: {
- object_ids: string[];
- values: (string | boolean | number | null)[];
+ objectIds: string[];
+ values: unknown[];
};
WorkspaceFilesRequest: {
- include_markdown?: boolean;
+ includeMarkdown?: boolean;
};
WorkspaceFilesResponse: {
files: components["schemas"]["MarimoFile"][];
diff --git a/openapi/src/index.ts b/openapi/src/index.ts
index da7d34580f..20195f0d24 100644
--- a/openapi/src/index.ts
+++ b/openapi/src/index.ts
@@ -1,7 +1,7 @@
-export * from "./api.d";
+export type * from "./api";
import createClient, { ClientOptions } from "openapi-fetch";
-import type { paths } from "./api.d";
+import type { paths } from "./api";
export function createMarimoClient(opts: ClientOptions) {
return createClient<paths>(opts);
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 443c289959..0656522ae3 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -140,7 +140,7 @@ class TestExecution:
element_id = k.globals["s"]._id
await k.set_ui_element_value(
- SetUIElementValueRequest([(element_id, 5)])
+ SetUIElementValueRequest.from_ids_and_values([(element_id, 5)])
)
assert k.globals["s"].value == 5
@@ -180,7 +180,9 @@ class TestExecution:
# Set a child of the array to 5 ...
child_id = k.globals["array"][0]._id
- await k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))
+ await k.set_ui_element_value(
+ SetUIElementValueRequest.from_ids_and_values([(child_id, 5)])
+ )
# Make sure the array and its child are updated
assert k.globals["array"].value == [5]
@@ -217,7 +219,9 @@ class TestExecution:
array_id = k.globals["array"]._id
await k.set_ui_element_value(
- SetUIElementValueRequest([(array_id, {"0": 5})])
+ SetUIElementValueRequest.from_ids_and_values(
+ [(array_id, {"0": 5})]
+ )
)
assert k.globals["array"].value == [5]
if k.lazy():
@@ -247,7 +251,9 @@ class TestExecution:
# Set a child of the array and make sure its on_change handler is
# called
child_id = k.globals["array"][0]._id
- await k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))
+ await k.set_ui_element_value(
+ SetUIElementValueRequest.from_ids_and_values([(child_id, 5)])
+ )
if k.lazy():
assert k.graph.cells[er.cell_id].stale
await k.run([er])
@@ -270,7 +276,7 @@ class TestExecution:
# This shouldn't crash the kernel, and s's value should still be
# updated
await k.set_ui_element_value(
- SetUIElementValueRequest([(element_id, 5)])
+ SetUIElementValueRequest.from_ids_and_values([(element_id, 5)])
)
assert k.globals["_cell_1_s"].value == 5
@@ -287,7 +293,7 @@ class TestExecution:
cell_id="1", code="s = mo.ui.slider(0, 10, value=1)"
),
),
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
[(id_provider.take_id(), 2)]
),
)
@@ -610,7 +616,7 @@ class TestExecution:
element_id = k.globals["defs"]["slider"]._id
await k.set_ui_element_value(
- SetUIElementValueRequest([(element_id, 5)])
+ SetUIElementValueRequest.from_ids_and_values([(element_id, 5)])
)
assert k.globals["defs"]["slider"].value == 5
if k.lazy():
@@ -629,7 +635,9 @@ class TestExecution:
# smoke test -- this shouldn't raise an exception
k = any_kernel
await k.set_ui_element_value(
- SetUIElementValueRequest([("does not exist", None)])
+ SetUIElementValueRequest.from_ids_and_values(
+ [("does not exist", None)]
+ )
)
async def test_interrupt(
diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.py
index 4ca3454438..f685b17fc7 100644
--- a/tests/_server/session/test_session_view.py
+++ b/tests/_server/session/test_session_view.py
@@ -126,7 +126,7 @@ def test_session_view_variable_values() -> None:
def test_ui_values() -> None:
session_view = SessionView()
session_view.add_control_request(
- SetUIElementValueRequest([("test_ui", 123)])
+ SetUIElementValueRequest.from_ids_and_values([("test_ui", 123)])
)
assert "test_ui" in session_view.ui_values
assert session_view.ui_values["test_ui"] == 123
@@ -134,7 +134,9 @@ def test_ui_values() -> None:
# Can add multiple values
# and can overwrite values
session_view.add_control_request(
- SetUIElementValueRequest([("test_ui2", 456), ("test_ui", 789)])
+ SetUIElementValueRequest.from_ids_and_values(
+ [("test_ui2", 456), ("test_ui", 789)]
+ )
)
assert "test_ui2" in session_view.ui_values
assert "test_ui" in session_view.ui_values
@@ -145,7 +147,7 @@ def test_ui_values() -> None:
session_view.add_control_request(
CreationRequest(
execution_requests=(),
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
[("test_ui3", 101112)]
),
)
@@ -157,9 +159,8 @@ def test_last_run_code() -> None:
session_view = SessionView()
session_view.add_control_request(
ExecuteMultipleRequest(
- execution_requests=[
- ExecutionRequest(cell_id=cell_id, code="print('hello')"),
- ]
+ cell_ids=[cell_id],
+ codes=["print('hello')"],
)
)
assert session_view.last_executed_code[cell_id] == "print('hello')"
@@ -167,12 +168,8 @@ def test_last_run_code() -> None:
# Can overwrite values and add multiple
session_view.add_control_request(
ExecuteMultipleRequest(
- execution_requests=[
- ExecutionRequest(cell_id=cell_id, code="print('hello world')"),
- ExecutionRequest(
- cell_id="cell_2", code="print('hello world')"
- ),
- ]
+ cell_ids=[cell_id, "cell_2"],
+ codes=["print('hello world')", "print('hello world')"],
)
)
assert session_view.last_executed_code[cell_id] == "print('hello world')"
@@ -184,7 +181,9 @@ def test_last_run_code() -> None:
execution_requests=(
ExecutionRequest(cell_id=cell_id, code="print('hello')"),
),
- set_ui_element_value_request=SetUIElementValueRequest([]),
+ set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ []
+ ),
)
)
assert session_view.last_executed_code[cell_id] == "print('hello')"
diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.py
index 2e1a14a7ee..e22a48eb64 100644
--- a/tests/_server/test_file_manager.py
+++ b/tests/_server/test_file_manager.py
@@ -10,9 +10,9 @@ from marimo import __version__
from marimo._ast.cell import CellConfig
from marimo._server.api.status import HTTPException, HTTPStatus
from marimo._server.file_manager import AppFileManager
-from marimo._server.models.models import SaveRequest
+from marimo._server.models.models import SaveNotebookRequest
-save_request = SaveRequest(
+save_request = SaveNotebookRequest(
cell_ids=["1"],
filename="save_existing.py",
codes=["import marimo as mo"],
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index 8bb0e07b5b..200c6ffe23 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -148,7 +148,7 @@ def test_kernel_manager_interrupt(tmp_path) -> None:
]
),
set_ui_element_value_request=SetUIElementValueRequest(
- ids_and_values=[]
+ object_ids=[], values=[]
),
)
)
diff --git a/tests/_utils/test_dataclass_to_openapi.py b/tests/_utils/test_dataclass_to_openapi.py
index fba617474e..34e12b38c8 100644
--- a/tests/_utils/test_dataclass_to_openapi.py
+++ b/tests/_utils/test_dataclass_to_openapi.py
@@ -47,6 +47,20 @@ def test_dataclass_to_openapi() -> None:
}
+def test_dataclass_to_openapi_with_camelcase() -> None:
+ openapi_spec = dataclass_to_openapi_spec(Address, camel_case=True)
+ assert openapi_spec == {
+ "type": "object",
+ "properties": {
+ "street": {"type": "string"},
+ "city": {"type": "string"},
+ "zipCode": {"type": "integer", "nullable": True},
+ "kind": {"enum": ["home", "work"]},
+ },
+ "required": ["street", "city", "kind"],
+ }
+
+
@dataclasses.dataclass
class Node:
value: int