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.

refactor: rename kernel Requests to Command (#7593)

Myles Scolnick39968449d3be
diff --git a/frontend/src/components/editor/cell/useRunCells.ts b/frontend/src/components/editor/cell/useRunCells.ts
index 13599f3bc1..97441c56be 100644
--- a/frontend/src/components/editor/cell/useRunCells.ts
+++ b/frontend/src/components/editor/cell/useRunCells.ts
@@ -13,7 +13,7 @@ import { enabledCellIds, staleCellIds } from "@/core/cells/utils";
import { getCurrentLanguageAdapter } from "@/core/codemirror/language/commands";
import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";
import { useRequestClient } from "@/core/network/requests";
-import type { RunRequest } from "@/core/network/types";
+import type { ExecuteCellsRequest } from "@/core/network/types";
import { Logger } from "@/utils/Logger";
export const hasRunAnyCellAtom = atom<boolean>(false);
@@ -78,7 +78,7 @@ export async function runCells({
notebook,
}: {
cellIds: CellId[];
- sendRun: (request: RunRequest) => Promise<null>;
+ sendRun: (request: ExecuteCellsRequest) => Promise<null>;
prepareForRun: (action: { cellId: CellId }) => void;
notebook: NotebookState;
}) {
diff --git a/frontend/src/core/ai/tools/base.ts b/frontend/src/core/ai/tools/base.ts
index 163aca85fa..bb03034778 100644
--- a/frontend/src/core/ai/tools/base.ts
+++ b/frontend/src/core/ai/tools/base.ts
@@ -3,7 +3,7 @@
import { z } from "zod";
import type { CreateNewCellAction } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
-import type { RunRequest } from "@/core/network/types";
+import type { ExecuteCellsRequest } from "@/core/network/types";
import type { JotaiStore } from "@/core/state/jotai";
import type { Edit } from "../staged-cells";
import type { CopilotMode } from "./registry";
@@ -106,7 +106,7 @@ export interface ToolNotebookContext {
addStagedCell: (payload: { cellId: CellId; edit: Edit }) => void;
createNewCell: (payload: CreateNewCellAction) => void;
prepareForRun: (payload: { cellId: CellId }) => void;
- sendRun: (request: RunRequest) => Promise<null>;
+ sendRun: (request: ExecuteCellsRequest) => Promise<null>;
}
export interface AiTool<TIn, TOut> {
diff --git a/frontend/src/core/datasets/request-registry.ts b/frontend/src/core/datasets/request-registry.ts
index 18c173586a..a487ba7031 100644
--- a/frontend/src/core/datasets/request-registry.ts
+++ b/frontend/src/core/datasets/request-registry.ts
@@ -8,7 +8,7 @@ import { CachingRequestRegistry } from "../network/CachingRequestRegistry";
import { DeferredRequestRegistry } from "../network/DeferredRequestRegistry";
import { getRequestClient } from "../network/requests";
import type {
- PreviewSQLTableListRequest,
+ ListSQLTablesRequest,
PreviewSQLTableRequest,
ValidateSQLRequest,
} from "../network/types";
@@ -29,7 +29,7 @@ export const PreviewSQLTable = new DeferredRequestRegistry<
});
export const PreviewSQLTableList = new DeferredRequestRegistry<
- Omit<PreviewSQLTableListRequest, "requestId">,
+ Omit<ListSQLTablesRequest, "requestId">,
SQLTableListPreview
>("sql-table-list-preview", async (requestId, req) => {
const client = getRequestClient();
diff --git a/frontend/src/core/functions/FunctionRegistry.ts b/frontend/src/core/functions/FunctionRegistry.ts
index 9609ac93aa..90f69db65a 100644
--- a/frontend/src/core/functions/FunctionRegistry.ts
+++ b/frontend/src/core/functions/FunctionRegistry.ts
@@ -3,10 +3,10 @@
import type { FunctionCallResultMessage } from "../kernel/messages";
import { DeferredRequestRegistry } from "../network/DeferredRequestRegistry";
import { getRequestClient } from "../network/requests";
-import type { FunctionCallRequest } from "../network/types";
+import type { InvokeFunctionRequest } from "../network/types";
export const FUNCTIONS_REGISTRY = new DeferredRequestRegistry<
- Omit<FunctionCallRequest, "functionCallId">,
+ Omit<InvokeFunctionRequest, "functionCallId">,
FunctionCallResultMessage
>("function-call-result", async (requestId, req) => {
const client = getRequestClient();
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index 1fd78b2309..f74a005fd3 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -49,6 +49,7 @@ export type Capabilities =
export type CacheInfoFetched = NotificationMessageData<"cache-info">;
export type NotificationMessage = schemas["KnownUnions"]["notification"];
+export type CommandMessage = schemas["KnownUnions"]["command"];
export type NotificationMessageType = NotificationMessage["op"];
export interface NotificationPayload {
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 75aca16447..392570ed62 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -17,8 +17,6 @@ export type CellConfig = schemas["CellConfig"];
export type RuntimeState = schemas["CellNotification"]["status"];
export type CodeCompletionRequest = schemas["CodeCompletionRequest"];
export type DeleteCellRequest = schemas["DeleteCellRequest"];
-export type ExecuteMultipleRequest = schemas["ExecuteMultipleRequest"];
-export type ExecutionRequest = schemas["ExecutionRequest"];
export type ExportAsHTMLRequest = schemas["ExportAsHTMLRequest"];
export type ExportAsMarkdownRequest = schemas["ExportAsMarkdownRequest"];
export type ExportAsIPYNBRequest = schemas["ExportAsIPYNBRequest"];
@@ -38,12 +36,11 @@ 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 FormatCellsRequest = schemas["FormatCellsRequest"];
export type FormatResponse = schemas["FormatResponse"];
-export type FunctionCallRequest = schemas["FunctionCallRequest"];
+export type InvokeFunctionRequest = schemas["InvokeFunctionRequest"];
export type ListSecretKeysResponse = schemas["ListSecretKeysResponse"];
-export type InstallMissingPackagesRequest =
- schemas["InstallMissingPackagesRequest"];
+export type InstallPackagesRequest = schemas["InstallPackagesRequest"];
export type AddPackageRequest = schemas["AddPackageRequest"];
export type RemovePackageRequest = schemas["RemovePackageRequest"];
export type ListPackagesResponse = schemas["ListPackagesResponse"];
@@ -51,7 +48,7 @@ export type DependencyTreeResponse = schemas["DependencyTreeResponse"];
export type DependencyTreeNode = schemas["DependencyTreeNode"];
export type PackageOperationResponse = schemas["PackageOperationResponse"];
-export type InstantiateRequest = schemas["InstantiateRequest"];
+export type InstantiateNotebookRequest = schemas["InstantiateNotebookRequest"];
export type MarimoConfig = schemas["MarimoConfig"];
export type MarimoFile = schemas["MarimoFile"];
export type ListSecretKeysRequest = schemas["ListSecretKeysRequest"];
@@ -59,15 +56,15 @@ export type CreateSecretRequest = schemas["CreateSecretRequest"];
export type PreviewDatasetColumnRequest =
schemas["PreviewDatasetColumnRequest"];
export type PreviewSQLTableRequest = schemas["PreviewSQLTableRequest"];
-export type PreviewSQLTableListRequest = schemas["PreviewSQLTableListRequest"];
-export type PreviewDataSourceConnectionRequest =
- schemas["PreviewDataSourceConnectionRequest"];
+export type ListSQLTablesRequest = schemas["ListSQLTablesRequest"];
+export type ListDataSourceConnectionRequest =
+ schemas["ListDataSourceConnectionRequest"];
export type ValidateSQLRequest = schemas["ValidateSQLRequest"];
-export type PdbRequest = schemas["PdbRequest"];
+export type DebugCellRequest = schemas["DebugCellRequest"];
export type ReadCodeResponse = schemas["ReadCodeResponse"];
export type RecentFilesResponse = schemas["RecentFilesResponse"];
-export type RenameFileRequest = schemas["RenameFileRequest"];
-export type RunRequest = schemas["RunRequest"];
+export type RenameNotebookRequest = schemas["RenameNotebookRequest"];
+export type ExecuteCellsRequest = schemas["ExecuteCellsRequest"];
export type ExecuteScratchpadRequest = schemas["ExecuteScratchpadRequest"];
export type SaveAppConfigurationRequest =
schemas["SaveAppConfigurationRequest"];
@@ -78,18 +75,18 @@ export type SaveUserConfigurationRequest =
export interface SetCellConfigRequest {
configs: Record<CellId, Partial<CellConfig>>;
}
-export type SetUIElementValueRequest = schemas["SetUIElementValueRequest"];
-export type SetModelMessageRequest = schemas["SetModelMessageRequest"];
+export type UpdateUIElementRequest = schemas["UpdateUIElementRequest"];
+export type UpdateWidgetModelRequest = schemas["UpdateWidgetModelRequest"];
export type UpdateCellIdsRequest = schemas["UpdateCellIdsRequest"];
-export type SetUserConfigRequest = schemas["SetUserConfigRequest"];
+export type UpdateUserConfigRequest = schemas["UpdateUserConfigRequest"];
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 UpdateUIElementValuesRequest =
+ schemas["UpdateUIElementValuesRequest"];
export type UsageResponse =
paths["/api/usage"]["get"]["responses"]["200"]["content"]["application/json"];
export type WorkspaceFilesRequest = schemas["WorkspaceFilesRequest"];
@@ -106,25 +103,25 @@ export type GetCacheInfoRequest = schemas["GetCacheInfoRequest"];
* Requests sent to the BE during run/edit mode.
*/
export interface RunRequests {
- sendComponentValues: (request: UpdateComponentValuesRequest) => Promise<null>;
- sendModelValue: (request: SetModelMessageRequest) => Promise<null>;
- sendInstantiate: (request: InstantiateRequest) => Promise<null>;
- sendFunctionRequest: (request: FunctionCallRequest) => Promise<null>;
+ sendComponentValues: (request: UpdateUIElementValuesRequest) => Promise<null>;
+ sendModelValue: (request: UpdateWidgetModelRequest) => Promise<null>;
+ sendInstantiate: (request: InstantiateNotebookRequest) => Promise<null>;
+ sendFunctionRequest: (request: InvokeFunctionRequest) => Promise<null>;
}
/**
* Requests sent to the BE during edit mode.
*/
export interface EditRequests {
- sendRename: (request: RenameFileRequest) => Promise<null>;
+ sendRename: (request: RenameNotebookRequest) => Promise<null>;
sendSave: (request: SaveNotebookRequest) => Promise<null>;
sendCopy: (request: CopyNotebookRequest) => Promise<null>;
sendStdin: (request: StdinRequest) => Promise<null>;
- sendRun: (request: RunRequest) => Promise<null>;
+ sendRun: (request: ExecuteCellsRequest) => Promise<null>;
sendRunScratchpad: (request: ExecuteScratchpadRequest) => Promise<null>;
sendInterrupt: () => Promise<null>;
sendShutdown: () => Promise<null>;
- sendFormat: (request: FormatRequest) => Promise<FormatResponse>;
+ sendFormat: (request: FormatCellsRequest) => Promise<FormatResponse>;
sendDeleteCell: (request: DeleteCellRequest) => Promise<null>;
sendCodeCompletionRequest: (request: CodeCompletionRequest) => Promise<null>;
saveUserConfig: (request: SaveUserConfigurationRequest) => Promise<null>;
@@ -133,21 +130,21 @@ export interface EditRequests {
sendRestart: () => Promise<null>;
syncCellIds: (request: UpdateCellIdsRequest) => Promise<null>;
sendInstallMissingPackages: (
- request: InstallMissingPackagesRequest,
+ request: InstallPackagesRequest,
) => Promise<null>;
readCode: () => Promise<{ contents: string }>;
readSnippets: () => Promise<Snippets>;
previewDatasetColumn: (request: PreviewDatasetColumnRequest) => Promise<null>;
previewSQLTable: (request: PreviewSQLTableRequest) => Promise<null>;
- previewSQLTableList: (request: PreviewSQLTableListRequest) => Promise<null>;
+ previewSQLTableList: (request: ListSQLTablesRequest) => Promise<null>;
previewDataSourceConnection: (
- request: PreviewDataSourceConnectionRequest,
+ request: ListDataSourceConnectionRequest,
) => Promise<null>;
validateSQL: (request: ValidateSQLRequest) => Promise<null>;
openFile: (request: { path: string; lineNumber?: number }) => Promise<null>;
getUsageStats: () => Promise<UsageResponse>;
// Debugger
- sendPdb: (request: PdbRequest) => Promise<null>;
+ sendPdb: (request: DebugCellRequest) => Promise<null>;
// File explorer requests
sendListFiles: (request: FileListRequest) => Promise<FileListResponse>;
sendSearchFiles: (request: FileSearchRequest) => Promise<FileSearchResponse>;
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index 146d84ba82..64b5080b50 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -9,6 +9,7 @@ import { Logger } from "@/utils/Logger";
import { reloadSafe } from "@/utils/reload-safe";
import { generateUUID } from "@/utils/uuid";
import { notebookIsRunningAtom } from "../cells/cells";
+import type { CommandMessage } from "../kernel/messages";
import { getMarimoVersion } from "../meta/globals";
import { getInitialAppMode } from "../mode";
import { API } from "../network/api";
@@ -247,13 +248,19 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendRun: EditRequests["sendRun"] = async (request) => {
await this.rpc.proxy.request.loadPackages(request.codes.join("\n"));
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "execute-cells",
+ ...request,
+ });
return null;
};
sendRunScratchpad: EditRequests["sendRunScratchpad"] = async (request) => {
await this.rpc.proxy.request.loadPackages(request.code);
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "execute-scratchpad",
+ ...request,
+ });
return null;
};
sendInterrupt: EditRequests["sendInterrupt"] = async () => {
@@ -276,13 +283,19 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
sendDeleteCell: EditRequests["sendDeleteCell"] = async (request) => {
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "delete-cell",
+ ...request,
+ });
return null;
};
sendInstallMissingPackages: EditRequests["sendInstallMissingPackages"] =
async (request) => {
- this.putControlRequest(request);
+ this.putControlRequest({
+ type: "install-packages",
+ ...request,
+ });
return null;
};
sendCodeCompletionRequest: EditRequests["sendCodeCompletionRequest"] = async (
@@ -328,7 +341,10 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
saveCellConfig: EditRequests["saveCellConfig"] = async (request) => {
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "update-cell-config",
+ ...request,
+ });
return null;
};
@@ -387,6 +403,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
sendComponentValues: RunRequests["sendComponentValues"] = async (request) => {
await this.putControlRequest({
+ type: "update-ui-element",
...request,
token: generateUUID(),
});
@@ -398,7 +415,10 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
sendFunctionRequest: RunRequests["sendFunctionRequest"] = async (request) => {
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "invoke-function",
+ ...request,
+ });
return null;
};
@@ -477,48 +497,57 @@ export class PyodideBridge implements RunRequests, EditRequests {
previewDatasetColumn: EditRequests["previewDatasetColumn"] = async (
request,
) => {
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "preview-dataset-column",
+ ...request,
+ });
return null;
};
previewSQLTable: EditRequests["previewSQLTable"] = async (request) => {
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "preview-sql-table",
+ ...request,
+ });
return null;
};
previewSQLTableList: EditRequests["previewSQLTableList"] = async (
request,
) => {
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "list-sql-tables",
+ ...request,
+ });
return null;
};
previewDataSourceConnection: EditRequests["previewDataSourceConnection"] =
async (request) => {
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "list-data-source-connection",
+ ...request,
+ });
return null;
};
validateSQL: EditRequests["validateSQL"] = async (request) => {
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "validate-sql",
+ ...request,
+ });
return null;
};
sendModelValue: RunRequests["sendModelValue"] = async (request) => {
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "update-widget-model",
+ ...request,
+ });
return null;
};
syncCellIds = () => Promise.resolve(null);
- getUsageStats = throwNotImplemented;
- openTutorial = throwNotImplemented;
- getRecentFiles = throwNotImplemented;
- getWorkspaceFiles = throwNotImplemented;
- getRunningNotebooks = throwNotImplemented;
- shutdownSession = throwNotImplemented;
- autoExportAsHTML = throwNotImplemented;
- autoExportAsMarkdown = throwNotImplemented;
- autoExportAsIPYNB = throwNotImplemented;
addPackage: EditRequests["addPackage"] = async (request) => {
return this.rpc.proxy.request.addPackage(request);
@@ -544,20 +573,28 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
listSecretKeys: EditRequests["listSecretKeys"] = async (request) => {
- await this.putControlRequest(request);
- return null;
- };
-
- writeSecret: EditRequests["writeSecret"] = async (request) => {
- await this.putControlRequest(request);
+ await this.putControlRequest({
+ type: "list-secret-keys",
+ ...request,
+ });
return null;
};
+ getUsageStats = throwNotImplemented;
+ openTutorial = throwNotImplemented;
+ getRecentFiles = throwNotImplemented;
+ getWorkspaceFiles = throwNotImplemented;
+ getRunningNotebooks = throwNotImplemented;
+ shutdownSession = throwNotImplemented;
+ autoExportAsHTML = throwNotImplemented;
+ autoExportAsMarkdown = throwNotImplemented;
+ autoExportAsIPYNB = throwNotImplemented;
+ writeSecret = throwNotImplemented;
invokeAiTool = throwNotImplemented;
clearCache = throwNotImplemented;
getCacheInfo = throwNotImplemented;
- private async putControlRequest(operation: object) {
+ private async putControlRequest(operation: CommandMessage) {
await this.rpc.proxy.request.bridge({
functionName: "put_control_request",
payload: operation,
diff --git a/frontend/src/core/wasm/worker/types.ts b/frontend/src/core/wasm/worker/types.ts
index 337cbd1032..b1850d8ee0 100644
--- a/frontend/src/core/wasm/worker/types.ts
+++ b/frontend/src/core/wasm/worker/types.ts
@@ -1,12 +1,16 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type { PyodideInterface } from "pyodide";
import type { UserConfig } from "@/core/config/config-schema";
-import type { NotificationPayload } from "@/core/kernel/messages";
+import type {
+ CommandMessage,
+ NotificationPayload,
+} from "@/core/kernel/messages";
import type { JsonString } from "@/utils/json/base64";
import type {
CodeCompletionRequest,
CopyNotebookRequest,
ExportAsHTMLRequest,
+ ExportAsMarkdownRequest,
FileCreateRequest,
FileCreateResponse,
FileDeleteRequest,
@@ -20,7 +24,7 @@ import type {
FileSearchResponse,
FileUpdateRequest,
FileUpdateResponse,
- FormatRequest,
+ FormatCellsRequest,
FormatResponse,
SaveAppConfigurationRequest,
SaveNotebookRequest,
@@ -62,12 +66,12 @@ export interface WasmController {
}
export interface RawBridge {
- put_control_request(operation: object): Promise<string>;
+ put_control_request(operation: CommandMessage): Promise<string>;
put_input(input: string): Promise<string>;
code_complete(request: CodeCompletionRequest): Promise<string>;
read_code(): Promise<{ contents: string }>;
read_snippets(): Promise<Snippets>;
- format(request: FormatRequest): Promise<FormatResponse>;
+ format(request: FormatCellsRequest): Promise<FormatResponse>;
save(request: SaveNotebookRequest): Promise<string>;
copy(request: CopyNotebookRequest): Promise<string>;
save_app_config(request: SaveAppConfigurationRequest): Promise<string>;
@@ -88,9 +92,13 @@ export interface RawBridge {
read_file(request: string): Promise<string>;
set_interrupt_buffer(request: Uint8Array): Promise<string>;
export_html(request: ExportAsHTMLRequest): Promise<string>;
- export_markdown(request: ExportAsHTMLRequest): Promise<string>;
+ export_markdown(request: ExportAsMarkdownRequest): Promise<string>;
}
+export type BridgePayload<T extends keyof RawBridge> = T extends keyof RawBridge
+ ? Parameters<RawBridge[T]>[0]
+ : undefined;
+
export type SerializedBridge = {
[P in keyof RawBridge]: RawBridge[P] extends (
payload: string,
diff --git a/frontend/src/core/wasm/worker/worker.ts b/frontend/src/core/wasm/worker/worker.ts
index a7f4136f9a..5d9ad22628 100644
--- a/frontend/src/core/wasm/worker/worker.ts
+++ b/frontend/src/core/wasm/worker/worker.ts
@@ -28,7 +28,12 @@ import { getController } from "./getController";
import { getPyodideVersion } from "./getPyodideVersion";
import { MessageBuffer } from "./message-buffer";
import { t } from "./tracer";
-import type { RawBridge, SerializedBridge, WasmController } from "./types";
+import type {
+ BridgePayload,
+ RawBridge,
+ SerializedBridge,
+ WasmController,
+} from "./types";
/**
* Web worker responsible for running the notebook.
@@ -256,10 +261,10 @@ const requestHandler = createRPCRequestHandler({
/**
* Call a function on the bridge
*/
- bridge: async (opts: {
+ async bridge<T extends keyof RawBridge>(opts: {
functionName: keyof RawBridge;
- payload: {} | undefined | null;
- }) => {
+ payload: BridgePayload<T>;
+ }): Promise<unknown> {
const span = t.startSpan("bridge", {
functionName: opts.functionName,
});
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 3a108a9808..49ad00c8d5 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -49,15 +49,15 @@ from marimo._output.rich_help import mddoc
from marimo._runtime import dataflow
from marimo._runtime.app.kernel_runner import AppKernelRunner
from marimo._runtime.app.script_runner import AppScriptRunner
+from marimo._runtime.commands import (
+ InvokeFunctionCommand,
+ UpdateUIElementCommand,
+)
from marimo._runtime.context.types import (
ContextNotInitializedError,
get_context,
runtime_context_installed,
)
-from marimo._runtime.requests import (
- FunctionCallRequest,
- SetUIElementValueRequest,
-)
from marimo._schemas.serialization import (
AppInstantiation,
CellDef,
@@ -744,13 +744,13 @@ class App:
return output, _Namespace(defs, owner=self)
async def _set_ui_element_value(
- self, request: SetUIElementValueRequest
+ self, request: UpdateUIElementCommand
) -> bool:
app_kernel_runner = self._get_kernel_runner()
return await app_kernel_runner.set_ui_element_value(request)
async def _function_call(
- self, request: FunctionCallRequest
+ self, request: InvokeFunctionCommand
) -> tuple[HumanReadableStatus, JSONType, bool]:
app_kernel_runner = self._get_kernel_runner()
return await app_kernel_runner.function_call(request)
@@ -1004,12 +1004,12 @@ class InternalApp:
return self._app._run_cell_sync(cell, kwargs)
async def set_ui_element_value(
- self, request: SetUIElementValueRequest
+ self, request: UpdateUIElementCommand
) -> bool:
return await self._app._set_ui_element_value(request)
async def function_call(
- self, request: FunctionCallRequest
+ self, request: InvokeFunctionCommand
) -> tuple[HumanReadableStatus, JSONType, bool]:
return await self._app._function_call(request)
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 9fb1d8bc59..9190dac56e 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -16,6 +16,7 @@ from marimo._cli.print import orange
from marimo._data.models import DataType
from marimo._messaging.errors import Error as MarimoError
from marimo._messaging.notification import NotificationMessage
+from marimo._runtime.commands import CommandMessage
from marimo._server.session.serialize import (
serialize_notebook,
serialize_session_view,
@@ -33,7 +34,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
import marimo._data.models as data
import marimo._messaging.errors as errors
import marimo._messaging.notification as notification
- import marimo._runtime.requests as requests
+ import marimo._runtime.commands as commands
import marimo._secrets.models as secrets_models
import marimo._server.models.completion as completion
import marimo._server.models.export as export
@@ -47,18 +48,12 @@ def _generate_server_api_schema() -> dict[str, Any]:
from marimo._ast.cell import CellConfig, RuntimeStateType
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.mimetypes import KnownMimeType
- from marimo._plugins.core.web_component import JSONType
from marimo._runtime.packages.package_manager import PackageDescription
from marimo._server.ai.tools.types import ToolDefinition
from marimo._server.api.router import build_routes
- from marimo._utils.dataclass_to_openapi import (
- PythonTypeToOpenAPI,
- )
from marimo._version import __version__
- # dataclass components used in websocket messages
- # these are always snake_case
- MESSAGES = [
+ MODELS = [
# Base
RuntimeStateType,
KnownMimeType,
@@ -140,18 +135,14 @@ def _generate_server_api_schema() -> dict[str, Any]:
# ai
ChatMessage,
ToolDefinition,
- ]
-
- # dataclass components used in requests/responses
- REQUEST_RESPONSES = [
# Sub components
home.MarimoFile,
files.FileInfo,
- requests.ExecutionRequest,
+ commands.ExecuteCellCommand,
snippets.SnippetSection,
snippets.Snippet,
snippets.Snippets,
- requests.SetUIElementValueRequest,
+ commands.UpdateUIElementCommand,
# Requests/responses
completion.VariableContext,
completion.SchemaColumn,
@@ -194,134 +185,94 @@ def _generate_server_api_schema() -> dict[str, Any]:
home.ShutdownSessionRequest,
home.WorkspaceFilesRequest,
home.WorkspaceFilesResponse,
+ commands.ClearCacheCommand,
+ commands.CodeCompletionCommand,
+ commands.DebugCellCommand,
+ commands.DeleteCellCommand,
+ commands.ExecuteCellsCommand,
+ commands.ExecuteScratchpadCommand,
+ commands.ExecuteStaleCellsCommand,
+ commands.ExecuteCellCommand,
+ commands.GetCacheInfoCommand,
+ commands.HTTPRequest,
+ commands.InstallPackagesCommand,
+ commands.InvokeFunctionCommand,
+ commands.ListDataSourceConnectionCommand,
+ commands.ListSecretKeysCommand,
+ commands.ListSQLTablesCommand,
+ commands.ModelMessage,
+ commands.PreviewDatasetColumnCommand,
+ commands.PreviewSQLTableCommand,
+ commands.RenameNotebookCommand,
+ commands.StopKernelCommand,
+ commands.UpdateCellConfigCommand,
+ commands.UpdateUserConfigCommand,
+ commands.UpdateWidgetModelCommand,
+ commands.ValidateSQLCommand,
models.BaseResponse,
- models.FormatRequest,
+ models.ClearCacheRequest,
+ models.CodeCompletionRequest,
+ models.CopyNotebookRequest,
+ models.DebugCellRequest,
+ models.DeleteCellRequest,
+ models.ExecuteScratchpadRequest,
+ models.FormatCellsRequest,
models.FormatResponse,
- models.InstantiateRequest,
+ models.GetCacheInfoRequest,
+ models.InstallPackagesRequest,
+ models.InstantiateNotebookRequest,
+ models.InvokeAiToolRequest,
+ models.InvokeAiToolResponse,
+ models.InvokeFunctionRequest,
+ models.ListDataSourceConnectionRequest,
+ models.ListSecretKeysRequest,
+ models.ListSQLTablesRequest,
+ models.MCPRefreshResponse,
+ models.MCPStatusResponse,
+ models.PreviewDatasetColumnRequest,
+ models.PreviewSQLTableRequest,
models.ReadCodeResponse,
- models.RenameFileRequest,
- models.RunRequest,
+ models.RefreshSecretsRequest,
+ models.RenameNotebookRequest,
+ models.ExecuteCellsRequest,
models.SaveAppConfigurationRequest,
models.SaveNotebookRequest,
- models.CopyNotebookRequest,
models.SaveUserConfigurationRequest,
models.StdinRequest,
models.SuccessResponse,
models.SuccessResponse,
- models.UpdateComponentValuesRequest,
- models.InvokeAiToolRequest,
- models.InvokeAiToolResponse,
- models.MCPStatusResponse,
- models.MCPRefreshResponse,
- requests.CodeCompletionRequest,
- requests.DeleteCellRequest,
- requests.UpdateCellIdsRequest,
- requests.HTTPRequest,
- requests.ExecuteMultipleRequest,
- requests.ExecuteScratchpadRequest,
- requests.ExecuteStaleRequest,
- requests.ExecutionRequest,
- requests.FunctionCallRequest,
- requests.InstallMissingPackagesRequest,
- requests.ListSecretKeysRequest,
- requests.ClearCacheRequest,
- requests.GetCacheInfoRequest,
- requests.PdbRequest,
- requests.PreviewDatasetColumnRequest,
- requests.PreviewSQLTableListRequest,
- requests.PreviewDataSourceConnectionRequest,
- requests.PreviewSQLTableRequest,
- requests.ValidateSQLRequest,
- requests.RenameRequest,
- requests.SetCellConfigRequest,
- requests.ModelMessage,
- requests.SetModelMessageRequest,
- requests.SetUserConfigRequest,
- requests.StopRequest,
+ models.UpdateCellConfigRequest,
+ models.UpdateCellIdsRequest,
+ models.UpdateUIElementValuesRequest,
+ models.UpdateUIElementRequest,
+ models.UpdateUserConfigRequest,
+ models.UpdateWidgetModelRequest,
+ models.ValidateSQLRequest,
]
- processed_classes: dict[Any, str] = {
- JSONType: "JSONType",
- }
- component_schemas: dict[str, Any] = {
- # Hand-written schema to avoid circular dependencies
- "JSONType": {
- "oneOf": [
- {"type": "string"},
- {"type": "number"},
- {"type": "object"},
- {"type": "array"},
- {"type": "boolean"},
- {"type": "null"},
- ]
- },
- "HTTPRequest": {"type": "null"},
- }
- # We must override the names of some Union Types,
- # otherwise, their __name__ is "Union"
- name_overrides: dict[Any, str] = {
- JSONType: "JSONType",
- errors.Error: "Error",
- KnownMimeType: "MimeType",
- data.DataType: "DataType",
- data.NonNestedLiteral: "NonNestedLiteral",
- RuntimeStateType: "RuntimeState",
- CellChannel: "CellChannel",
- notification.NotificationMessage: "NotificationMessage",
- }
-
# Hack to get the unions to be included in the schema
class KnownUnions(msgspec.Struct):
notification: NotificationMessage
+ command: CommandMessage
error: MarimoError
data_type: DataType
- specs = msgspec.json.schema_components(
- MESSAGES + [KnownUnions],
+ _defs, component_schemas = msgspec.json.schema_components(
+ MODELS + [KnownUnions],
ref_template="#/components/schemas/{name}",
)
- component_schemas = {
- **specs[1],
- }
- processed_classes = {
- **processed_classes,
- **{name: name for name in specs[1].keys()},
- }
-
- converter = PythonTypeToOpenAPI(
- camel_case=True, name_overrides=name_overrides
- )
- for cls in REQUEST_RESPONSES:
- # Remove self from the list
- # since it may not have been processed yet
- if cls in processed_classes:
- del processed_classes[cls]
- name = name_overrides.get(cls, cls.__name__) # type: ignore[attr-defined]
- component_schemas[name] = converter.convert(cls, processed_classes)
- processed_classes[cls] = name
schemas_generator = SchemaGenerator(
{
"openapi": "3.1.0",
"info": {"title": "marimo API", "version": __version__},
"components": {
- "schemas": {
- **component_schemas,
- }
+ "schemas": component_schemas,
},
}
)
- schemas = schemas_generator.get_schema(routes=build_routes())
-
- # Find/replace #/$defs with #/components/schemas
- import json
-
- schemas_str = json.dumps(schemas)
- schemas_str = schemas_str.replace("#/$defs", "#/components/schemas")
- schemas = json.loads(schemas_str)
-
- return schemas
+ return schemas_generator.get_schema(routes=build_routes())
@click.group(
diff --git a/marimo/_cli/parse_args.py b/marimo/_cli/parse_args.py
index 12b2725fad..1422f23e23 100644
--- a/marimo/_cli/parse_args.py
+++ b/marimo/_cli/parse_args.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import sys
from typing import TYPE_CHECKING, Any
-from marimo._runtime.requests import SerializedCLIArgs
+from marimo._runtime.commands import SerializedCLIArgs
if TYPE_CHECKING:
from collections.abc import Iterable
diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.py
index 6ca47318cb..92b02bb803 100644
--- a/marimo/_data/preview_column.py
+++ b/marimo/_data/preview_column.py
@@ -22,7 +22,7 @@ from marimo._plugins.ui._impl.tables.table_manager import (
TableManager,
)
from marimo._plugins.ui._impl.tables.utils import get_table_manager_or_none
-from marimo._runtime.requests import PreviewDatasetColumnRequest
+from marimo._runtime.commands import PreviewDatasetColumnCommand
from marimo._sql.utils import wrapped_sql
from marimo._utils.narwhals_utils import downgrade_narwhals_df_to_v1
@@ -138,7 +138,7 @@ def get_column_preview_dataset(
def get_column_preview_for_dataframe(
item: object,
- request: PreviewDatasetColumnRequest,
+ request: PreviewDatasetColumnCommand,
) -> DataColumnPreviewNotification | None:
"""
Finds the table manager for the item and gets the column preview.
diff --git a/marimo/_ipc/connection.py b/marimo/_ipc/connection.py
index 8a65d31cd5..ed8834604d 100644
--- a/marimo/_ipc/connection.py
+++ b/marimo/_ipc/connection.py
@@ -17,10 +17,10 @@ from marimo._server.types import QueueType
if typing.TYPE_CHECKING:
from marimo._messaging.types import KernelMessage
- from marimo._runtime.requests import (
- CodeCompletionRequest,
- ControlRequest,
- SetUIElementValueRequest,
+ from marimo._runtime.commands import (
+ CodeCompletionCommand,
+ CommandMessage,
+ UpdateUIElementCommand,
)
LOGGER = _loggers.marimo_logger()
@@ -81,9 +81,9 @@ class Connection:
context: zmq.Context[zmq.Socket[bytes]]
- control: Channel[ControlRequest]
- ui_element: Channel[SetUIElementValueRequest]
- completion: Channel[CodeCompletionRequest]
+ control: Channel[CommandMessage]
+ ui_element: Channel[UpdateUIElementCommand]
+ completion: Channel[CodeCompletionCommand]
win32_interrupt: Channel[bool] | None
input: Channel[str]
diff --git a/marimo/_ipc/queue_manager.py b/marimo/_ipc/queue_manager.py
index 38fdecbdb2..870af94ba6 100644
--- a/marimo/_ipc/queue_manager.py
+++ b/marimo/_ipc/queue_manager.py
@@ -11,10 +11,10 @@ from marimo._ipc.types import ConnectionInfo
if typing.TYPE_CHECKING:
from marimo._messaging.types import KernelMessage
- from marimo._runtime.requests import (
- CodeCompletionRequest,
- ControlRequest,
- SetUIElementValueRequest,
+ from marimo._runtime.commands import (
+ CodeCompletionCommand,
+ CommandMessage,
+ UpdateUIElementCommand,
)
from marimo._server.types import QueueType
@@ -38,17 +38,17 @@ class QueueManager:
conn: Connection
@property
- def control_queue(self) -> QueueType[ControlRequest]:
+ def control_queue(self) -> QueueType[CommandMessage]:
"""Queue for control requests (execute, interrupt, etc.)."""
return self.conn.control.queue
@property
- def set_ui_element_queue(self) -> QueueType[SetUIElementValueRequest]:
+ def set_ui_element_queue(self) -> QueueType[UpdateUIElementCommand]:
"""Queue for UI element value updates."""
return self.conn.ui_element.queue
@property
- def completion_queue(self) -> QueueType[CodeCompletionRequest]:
+ def completion_queue(self) -> QueueType[CodeCompletionCommand]:
"""Queue for code completion requests."""
return self.conn.completion.queue
diff --git a/marimo/_ipc/types.py b/marimo/_ipc/types.py
index 4ea9bce615..8fcaaadcc6 100644
--- a/marimo/_ipc/types.py
+++ b/marimo/_ipc/types.py
@@ -9,7 +9,7 @@ import msgspec.json
from marimo._ast.cell import CellConfig
from marimo._config.config import MarimoConfig
from marimo._messaging.msgspec_encoder import encode_json_bytes
-from marimo._runtime.requests import AppMetadata
+from marimo._runtime.commands import AppMetadata
from marimo._types.ids import CellId_t
diff --git a/marimo/_messaging/context.py b/marimo/_messaging/context.py
index a7f90f75a8..b5a79ba496 100644
--- a/marimo/_messaging/context.py
+++ b/marimo/_messaging/context.py
@@ -6,7 +6,7 @@ from contextvars import ContextVar
from dataclasses import dataclass
from typing import Any, Optional
-from marimo._runtime.requests import HTTPRequest
+from marimo._runtime.commands import HTTPRequest
RunId_t = str
RUN_ID_CTX = ContextVar[Optional[RunId_t]]("run_id")
diff --git a/marimo/_plugins/ui/_impl/chat/chat.py b/marimo/_plugins/ui/_impl/chat/chat.py
index bbc692e31d..316ff6feab 100644
--- a/marimo/_plugins/ui/_impl/chat/chat.py
+++ b/marimo/_plugins/ui/_impl/chat/chat.py
@@ -16,9 +16,9 @@ from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._plugins.ui._impl.chat.utils import from_chat_message_dict
+from marimo._runtime.commands import UpdateUIElementCommand
from marimo._runtime.context.types import ContextNotInitializedError
from marimo._runtime.functions import EmptyArgs, Function
-from marimo._runtime.requests import SetUIElementValueRequest
DEFAULT_CONFIG = ChatModelConfigDict(
max_tokens=4096,
@@ -313,7 +313,7 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):
if isinstance(ctx, KernelRuntimeContext):
ctx._kernel.enqueue_control_request(
- SetUIElementValueRequest(
+ UpdateUIElementCommand(
object_ids=[self._id],
values=[{"messages": self._chat_history}],
request=None,
diff --git a/marimo/_plugins/ui/_impl/comm.py b/marimo/_plugins/ui/_impl/comm.py
index 7b48052620..eff12beb3c 100644
--- a/marimo/_plugins/ui/_impl/comm.py
+++ b/marimo/_plugins/ui/_impl/comm.py
@@ -11,7 +11,7 @@ if TYPE_CHECKING:
from marimo._plugins.ui._impl.anywidget.types import (
TypedModelMessagePayload,
)
- from marimo._runtime.requests import ModelMessage
+ from marimo._runtime.commands import ModelMessage
LOGGER = marimo_logger()
diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.py
index 206da9df32..16dda6ea7f 100644
--- a/marimo/_pyodide/bootstrap.py
+++ b/marimo/_pyodide/bootstrap.py
@@ -13,12 +13,12 @@ from marimo._messaging.serde import (
deserialize_kernel_message,
serialize_kernel_message,
)
-from marimo._runtime.requests import (
+from marimo._runtime.commands import (
AppMetadata,
- CreationRequest,
- ExecutionRequest,
+ CreateNotebookCommand,
+ ExecuteCellCommand,
SerializedQueryParams,
- SetUIElementValueRequest,
+ UpdateUIElementCommand,
)
from marimo._server.model import SessionMode
from marimo._server.models.models import SaveNotebookRequest
@@ -42,7 +42,7 @@ def instantiate(
app = session.app_manager.app
execution_requests = tuple(
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id=cell_data.cell_id,
code=cell_data.code,
request=None,
@@ -51,9 +51,9 @@ def instantiate(
)
session.put_control_request(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=execution_requests,
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[], values=[], request=None
),
auto_run=auto_instantiate,
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 5b10761f94..b5dfa2cfd3 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -6,12 +6,9 @@ import base64
import json
import re
import signal
-import typing
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
-import msgspec
-
from marimo import _loggers
from marimo._config.config import (
MarimoConfig,
@@ -26,20 +23,20 @@ from marimo._pyodide.streams import (
PyodideStdout,
PyodideStream,
)
-from marimo._runtime import handlers, patches, requests
+from marimo._runtime import commands, handlers, patches
+from marimo._runtime.commands import (
+ AppMetadata,
+ CodeCompletionCommand,
+ CommandMessage,
+ UpdateUIElementCommand,
+ UpdateUserConfigCommand,
+)
from marimo._runtime.context.kernel_context import initialize_kernel_context
from marimo._runtime.input_override import input_override
from marimo._runtime.marimo_pdb import MarimoPdb
from marimo._runtime.packages.pypi_package_manager import (
MicropipPackageManager,
)
-from marimo._runtime.requests import (
- AppMetadata,
- CodeCompletionRequest,
- ControlRequest,
- SetUIElementValueRequest,
- SetUserConfigRequest,
-)
from marimo._runtime.runtime import Kernel
from marimo._runtime.utils.set_ui_element_request_manager import (
SetUIElementRequestManager,
@@ -64,7 +61,7 @@ from marimo._server.models.files import (
FileUpdateResponse,
)
from marimo._server.models.models import (
- FormatRequest,
+ FormatCellsRequest,
FormatResponse,
ReadCodeResponse,
SaveAppConfigurationRequest,
@@ -92,15 +89,15 @@ class AsyncQueueManager:
def __init__(self) -> None:
# Control messages for the kernel (run, set UI element, set config, etc
# ) are sent through the control queue
- self.control_queue = asyncio.Queue[requests.ControlRequest]()
+ self.control_queue = asyncio.Queue[commands.CommandMessage]()
# set UI elements duplicated in another queue so they can be batched
self.set_ui_element_queue = asyncio.Queue[
- requests.SetUIElementValueRequest
+ commands.UpdateUIElementCommand
]()
# Code completion requests are sent through a separate queue
- self.completion_queue = asyncio.Queue[requests.CodeCompletionRequest]()
+ self.completion_queue = asyncio.Queue[commands.CodeCompletionCommand]()
# Input messages for the user's Python code are sent through the
# input queue
@@ -109,7 +106,7 @@ class AsyncQueueManager:
def close_queues(self) -> None:
# kernel thread cleans up read/write conn and IOloop handler on
# exit; we don't join the thread because we don't want to block
- self.control_queue.put_nowait(requests.StopRequest())
+ self.control_queue.put_nowait(commands.StopKernelCommand())
class PyodideSession:
@@ -155,13 +152,13 @@ class PyodideSession:
)
await self.kernel_task.start()
- def put_control_request(self, request: requests.ControlRequest) -> None:
+ def put_control_request(self, request: commands.CommandMessage) -> None:
self._queue_manager.control_queue.put_nowait(request)
- if isinstance(request, requests.SetUIElementValueRequest):
+ if isinstance(request, commands.UpdateUIElementCommand):
self._queue_manager.set_ui_element_queue.put_nowait(request)
def put_completion_request(
- self, request: requests.CodeCompletionRequest
+ self, request: commands.CodeCompletionCommand
) -> None:
self._queue_manager.completion_queue.put_nowait(request)
@@ -211,36 +208,24 @@ class PyodideSession:
T = TypeVar("T")
-def parse_wasm_control_request(request: str) -> requests.ControlRequest:
- """Parse a control request string for WASM/Pyodide.
-
- This iterates through ControlRequest types in order until one successfully
- parses. The order matters because some types have overlapping structures
- when parsed with msgspec (e.g., types with only optional fields).
+def parse_command(request: str) -> commands.CommandMessage:
+ """Parse a command string for WASM/Pyodide.
Args:
request: JSON string containing the request
Returns:
- Parsed ControlRequest
+ Parsed CommandMessage
Raises:
msgspec.DecodeError: If no type successfully parses
"""
- parsed: typing.Union[requests.ControlRequest, None] = None
- for ControlRequestType in typing.get_args(requests.ControlRequest):
- try:
- parsed = parse_raw(request, cls=ControlRequestType)
- break # success
- except msgspec.DecodeError:
- continue
-
- if parsed is None:
- raise msgspec.DecodeError(
- f"Could not decode ControlRequest as any of {typing.get_args(requests.ControlRequest)}"
- )
-
- return parsed
+ parsed = parse_raw(
+ request,
+ cls=commands.CommandMessage, # type: ignore
+ allow_unknown_keys=True,
+ )
+ return cast(commands.CommandMessage, parsed)
class PyodideBridge:
@@ -252,14 +237,14 @@ class PyodideBridge:
self.file_system = OSFileSystem()
def put_control_request(self, request: str) -> None:
- parsed = parse_wasm_control_request(request)
+ parsed = parse_command(request)
self.session.put_control_request(parsed)
def put_input(self, text: str) -> None:
self.session.put_input(text)
def code_complete(self, request: str) -> None:
- parsed = self._parse(request, requests.CodeCompletionRequest)
+ parsed = self._parse(request, commands.CodeCompletionCommand)
self.session.put_completion_request(parsed)
def read_code(self) -> str:
@@ -272,7 +257,7 @@ class PyodideBridge:
return self._dump(snippets)
async def format(self, request: str) -> str:
- parsed = self._parse(request, FormatRequest)
+ parsed = self._parse(request, FormatCellsRequest)
formatter = DefaultFormatter(line_length=parsed.line_length)
response = FormatResponse(codes=await formatter.format(parsed.codes))
@@ -289,7 +274,9 @@ class PyodideBridge:
def save_user_config(self, request: str) -> None:
parsed = self._parse(request, SaveUserConfigurationRequest)
config = merge_default_config(cast(PartialMarimoConfig, parsed.config))
- self.session.put_control_request(SetUserConfigRequest(config=config))
+ self.session.put_control_request(
+ UpdateUserConfigCommand(config=config)
+ )
def rename_file(self, filename: str) -> None:
self.session.app_manager.rename(filename)
@@ -414,9 +401,9 @@ class PyodideBridge:
def _launch_pyodide_kernel(
- control_queue: asyncio.Queue[ControlRequest],
- set_ui_element_queue: asyncio.Queue[SetUIElementValueRequest],
- completion_queue: asyncio.Queue[CodeCompletionRequest],
+ control_queue: asyncio.Queue[CommandMessage],
+ set_ui_element_queue: asyncio.Queue[UpdateUIElementCommand],
+ completion_queue: asyncio.Queue[CodeCompletionCommand],
input_queue: asyncio.Queue[str],
on_message: Callable[[KernelMessage], None],
is_edit_mode: bool,
@@ -444,9 +431,9 @@ def _launch_pyodide_kernel(
stdin = PyodideStdin(stream) if is_edit_mode else None
debugger = MarimoPdb(stdout=stdout, stdin=stdin) if is_edit_mode else None
- def _enqueue_control_request(req: ControlRequest) -> None:
+ def _enqueue_control_request(req: CommandMessage) -> None:
control_queue.put_nowait(req)
- if isinstance(req, SetUIElementValueRequest):
+ if isinstance(req, UpdateUIElementCommand):
set_ui_element_queue.put_nowait(req)
kernel = Kernel(
@@ -481,9 +468,9 @@ def _launch_pyodide_kernel(
async def listen_messages() -> None:
while True:
- request: ControlRequest | None = await control_queue.get()
+ request: CommandMessage | None = await control_queue.get()
LOGGER.debug("received request %s", request)
- if isinstance(request, requests.SetUIElementValueRequest):
+ if isinstance(request, commands.UpdateUIElementCommand):
request = ui_element_request_mgr.process_request(request)
if request is not None:
diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.py
index 2ca4daaea7..e1fc6aab37 100644
--- a/marimo/_runtime/app/kernel_runner.py
+++ b/marimo/_runtime/app/kernel_runner.py
@@ -7,14 +7,14 @@ from typing import TYPE_CHECKING, Any
from marimo._ast.cell import CellImpl
from marimo._config.config import DEFAULT_CONFIG
from marimo._runtime.app.common import RunOutput
-from marimo._runtime.context.types import get_context
-from marimo._runtime.patches import create_main_module
-from marimo._runtime.requests import (
+from marimo._runtime.commands import (
AppMetadata,
- ExecutionRequest,
- FunctionCallRequest,
- SetUIElementValueRequest,
+ ExecuteCellCommand,
+ InvokeFunctionCommand,
+ UpdateUIElementCommand,
)
+from marimo._runtime.context.types import get_context
+from marimo._runtime.patches import create_main_module
from marimo._runtime.runner import cell_runner
from marimo._server.model import SessionMode
from marimo._types.ids import CellId_t
@@ -127,7 +127,7 @@ class AppKernelRunner:
async def run(self, cells_to_run: set[CellId_t]) -> RunOutput:
execution_requests = [
- ExecutionRequest(cell_id=cid, code=cell._cell.code, request=None)
+ ExecuteCellCommand(cell_id=cid, code=cell._cell.code, request=None)
for cid in cells_to_run
if (cell := self.app.cell_manager.cell_data_at(cid).cell)
is not None
@@ -151,13 +151,13 @@ class AppKernelRunner:
return self.outputs, self._kernel.globals
async def set_ui_element_value(
- self, request: SetUIElementValueRequest
+ self, request: UpdateUIElementCommand
) -> bool:
with self._runtime_context.install():
return await self._kernel.set_ui_element_value(request)
async def function_call(
- self, request: FunctionCallRequest
+ self, request: InvokeFunctionCommand
) -> tuple[HumanReadableStatus, JSONType, bool]:
with self._runtime_context.install():
return await self._kernel.function_call_request(request)
diff --git a/marimo/_runtime/app_meta.py b/marimo/_runtime/app_meta.py
index 4430a3e292..7238761947 100644
--- a/marimo/_runtime/app_meta.py
+++ b/marimo/_runtime/app_meta.py
@@ -5,12 +5,12 @@ from typing import Optional
from marimo._config.config import DEFAULT_CONFIG
from marimo._output.rich_help import mddoc
+from marimo._runtime.commands import HTTPRequest
from marimo._runtime.context.types import (
ContextNotInitializedError,
get_context,
)
from marimo._runtime.context.utils import RunMode, get_mode
-from marimo._runtime.requests import HTTPRequest
@mddoc
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/commands.py
similarity index 65%
rename from marimo/_runtime/requests.py
rename to marimo/_runtime/commands.py
index 66c393d180..51cde2d60b 100644
--- a/marimo/_runtime/requests.py
+++ b/marimo/_runtime/commands.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import re
import time
from collections import defaultdict
from collections.abc import Mapping
@@ -31,7 +32,24 @@ if TYPE_CHECKING:
from starlette.requests import HTTPConnection
-CompletionRequestId = str
+def kebab_case(name: str) -> str:
+ if name.endswith("Command"):
+ name = name[:-7] # Remove 'Command' (7 characters)
+ if not name:
+ return name
+ # Insert hyphens before uppercase letters that follow lowercase letters
+ # or before an uppercase letter followed by a lowercase letter (handling acronyms)
+ # This groups consecutive uppercase letters together (e.g., "SQL" -> "sql")
+ s1 = re.sub("(.)([A-Z][a-z]+)", r"\1-\2", name)
+ s2 = re.sub("([a-z0-9])([A-Z])", r"\1-\2", s1)
+ return s2.lower()
+
+
+class Command(
+ msgspec.Struct, rename="camel", tag_field="type", tag=kebab_case
+):
+ pass
+
T = TypeVar("T")
ListOrValue = Union[T, list[T]]
@@ -128,16 +146,16 @@ class HTTPRequest(Mapping[str, Any]):
)
-class PdbRequest(msgspec.Struct, rename="camel"):
+class DebugCellCommand(Command):
cell_id: CellId_t
# incoming request, e.g. from Starlette or FastAPI
request: Optional[HTTPRequest] = None
def __repr__(self) -> str:
- return f"PdbRequest(cell={self.cell_id})"
+ return f"DebugCellCommand(cell={self.cell_id})"
-class ExecutionRequest(msgspec.Struct, rename="camel"):
+class ExecuteCellCommand(Command):
cell_id: CellId_t
code: str
# incoming request, e.g. from Starlette or FastAPI
@@ -146,14 +164,16 @@ class ExecutionRequest(msgspec.Struct, rename="camel"):
def __repr__(self) -> str:
preview = self.code[:10].replace("\n", " ")
- return f"ExecutionRequest(cell={self.cell_id}, code_preview={preview})"
+ return (
+ f"ExecuteCellCommand(cell={self.cell_id}, code_preview={preview})"
+ )
-class ExecuteStaleRequest(msgspec.Struct, rename="camel"):
+class ExecuteStaleCellsCommand(Command):
request: Optional[HTTPRequest] = None
-class ExecuteMultipleRequest(msgspec.Struct, rename="camel"):
+class ExecuteCellsCommand(Command):
# ids of cells to run
cell_ids: list[CellId_t]
# code to register/run for each cell
@@ -164,12 +184,12 @@ class ExecuteMultipleRequest(msgspec.Struct, rename="camel"):
timestamp: float = msgspec.field(default_factory=time.time)
def __repr__(self) -> str:
- return f"ExecuteMultipleRequest(cells={len(self.cell_ids)})"
+ return f"ExecuteCellsCommand(cells={len(self.cell_ids)})"
@property
- def execution_requests(self) -> list[ExecutionRequest]:
+ def execution_requests(self) -> list[ExecuteCellCommand]:
return [
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id=cell_id,
code=code,
request=self.request,
@@ -184,7 +204,7 @@ class ExecuteMultipleRequest(msgspec.Struct, rename="camel"):
)
-class SyncGraphRequest(msgspec.Struct, rename="camel"):
+class SyncGraphCommand(Command):
# ids of cells known to filemanager
cells: dict[CellId_t, str]
# From the list of ALL cells that filemanager knows about,
@@ -195,9 +215,9 @@ class SyncGraphRequest(msgspec.Struct, rename="camel"):
timestamp: float = msgspec.field(default_factory=time.time)
@property
- def execution_requests(self) -> list[ExecutionRequest]:
+ def execution_requests(self) -> list[ExecuteCellCommand]:
return [
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id=cell_id,
code=self.cells[cell_id],
request=None,
@@ -207,17 +227,17 @@ class SyncGraphRequest(msgspec.Struct, rename="camel"):
]
-class ExecuteScratchpadRequest(msgspec.Struct, rename="camel"):
+class ExecuteScratchpadCommand(Command):
code: str
# incoming request, e.g. from Starlette or FastAPI
request: Optional[HTTPRequest] = None
-class RenameRequest(msgspec.Struct, rename="camel"):
+class RenameNotebookCommand(Command):
filename: str
-class SetUIElementValueRequest(msgspec.Struct, rename="camel"):
+class UpdateUIElementCommand(Command):
object_ids: list[UIElementId]
values: list[Any]
# Incoming request, e.g. from Starlette or FastAPI
@@ -226,7 +246,7 @@ class SetUIElementValueRequest(msgspec.Struct, rename="camel"):
token: str = msgspec.field(default_factory=lambda: str(uuid4()))
def __repr__(self) -> str:
- return f"SetUIElementValueRequest(n_elements={len(self.object_ids)}, token={self.token})"
+ return f"UpdateUIElementCommand(n_elements={len(self.object_ids)}, token={self.token})"
def __post_init__(self) -> None:
assert len(self.object_ids) == len(self.values), (
@@ -235,20 +255,20 @@ class SetUIElementValueRequest(msgspec.Struct, rename="camel"):
# Empty token is not valid (but let's not fail)
if not self.token:
LOGGER.warning(
- "SetUIElementValueRequest with empty token is invalid"
+ "UpdateUIElementRequest with empty token is invalid"
)
@staticmethod
def from_ids_and_values(
ids_and_values: list[tuple[UIElementId, Any]],
request: Optional[HTTPRequest] = None,
- ) -> SetUIElementValueRequest:
+ ) -> UpdateUIElementCommand:
if not ids_and_values:
- return SetUIElementValueRequest(
+ return UpdateUIElementCommand(
object_ids=[], values=[], request=request
)
object_ids, values = zip(*ids_and_values)
- return SetUIElementValueRequest(
+ return UpdateUIElementCommand(
object_ids=list(object_ids),
values=list(values),
request=request,
@@ -259,17 +279,17 @@ class SetUIElementValueRequest(msgspec.Struct, rename="camel"):
return list(zip(self.object_ids, self.values))
-class FunctionCallRequest(msgspec.Struct, rename="camel"):
+class InvokeFunctionCommand(Command):
function_call_id: RequestId
namespace: str
function_name: str
args: dict[str, Any]
def __repr__(self) -> str:
- return f"FunctionCallRequest(id={self.function_call_id}, fn={self.namespace}.{self.function_name})"
+ return f"InvokeFunctionCommand(id={self.function_call_id}, fn={self.namespace}.{self.function_name})"
-class AppMetadata(msgspec.Struct, rename="camel"):
+class AppMetadata(Command):
"""Hold metadata about the app, like its filename."""
query_params: SerializedQueryParams
@@ -280,49 +300,45 @@ class AppMetadata(msgspec.Struct, rename="camel"):
filename: Optional[str] = None
-class SetCellConfigRequest(msgspec.Struct, rename="camel"):
+class UpdateCellConfigCommand(Command):
# Map from Cell ID to (possibly partial) CellConfig
configs: dict[CellId_t, dict[str, Any]]
-class SetUserConfigRequest(msgspec.Struct, rename="camel"):
+class UpdateUserConfigCommand(Command):
# MarimoConfig TypedDict
config: MarimoConfig
def __repr__(self) -> str:
- return "SetUserConfigRequest(config=...)"
+ return "UpdateUserConfigCommand(config=...)"
-class CreationRequest(msgspec.Struct, rename="camel"):
- execution_requests: tuple[ExecutionRequest, ...]
- set_ui_element_value_request: SetUIElementValueRequest
+class CreateNotebookCommand(Command):
+ execution_requests: tuple[ExecuteCellCommand, ...]
+ set_ui_element_value_request: UpdateUIElementCommand
auto_run: bool
request: Optional[HTTPRequest] = None
-class DeleteCellRequest(msgspec.Struct, rename="camel"):
+class DeleteCellCommand(Command):
cell_id: CellId_t
-class UpdateCellIdsRequest(msgspec.Struct, rename="camel"):
- cell_ids: list[CellId_t]
-
-
-class StopRequest(msgspec.Struct, rename="camel"):
+class StopKernelCommand(Command):
pass
-class CodeCompletionRequest(msgspec.Struct, rename="camel"):
- id: CompletionRequestId
+class CodeCompletionCommand(Command):
+ id: RequestId
document: str
"""Source code found in the cell up to the cursor position."""
cell_id: CellId_t
def __repr__(self) -> str:
- return f"CodeCompletionRequest(id={self.id}, cell={self.cell_id})"
+ return f"CodeCompletionCommand(id={self.id}, cell={self.cell_id})"
-class InstallMissingPackagesRequest(msgspec.Struct, rename="camel"):
+class InstallPackagesCommand(Command):
# TODO: index URL (index/channel/...)
manager: str
@@ -332,7 +348,7 @@ class InstallMissingPackagesRequest(msgspec.Struct, rename="camel"):
versions: dict[str, str]
-class PreviewDatasetColumnRequest(msgspec.Struct, rename="camel"):
+class PreviewDatasetColumnCommand(Command):
# The source type of the dataset
source_type: DataTableSource
# The source of the dataset
@@ -348,7 +364,7 @@ class PreviewDatasetColumnRequest(msgspec.Struct, rename="camel"):
fully_qualified_table_name: Optional[str] = None
-class PreviewSQLTableRequest(msgspec.Struct, rename="camel"):
+class PreviewSQLTableCommand(Command):
"""Preview table details in an SQL database"""
request_id: RequestId
@@ -358,7 +374,7 @@ class PreviewSQLTableRequest(msgspec.Struct, rename="camel"):
table_name: str
-class PreviewSQLTableListRequest(msgspec.Struct, rename="camel"):
+class ListSQLTablesCommand(Command):
"""Preview list of tables in an SQL schema"""
request_id: RequestId
@@ -367,13 +383,13 @@ class PreviewSQLTableListRequest(msgspec.Struct, rename="camel"):
schema: str
-class PreviewDataSourceConnectionRequest(msgspec.Struct, rename="camel"):
+class ListDataSourceConnectionCommand(Command):
"""Fetch a datasource connection"""
engine: str
-class ValidateSQLRequest(msgspec.Struct, rename="camel"):
+class ValidateSQLCommand(Command):
"""Validate an SQL query against the engine"""
request_id: RequestId
@@ -385,15 +401,7 @@ class ValidateSQLRequest(msgspec.Struct, rename="camel"):
dialect: Optional[str] = None
-class ParseSQLRequest(msgspec.Struct, rename="camel"):
- """Parse an SQL query for linting"""
-
- request_id: RequestId
- dialect: str
- query: str
-
-
-class ListSecretKeysRequest(msgspec.Struct, rename="camel"):
+class ListSecretKeysCommand(Command):
request_id: RequestId
@@ -402,70 +410,56 @@ class ModelMessage(msgspec.Struct, rename="camel"):
buffer_paths: list[list[Union[str, int]]]
-class SetModelMessageRequest(msgspec.Struct, rename="camel"):
+class UpdateWidgetModelCommand(Command):
model_id: WidgetModelId
message: ModelMessage
buffers: Optional[list[str]] = None
-class RefreshSecretsRequest(msgspec.Struct, rename="camel"):
+class RefreshSecretsCommand(Command):
pass
-class ClearCacheRequest(msgspec.Struct, rename="camel"):
+class ClearCacheCommand(Command):
pass
-class GetCacheInfoRequest(msgspec.Struct, rename="camel"):
+class GetCacheInfoCommand(Command):
pass
-# IMPORTANT: This is NOT a discriminated union. In WASM/Pyodide, we parse requests
-# by trying each type in order until one succeeds (see PyodideBridge.put_control_request).
-# The order matters because some types have overlapping structures when parsed with
-# msgspec (e.g., types with only optional fields).
-#
-# Ordering principles for WASM compatibility:
-# 1. Types with more specific/required fields should come before generic ones
-# 2. Types with unique field names should come before types with common field names
-# 3. Types with no fields or only optional fields should come last
-#
-# Known overlaps to be careful about:
-# - SetUIElementValueRequest has specific fields (object_ids, values) and should
-# come before generic requests
-# - ExecuteStaleRequest has only an optional 'request' field and could match many
-# payloads - should be near the end
-# - StopRequest and RefreshSecretsRequest have no fields and will match any empty
-# object - should be last
-ControlRequest = Union[
- # Requests with many specific required fields (most specific first)
- CreationRequest,
- ExecuteMultipleRequest,
- InstallMissingPackagesRequest,
- PreviewDatasetColumnRequest,
- PreviewSQLTableRequest,
- PreviewSQLTableListRequest,
- SetUIElementValueRequest,
- SetModelMessageRequest,
- FunctionCallRequest,
- # Requests with fewer but still specific required fields
- # Note: DeleteCellRequest and PdbRequest both have only cellId as required field.
- # We put DeleteCellRequest first as it's more commonly used in WASM.
- # PdbRequest (debugger) is rarely/never used in WASM context.
- DeleteCellRequest,
- PdbRequest,
- ExecuteScratchpadRequest,
- SyncGraphRequest,
- RenameRequest,
- SetCellConfigRequest,
- SetUserConfigRequest,
- ListSecretKeysRequest,
- PreviewDataSourceConnectionRequest,
- ValidateSQLRequest,
- # Requests with no fields (will match any empty object)
- StopRequest,
- RefreshSecretsRequest,
- ClearCacheRequest,
- GetCacheInfoRequest,
- ExecuteStaleRequest, # only comes from backend set low priority
+CommandMessage = Union[
+ # Notebook operations
+ CreateNotebookCommand,
+ RenameNotebookCommand,
+ # Cell execution and management
+ ExecuteCellsCommand,
+ ExecuteScratchpadCommand,
+ ExecuteStaleCellsCommand,
+ DebugCellCommand,
+ DeleteCellCommand,
+ SyncGraphCommand,
+ UpdateCellConfigCommand,
+ # Package management
+ InstallPackagesCommand,
+ # UI element and widget model operations
+ UpdateUIElementCommand,
+ UpdateWidgetModelCommand,
+ InvokeFunctionCommand,
+ # User/configuration operations
+ UpdateUserConfigCommand,
+ # Data SQL operations
+ PreviewDatasetColumnCommand,
+ PreviewSQLTableCommand,
+ ListSQLTablesCommand,
+ ValidateSQLCommand,
+ ListDataSourceConnectionCommand,
+ # Secrets management
+ ListSecretKeysCommand,
+ RefreshSecretsCommand,
+ # Cache management
+ ClearCacheCommand,
+ GetCacheInfoCommand,
+ # Kernel operations
+ StopKernelCommand,
]
diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.py
index e00bb3cd94..56b40578e2 100644
--- a/marimo/_runtime/complete.py
+++ b/marimo/_runtime/complete.py
@@ -21,7 +21,7 @@ from marimo._messaging.notification_utils import broadcast_notification
from marimo._messaging.types import Stream
from marimo._output.md import _md
from marimo._runtime import dataflow
-from marimo._runtime.requests import CodeCompletionRequest
+from marimo._runtime.commands import CodeCompletionCommand
from marimo._server.types import QueueType
from marimo._utils.docs import MarimoConverter
from marimo._utils.format_signature import format_signature
@@ -314,8 +314,8 @@ def _write_no_completions(stream: Stream, completion_id: str) -> None:
def _drain_queue(
- completion_queue: QueueType[CodeCompletionRequest],
-) -> CodeCompletionRequest:
+ completion_queue: QueueType[CodeCompletionCommand],
+) -> CodeCompletionCommand:
"""Drain the queue of completion requests, returning the most recent one"""
request = completion_queue.get()
@@ -555,7 +555,7 @@ def _get_completions(
# share the same `prefix_length`. This could happen if completion values
# are generated via different means
def complete(
- request: CodeCompletionRequest,
+ request: CodeCompletionCommand,
graph: dataflow.DirectedGraph,
glbls: dict[str, Any],
glbls_lock: threading.RLock,
@@ -698,7 +698,7 @@ def complete(
def completion_worker(
- completion_queue: QueueType[CodeCompletionRequest],
+ completion_queue: QueueType[CodeCompletionCommand],
graph: dataflow.DirectedGraph,
glbls: dict[str, Any],
glbls_lock: threading.RLock,
diff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.py
index ec52b93fdc..fbfe037b34 100644
--- a/marimo/_runtime/context/types.py
+++ b/marimo/_runtime/context/types.py
@@ -30,9 +30,9 @@ if TYPE_CHECKING:
from marimo._plugins.ui._core.registry import UIElementRegistry
from marimo._runtime import dataflow
from marimo._runtime.cell_lifecycle_registry import CellLifecycleRegistry
+ from marimo._runtime.commands import HTTPRequest
from marimo._runtime.functions import FunctionRegistry
from marimo._runtime.params import CLIArgs, QueryParams
- from marimo._runtime.requests import HTTPRequest
from marimo._runtime.state import State, StateRegistry
from marimo._runtime.virtual_file import VirtualFileRegistry
from marimo._save.stores import Store
diff --git a/marimo/_runtime/marimo_pdb.py b/marimo/_runtime/marimo_pdb.py
index e680c1b165..444a61d657 100644
--- a/marimo/_runtime/marimo_pdb.py
+++ b/marimo/_runtime/marimo_pdb.py
@@ -18,6 +18,7 @@ LOGGER = _loggers.marimo_logger()
def try_restart() -> bool:
+ from marimo._runtime.commands import ExecuteCellsCommand
from marimo._runtime.context import (
ContextNotInitializedError,
get_context,
@@ -25,7 +26,6 @@ def try_restart() -> bool:
from marimo._runtime.context.kernel_context import (
KernelRuntimeContext,
)
- from marimo._runtime.requests import ExecuteMultipleRequest
try:
ctx = get_context()
@@ -38,7 +38,7 @@ def try_restart() -> bool:
# This runs the request and also runs UpdateCellCodes
ctx._kernel.enqueue_control_request(
- ExecuteMultipleRequest(
+ ExecuteCellsCommand(
cell_ids=[ctx.cell_id],
codes=[graph.cells[ctx.cell_id].code],
)
diff --git a/marimo/_runtime/params.py b/marimo/_runtime/params.py
index ad22aac09c..6a7f1906c1 100644
--- a/marimo/_runtime/params.py
+++ b/marimo/_runtime/params.py
@@ -19,7 +19,7 @@ from marimo._messaging.notification import (
from marimo._messaging.notification_utils import broadcast_notification
from marimo._messaging.types import Stream
from marimo._output.rich_help import mddoc
-from marimo._runtime.requests import (
+from marimo._runtime.commands import (
ListOrValue,
Primitive,
SerializedCLIArgs,
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 07403b43b2..09a68cc401 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -101,6 +101,36 @@ from marimo._plugins.ui._core.ui_element import MarimoConvertValueException
from marimo._plugins.ui._impl.anywidget.init import WIDGET_COMM_MANAGER
from marimo._runtime import dataflow, handlers, marimo_pdb, patches
from marimo._runtime.app_meta import AppMeta
+from marimo._runtime.commands import (
+ AppMetadata,
+ ClearCacheCommand,
+ CodeCompletionCommand,
+ CommandMessage,
+ CreateNotebookCommand,
+ DebugCellCommand,
+ DeleteCellCommand,
+ ExecuteCellCommand,
+ ExecuteCellsCommand,
+ ExecuteScratchpadCommand,
+ ExecuteStaleCellsCommand,
+ GetCacheInfoCommand,
+ InstallPackagesCommand,
+ InvokeFunctionCommand,
+ ListDataSourceConnectionCommand,
+ ListSecretKeysCommand,
+ ListSQLTablesCommand,
+ PreviewDatasetColumnCommand,
+ PreviewSQLTableCommand,
+ RefreshSecretsCommand,
+ RenameNotebookCommand,
+ StopKernelCommand,
+ SyncGraphCommand,
+ UpdateCellConfigCommand,
+ UpdateUIElementCommand,
+ UpdateUserConfigCommand,
+ UpdateWidgetModelCommand,
+ ValidateSQLCommand,
+)
from marimo._runtime.context import (
ContextNotInitializedError,
ExecutionContext,
@@ -131,36 +161,6 @@ from marimo._runtime.params import CLIArgs, QueryParams
from marimo._runtime.redirect_streams import redirect_streams
from marimo._runtime.reload.autoreload import ModuleReloader
from marimo._runtime.reload.module_watcher import ModuleWatcher
-from marimo._runtime.requests import (
- AppMetadata,
- ClearCacheRequest,
- CodeCompletionRequest,
- ControlRequest,
- CreationRequest,
- DeleteCellRequest,
- ExecuteMultipleRequest,
- ExecuteScratchpadRequest,
- ExecuteStaleRequest,
- ExecutionRequest,
- FunctionCallRequest,
- GetCacheInfoRequest,
- InstallMissingPackagesRequest,
- ListSecretKeysRequest,
- PdbRequest,
- PreviewDatasetColumnRequest,
- PreviewDataSourceConnectionRequest,
- PreviewSQLTableListRequest,
- PreviewSQLTableRequest,
- RefreshSecretsRequest,
- RenameRequest,
- SetCellConfigRequest,
- SetModelMessageRequest,
- SetUIElementValueRequest,
- SetUserConfigRequest,
- StopRequest,
- SyncGraphRequest,
- ValidateSQLRequest,
-)
from marimo._runtime.runner import cell_runner
from marimo._runtime.runner.hooks import (
ON_FINISH_HOOKS,
@@ -501,7 +501,7 @@ class Kernel:
stderr: Stderr | None,
stdin: Stdin | None,
module: ModuleType,
- enqueue_control_request: Callable[[ControlRequest], None],
+ enqueue_control_request: Callable[[CommandMessage], None],
preparation_hooks: list[PreparationHookType] | None = None,
pre_execution_hooks: list[PreExecutionHookType] | None = None,
post_execution_hooks: list[PostExecutionHookType] | None = None,
@@ -618,7 +618,7 @@ class Kernel:
# not yet been run; these cells are removed when they or their
# descendants are run
self._uninstantiated_execution_requests: dict[
- CellId_t, ExecutionRequest
+ CellId_t, ExecuteCellCommand
] = {}
self.cell_metadata: dict[CellId_t, CellMetadata] = {
cell_id: CellMetadata(config=config)
@@ -693,7 +693,7 @@ class Kernel:
return self.reactive_execution_mode == "lazy"
def _execute_stale_cells_callback(self) -> None:
- return self.enqueue_control_request(ExecuteStaleRequest())
+ return self.enqueue_control_request(ExecuteStaleCellsCommand())
def _update_runtime_from_user_config(self, config: MarimoConfig) -> None:
package_manager = config["package_management"]["manager"]
@@ -748,7 +748,7 @@ class Kernel:
yield
def start_completion_worker(
- self, completion_queue: QueueType[CodeCompletionRequest]
+ self, completion_queue: QueueType[CodeCompletionCommand]
) -> None:
"""Must be called after context is initialized"""
from marimo._runtime.complete import completion_worker
@@ -768,7 +768,7 @@ class Kernel:
@kernel_tracer.start_as_current_span("code_completion")
def code_completion(
- self, request: CodeCompletionRequest, docstrings_limit: int
+ self, request: CodeCompletionCommand, docstrings_limit: int
) -> None:
from marimo._runtime.complete import complete
@@ -1144,8 +1144,8 @@ class Kernel:
def mutate_graph(
self,
- execution_requests: Sequence[ExecutionRequest],
- deletion_requests: Sequence[DeleteCellRequest],
+ execution_requests: Sequence[ExecuteCellCommand],
+ deletion_requests: Sequence[DeleteCellCommand],
cells_starting_stale: set[CellId_t] | None = None,
) -> set[CellId_t]:
"""Add and remove cells to/from the graph.
@@ -1514,7 +1514,7 @@ class Kernel:
self._execute_stale_cells_callback()
@kernel_tracer.start_as_current_span("delete_cell")
- async def delete_cell(self, request: DeleteCellRequest) -> None:
+ async def delete_cell(self, request: DeleteCellCommand) -> None:
"""Delete a cell from kernel and graph."""
cell_id = request.cell_id
if cell_id in self._uninstantiated_execution_requests:
@@ -1553,13 +1553,13 @@ class Kernel:
# Create execution requests for cells to run
execution_requests = [
- ExecutionRequest(cell_id=cell_id, code=cells[cell_id])
+ ExecuteCellCommand(cell_id=cell_id, code=cells[cell_id])
for cell_id in run_ids
]
# Create deletion requests for all cells to delete
deletion_requests = [
- DeleteCellRequest(cell_id=cell_id) for cell_id in all_delete_ids
+ DeleteCellCommand(cell_id=cell_id) for cell_id in all_delete_ids
]
# Clean up uninstantiated requests for deleted cells
@@ -1573,7 +1573,7 @@ class Kernel:
@kernel_tracer.start_as_current_span("run")
async def run(
- self, execution_requests: Sequence[ExecutionRequest]
+ self, execution_requests: Sequence[ExecuteCellCommand]
) -> None:
"""Run cells and their descendants.
@@ -1587,7 +1587,7 @@ class Kernel:
"""
async def _run_with_uninstantiated_requests(
- execution_requests: Sequence[ExecutionRequest],
+ execution_requests: Sequence[ExecuteCellCommand],
) -> None:
if not self._uninstantiated_execution_requests:
await self._run_cells(
@@ -1630,7 +1630,7 @@ class Kernel:
ancestors |= graph.ancestors(er.cell_id)
# We run all uninstantiated ancestors of the requested cells
- previously_uninstantiated_requests: list[ExecutionRequest] = []
+ previously_uninstantiated_requests: list[ExecuteCellCommand] = []
for ancestor_cid in ancestors:
if ancestor_cid in self._uninstantiated_execution_requests:
previously_uninstantiated_requests.append(
@@ -1654,7 +1654,7 @@ class Kernel:
return
# Filter out requests that were created before the last interruption
- filtered_requests: list[ExecutionRequest] = []
+ filtered_requests: list[ExecuteCellCommand] = []
for request in execution_requests:
if request.timestamp < self.last_interrupt_timestamp:
CellNotificationUtils.broadcast_error(
@@ -1770,7 +1770,7 @@ class Kernel:
self.module_watcher.run_is_processed.set()
@kernel_tracer.start_as_current_span("set_cell_config")
- async def set_cell_config(self, request: SetCellConfigRequest) -> None:
+ async def set_cell_config(self, request: UpdateCellConfigCommand) -> None:
"""Update cell configs.
Cells that are enabled (via config) but stale are run as a side-effect.
@@ -1795,12 +1795,12 @@ class Kernel:
await self._run_cells(stale_cells)
@kernel_tracer.start_as_current_span("set_user_config")
- def set_user_config(self, request: SetUserConfigRequest) -> None:
+ def set_user_config(self, request: UpdateUserConfigCommand) -> None:
self._update_runtime_from_user_config(request.config)
@kernel_tracer.start_as_current_span("set_ui_element_value")
async def set_ui_element_value(
- self, request: SetUIElementValueRequest
+ self, request: UpdateUIElementCommand
) -> bool:
"""Set the value of a UI element bound to a global variable.
@@ -1829,7 +1829,7 @@ class Kernel:
if (
child_context.app is not None
and await child_context.app.set_ui_element_value(
- SetUIElementValueRequest(
+ UpdateUIElementCommand(
object_ids=[object_id],
values=[value],
request=request.request,
@@ -1996,14 +1996,14 @@ class Kernel:
@kernel_tracer.start_as_current_span("function_call_request")
async def function_call_request(
- self, request: FunctionCallRequest
+ self, request: InvokeFunctionCommand
) -> tuple[HumanReadableStatus, JSONType, bool]:
"""Execute a function call.
If the function is not found, children contexts are also searched.
Args:
- request (FunctionCallRequest): The function call request.
+ request (InvokeFunctionRequest): The function call request.
Returns:
tuple[HumanReadableStatus, JSONType, bool]: A tuple containing:
@@ -2090,7 +2090,7 @@ class Kernel:
)
@kernel_tracer.start_as_current_span("instantiate")
- async def instantiate(self, request: CreationRequest) -> None:
+ async def instantiate(self, request: CreateNotebookCommand) -> None:
"""Instantiate the kernel with cells and UIElement initial values
During instantiation, UIElements can check for an initial value
@@ -2135,7 +2135,7 @@ class Kernel:
)
def _handle_markdown_cells_on_instantiate(
- self, execution_requests: dict[CellId_t, ExecutionRequest]
+ self, execution_requests: dict[CellId_t, ExecuteCellCommand]
) -> None:
"""Handle markdown cells during kernel-ready initialization.
Mutates the execution_requests to remove markdown cells.
@@ -2221,20 +2221,20 @@ class Kernel:
def request_handler(self) -> RequestHandler:
handler = RequestHandler()
- async def handle_instantiate(request: CreationRequest) -> None:
+ async def handle_instantiate(request: CreateNotebookCommand) -> None:
with http_request_context(request.request):
await self.instantiate(request)
broadcast_notification(CompletedRunNotification())
async def handle_execute_multiple(
- request: ExecuteMultipleRequest,
+ request: ExecuteCellsCommand,
) -> None:
with http_request_context(request.request):
await self.run(request.execution_requests)
broadcast_notification(CompletedRunNotification())
async def handle_sync_graph(
- request: SyncGraphRequest,
+ request: SyncGraphCommand,
) -> None:
with http_request_context(None):
await self.sync_graph(
@@ -2243,32 +2243,34 @@ class Kernel:
broadcast_notification(CompletedRunNotification())
async def handle_execute_scratchpad(
- request: ExecuteScratchpadRequest,
+ request: ExecuteScratchpadCommand,
) -> None:
with http_request_context(request.request):
await self.run_scratchpad(request.code)
broadcast_notification(CompletedRunNotification())
- async def handle_execute_stale(request: ExecuteStaleRequest) -> None:
+ async def handle_execute_stale(
+ request: ExecuteStaleCellsCommand,
+ ) -> None:
with http_request_context(request.request):
await self.run_stale_cells()
broadcast_notification(CompletedRunNotification())
async def handle_set_ui_element_value(
- request: SetUIElementValueRequest,
+ request: UpdateUIElementCommand,
) -> None:
with http_request_context(request.request):
await self.set_ui_element_value(request)
broadcast_notification(CompletedRunNotification())
- async def handle_pdb_request(request: PdbRequest) -> None:
+ async def handle_pdb_request(request: DebugCellCommand) -> None:
await self.pdb_request(request.cell_id)
- async def handle_rename(request: RenameRequest) -> None:
+ async def handle_rename(request: RenameNotebookCommand) -> None:
await self.rename_file(request.filename)
async def handle_receive_model_message(
- request: SetModelMessageRequest,
+ request: UpdateWidgetModelCommand,
) -> None:
buffers = request.buffers or []
buffers_as_bytes = [buffer.encode("utf-8") for buffer in buffers]
@@ -2276,7 +2278,7 @@ class Kernel:
request.model_id, request.message, buffers_as_bytes
)
- async def handle_function_call(request: FunctionCallRequest) -> None:
+ async def handle_function_call(request: InvokeFunctionCommand) -> None:
status, ret, _ = await self.function_call_request(request)
LOGGER.debug("Function returned with status %s", status)
broadcast_notification(
@@ -2288,71 +2290,73 @@ class Kernel:
)
async def handle_set_user_config(
- request: SetUserConfigRequest,
+ request: UpdateUserConfigCommand,
) -> None:
self.set_user_config(request)
async def handle_install_missing_packages(
- request: InstallMissingPackagesRequest,
+ request: InstallPackagesCommand,
) -> None:
await self.packages_callbacks.install_missing_packages(request)
broadcast_notification(CompletedRunNotification())
- async def handle_stop(request: StopRequest) -> None:
+ async def handle_stop(request: StopKernelCommand) -> None:
del request
return None
- handler.register(CreationRequest, handle_instantiate)
- handler.register(DeleteCellRequest, self.delete_cell)
- handler.register(ExecuteMultipleRequest, handle_execute_multiple)
- handler.register(SyncGraphRequest, handle_sync_graph)
- handler.register(ExecuteScratchpadRequest, handle_execute_scratchpad)
- handler.register(ExecuteStaleRequest, handle_execute_stale)
- handler.register(FunctionCallRequest, handle_function_call)
+ handler.register(CreateNotebookCommand, handle_instantiate)
+ handler.register(DeleteCellCommand, self.delete_cell)
+ handler.register(ExecuteCellsCommand, handle_execute_multiple)
+ handler.register(SyncGraphCommand, handle_sync_graph)
+ handler.register(ExecuteScratchpadCommand, handle_execute_scratchpad)
+ handler.register(ExecuteStaleCellsCommand, handle_execute_stale)
+ handler.register(InvokeFunctionCommand, handle_function_call)
+ handler.register(
+ InstallPackagesCommand, handle_install_missing_packages
+ )
+ handler.register(DebugCellCommand, handle_pdb_request)
+ handler.register(RenameNotebookCommand, handle_rename)
+ handler.register(UpdateCellConfigCommand, self.set_cell_config)
+ handler.register(UpdateUIElementCommand, handle_set_ui_element_value)
handler.register(
- InstallMissingPackagesRequest, handle_install_missing_packages
+ UpdateWidgetModelCommand, handle_receive_model_message
)
- handler.register(PdbRequest, handle_pdb_request)
- handler.register(RenameRequest, handle_rename)
- handler.register(SetCellConfigRequest, self.set_cell_config)
- handler.register(SetUIElementValueRequest, handle_set_ui_element_value)
- handler.register(SetModelMessageRequest, handle_receive_model_message)
- handler.register(SetUserConfigRequest, handle_set_user_config)
- handler.register(StopRequest, handle_stop)
+ handler.register(UpdateUserConfigCommand, handle_set_user_config)
+ handler.register(StopKernelCommand, handle_stop)
# Datasets
handler.register(
- PreviewDatasetColumnRequest,
+ PreviewDatasetColumnCommand,
self.datasets_callbacks.preview_dataset_column,
)
handler.register(
- PreviewSQLTableRequest, self.datasets_callbacks.preview_sql_table
+ PreviewSQLTableCommand, self.datasets_callbacks.preview_sql_table
)
handler.register(
- PreviewSQLTableListRequest,
+ ListSQLTablesCommand,
self.datasets_callbacks.preview_sql_table_list,
)
handler.register(
- PreviewDataSourceConnectionRequest,
+ ListDataSourceConnectionCommand,
self.datasets_callbacks.preview_datasource_connection,
)
# SQL
- handler.register(ValidateSQLRequest, self.sql_callbacks.validate_sql)
+ handler.register(ValidateSQLCommand, self.sql_callbacks.validate_sql)
# Secrets
handler.register(
- ListSecretKeysRequest, self.secrets_callbacks.list_secrets
+ ListSecretKeysCommand, self.secrets_callbacks.list_secrets
)
handler.register(
- RefreshSecretsRequest, self.secrets_callbacks.refresh_secrets
+ RefreshSecretsCommand, self.secrets_callbacks.refresh_secrets
)
# Cache
- handler.register(ClearCacheRequest, self.cache_callbacks.clear_cache)
+ handler.register(ClearCacheCommand, self.cache_callbacks.clear_cache)
handler.register(
- GetCacheInfoRequest, self.cache_callbacks.get_cache_info
+ GetCacheInfoCommand, self.cache_callbacks.get_cache_info
)
return handler
- async def handle_message(self, request: ControlRequest) -> None:
+ async def handle_message(self, request: CommandMessage) -> None:
"""Handle a message from the client.
The message is dispatched to the appropriate method based on its type.
@@ -2418,7 +2422,7 @@ class DatasetCallbacks:
@kernel_tracer.start_as_current_span("preview_dataset_column")
async def preview_dataset_column(
- self, request: PreviewDatasetColumnRequest
+ self, request: PreviewDatasetColumnCommand
) -> None:
"""Preview a column of a dataset.
@@ -2494,7 +2498,7 @@ class DatasetCallbacks:
return
@kernel_tracer.start_as_current_span("preview_sql_table")
- async def preview_sql_table(self, request: PreviewSQLTableRequest) -> None:
+ async def preview_sql_table(self, request: PreviewSQLTableCommand) -> None:
"""Get table details for an SQL table.
Args:
@@ -2557,12 +2561,12 @@ class DatasetCallbacks:
@kernel_tracer.start_as_current_span("preview_sql_table_list")
async def preview_sql_table_list(
- self, request: PreviewSQLTableListRequest
+ self, request: ListSQLTablesCommand
) -> None:
"""Get a list of tables from an SQL schema
Args:
- request (PreviewSQLTableListRequest): The request containing:
+ request (ListSQLTablesRequest): The request containing:
- engine: Name of the SQL engine / connection
- database: Name of the database
- schema: Name of the schema
@@ -2616,7 +2620,7 @@ class DatasetCallbacks:
@kernel_tracer.start_as_current_span("preview_datasource_connection")
async def preview_datasource_connection(
- self, request: PreviewDataSourceConnectionRequest
+ self, request: ListDataSourceConnectionCommand
) -> None:
"""Broadcasts a datasource connection for a given engine"""
variable_name = cast(VariableName, request.engine)
@@ -2643,7 +2647,7 @@ class SqlCallbacks:
def __init__(self, kernel: Kernel):
self._kernel = kernel
- async def _validate_sql_query(self, request: ValidateSQLRequest) -> None:
+ async def _validate_sql_query(self, request: ValidateSQLCommand) -> None:
"""Validate an SQL query
This will validate:
@@ -2735,7 +2739,7 @@ class SqlCallbacks:
)
@kernel_tracer.start_as_current_span("validate_sql")
- async def validate_sql(self, request: ValidateSQLRequest) -> None:
+ async def validate_sql(self, request: ValidateSQLCommand) -> None:
"""Validate an SQL query"""
try:
@@ -2754,7 +2758,7 @@ class SecretsCallbacks:
def __init__(self, kernel: Kernel):
self._kernel = kernel
- async def list_secrets(self, request: ListSecretKeysRequest) -> None:
+ async def list_secrets(self, request: ListSecretKeysCommand) -> None:
secrets = get_secret_keys(
self._kernel.user_config, self._kernel._original_environ
)
@@ -2764,7 +2768,7 @@ class SecretsCallbacks:
),
)
- async def refresh_secrets(self, request: RefreshSecretsRequest) -> None:
+ async def refresh_secrets(self, request: RefreshSecretsCommand) -> None:
del request
self._kernel.load_dotenv()
@@ -2875,7 +2879,7 @@ class PackagesCallbacks:
if self.package_manager.should_auto_install():
version = {pkg: "" for pkg in packages}
self._kernel.enqueue_control_request(
- InstallMissingPackagesRequest(
+ InstallPackagesCommand(
manager=self.package_manager.name, versions=version
)
)
@@ -2888,7 +2892,7 @@ class PackagesCallbacks:
)
async def install_missing_packages(
- self, request: InstallMissingPackagesRequest
+ self, request: InstallPackagesCommand
) -> None:
"""Attempts to install packages for modules that cannot be imported
@@ -3062,7 +3066,7 @@ class CacheCallbacks:
def __init__(self, kernel: Kernel):
self._kernel = kernel
- async def clear_cache(self, request: ClearCacheRequest) -> None:
+ async def clear_cache(self, request: ClearCacheCommand) -> None:
del request
from marimo._save.cache import CacheContext
from marimo._save.loaders import BasePersistenceLoader
@@ -3076,7 +3080,7 @@ class CacheCallbacks:
broadcast_notification(CacheClearedNotification(bytes_freed=saved))
- async def get_cache_info(self, request: GetCacheInfoRequest) -> None:
+ async def get_cache_info(self, request: GetCacheInfoCommand) -> None:
del request
from marimo._save.cache import CacheContext
@@ -3108,18 +3112,18 @@ class CacheCallbacks:
class RequestHandler:
def __init__(self) -> None:
self._handlers: dict[
- type[ControlRequest],
- Callable[[ControlRequest], Awaitable[None]],
+ type[CommandMessage],
+ Callable[[CommandMessage], Awaitable[None]],
] = {}
def register(
self,
- request_type: type[ControlRequest],
+ request_type: type[CommandMessage],
handler: Callable[[Any], Awaitable[None]],
) -> None:
self._handlers[request_type] = handler
- async def handle(self, request: ControlRequest) -> None:
+ async def handle(self, request: CommandMessage) -> None:
handler = self._handlers.get(type(request))
if handler:
return await handler(request)
@@ -3127,9 +3131,9 @@ class RequestHandler:
def launch_kernel(
- control_queue: QueueType[ControlRequest],
- set_ui_element_queue: QueueType[SetUIElementValueRequest],
- completion_queue: QueueType[CodeCompletionRequest],
+ control_queue: QueueType[CommandMessage],
+ set_ui_element_queue: QueueType[UpdateUIElementCommand],
+ completion_queue: QueueType[CodeCompletionCommand],
input_queue: QueueType[str],
stream_queue: QueueType[KernelMessage] | None,
socket_addr: tuple[str, int] | None,
@@ -3215,9 +3219,9 @@ def launch_kernel(
user_config["runtime"]["on_cell_change"] = "autorun"
user_config["runtime"]["auto_reload"] = "off"
- def _enqueue_control_request(req: ControlRequest) -> None:
+ def _enqueue_control_request(req: CommandMessage) -> None:
control_queue.put_nowait(req)
- if isinstance(req, SetUIElementValueRequest):
+ if isinstance(req, UpdateUIElementCommand):
set_ui_element_queue.put_nowait(req)
kernel = Kernel(
@@ -3290,7 +3294,7 @@ def launch_kernel(
# 100ms timeout to avoid blocking
# this does not mean ControlRequest will be blocked for 100ms
# but rather background tasks may not start until 100ms have passed
- request: ControlRequest | None = control_queue.get(
+ request: CommandMessage | None = control_queue.get(
timeout=TIMEOUT_S
)
except Empty:
@@ -3303,9 +3307,9 @@ def launch_kernel(
LOGGER.debug("kernel queue.get() failed %s", e)
break
LOGGER.debug("Received control request: %s", request)
- if isinstance(request, StopRequest):
+ if isinstance(request, StopKernelCommand):
break
- elif isinstance(request, SetUIElementValueRequest):
+ elif isinstance(request, UpdateUIElementCommand):
request = ui_element_request_mgr.process_request(request)
if request is not None:
diff --git a/marimo/_runtime/utils/set_ui_element_request_manager.py b/marimo/_runtime/utils/set_ui_element_request_manager.py
index 0eebb1fc29..ae8a7efdb6 100644
--- a/marimo/_runtime/utils/set_ui_element_request_manager.py
+++ b/marimo/_runtime/utils/set_ui_element_request_manager.py
@@ -3,7 +3,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any
-from marimo._runtime.requests import SetUIElementValueRequest
+from marimo._runtime.commands import UpdateUIElementCommand
from marimo._server.types import QueueType
from marimo._types.ids import UIElementId
@@ -15,17 +15,17 @@ class SetUIElementRequestManager:
def __init__(
self,
set_ui_element_queue: (
- QueueType[SetUIElementValueRequest]
- | asyncio.Queue[SetUIElementValueRequest]
+ QueueType[UpdateUIElementCommand]
+ | asyncio.Queue[UpdateUIElementCommand]
),
) -> None:
self._set_ui_element_queue = set_ui_element_queue
self._processed_request_tokens: set[str] = set()
def process_request(
- self, request: SetUIElementValueRequest
- ) -> SetUIElementValueRequest | None:
- request_batch: list[SetUIElementValueRequest] = []
+ self, request: UpdateUIElementCommand
+ ) -> UpdateUIElementCommand | None:
+ request_batch: list[UpdateUIElementCommand] = []
if request.token not in self._processed_request_tokens:
request_batch.append(request)
self._processed_request_tokens.add(request.token)
@@ -44,8 +44,8 @@ class SetUIElementRequestManager:
def _merge_set_ui_element_requests(
self,
- requests: list[SetUIElementValueRequest],
- ) -> SetUIElementValueRequest | None:
+ requests: list[UpdateUIElementCommand],
+ ) -> UpdateUIElementCommand | None:
if not requests:
return None
@@ -54,7 +54,7 @@ class SetUIElementRequestManager:
for ui_id, value in request.ids_and_values:
merged[ui_id] = value
last_request = requests[-1]
- return SetUIElementValueRequest(
+ return UpdateUIElementCommand(
object_ids=list(merged.keys()),
values=list(merged.values()),
token=last_request.token,
diff --git a/marimo/_server/api/endpoints/cache.py b/marimo/_server/api/endpoints/cache.py
index ae973b1e20..303e7033fd 100644
--- a/marimo/_server/api/endpoints/cache.py
+++ b/marimo/_server/api/endpoints/cache.py
@@ -5,10 +5,7 @@ from typing import TYPE_CHECKING
from starlette.authentication import requires
-from marimo._runtime.requests import (
- ClearCacheRequest,
- GetCacheInfoRequest,
-)
+from marimo._runtime.commands import ClearCacheCommand, GetCacheInfoCommand
from marimo._server.api.utils import dispatch_control_request
from marimo._server.models.models import SuccessResponse
from marimo._server.router import APIRouter
@@ -37,7 +34,7 @@ async def clear_cache(request: Request) -> SuccessResponse:
schema:
$ref: "#/components/schemas/SuccessResponse"
"""
- return await dispatch_control_request(request, ClearCacheRequest())
+ return await dispatch_control_request(request, ClearCacheCommand())
@router.post("/info")
@@ -57,4 +54,4 @@ async def get_cache_info(request: Request) -> SuccessResponse:
schema:
$ref: "#/components/schemas/SuccessResponse"
"""
- return await dispatch_control_request(request, GetCacheInfoRequest())
+ return await dispatch_control_request(request, GetCacheInfoCommand())
diff --git a/marimo/_server/api/endpoints/config.py b/marimo/_server/api/endpoints/config.py
index 2af377c719..f1dd3bc466 100644
--- a/marimo/_server/api/endpoints/config.py
+++ b/marimo/_server/api/endpoints/config.py
@@ -13,13 +13,13 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.msgspec_encoder import asdict
from marimo._messaging.notification import MissingPackageAlertNotification
from marimo._runtime.packages.utils import is_python_isolated
-from marimo._runtime.requests import SetUserConfigRequest
from marimo._server.ai.mcp.config import is_mcp_config_empty
from marimo._server.api.deps import AppState
from marimo._server.api.utils import parse_request
from marimo._server.models.models import (
SaveUserConfigurationRequest,
SuccessResponse,
+ UpdateUserConfigRequest,
)
from marimo._server.router import APIRouter
from marimo._server.sessions import send_message_to_consumer
@@ -109,10 +109,9 @@ async def save_user_config(
# Update the kernel's view of the config
# Session could be None if the user is on the home page
- session = app_state.get_current_session()
if session is not None:
session.put_control_request(
- SetUserConfigRequest(config),
+ UpdateUserConfigRequest(config),
from_consumer_id=ConsumerId(
app_state.require_current_session_id()
),
diff --git a/marimo/_server/api/endpoints/datasources.py b/marimo/_server/api/endpoints/datasources.py
index 607450ceac..3b46c7ec07 100644
--- a/marimo/_server/api/endpoints/datasources.py
+++ b/marimo/_server/api/endpoints/datasources.py
@@ -6,14 +6,14 @@ from typing import TYPE_CHECKING
from starlette.authentication import requires
from marimo import _loggers
-from marimo._runtime.requests import (
+from marimo._server.api.utils import dispatch_control_request
+from marimo._server.models.models import (
+ BaseResponse,
+ ListDataSourceConnectionRequest,
+ ListSQLTablesRequest,
PreviewDatasetColumnRequest,
- PreviewDataSourceConnectionRequest,
- PreviewSQLTableListRequest,
PreviewSQLTableRequest,
)
-from marimo._server.api.utils import dispatch_control_request
-from marimo._server.models.models import BaseResponse
from marimo._server.router import APIRouter
if TYPE_CHECKING:
@@ -75,7 +75,7 @@ async def preview_sql_table_list(request: Request) -> BaseResponse:
content:
application/json:
schema:
- $ref: "#/components/schemas/PreviewSQLTableListRequest"
+ $ref: "#/components/schemas/ListSQLTablesRequest"
responses:
200:
description: Preview a list of tables in an SQL schema
@@ -84,7 +84,7 @@ async def preview_sql_table_list(request: Request) -> BaseResponse:
schema:
$ref: "#/components/schemas/SuccessResponse"
"""
- return await dispatch_control_request(request, PreviewSQLTableListRequest)
+ return await dispatch_control_request(request, ListSQLTablesRequest)
@router.post("/preview_datasource_connection")
@@ -95,7 +95,7 @@ async def preview_datasource_connection(request: Request) -> BaseResponse:
content:
application/json:
schema:
- $ref: "#/components/schemas/PreviewDataSourceConnectionRequest"
+ $ref: "#/components/schemas/ListDataSourceConnectionRequest"
responses:
200:
description: Broadcasts a datasource connection
@@ -105,5 +105,5 @@ async def preview_datasource_connection(request: Request) -> BaseResponse:
$ref: "#/components/schemas/SuccessResponse"
"""
return await dispatch_control_request(
- request, PreviewDataSourceConnectionRequest
+ request, ListDataSourceConnectionRequest
)
diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.py
index 6e53d078c3..1b2261f010 100644
--- a/marimo/_server/api/endpoints/editing.py
+++ b/marimo/_server/api/endpoints/editing.py
@@ -6,21 +6,19 @@ from typing import TYPE_CHECKING
from starlette.authentication import requires
from marimo._messaging.notification import UpdateCellIdsNotification
-from marimo._runtime.requests import (
- CodeCompletionRequest,
- DeleteCellRequest,
- InstallMissingPackagesRequest,
- SetCellConfigRequest,
- UpdateCellIdsRequest,
-)
from marimo._server.api.deps import AppState
from marimo._server.api.utils import dispatch_control_request, parse_request
from marimo._server.models.models import (
BaseResponse,
- FormatRequest,
+ CodeCompletionRequest,
+ DeleteCellRequest,
+ FormatCellsRequest,
FormatResponse,
+ InstallPackagesRequest,
StdinRequest,
SuccessResponse,
+ UpdateCellConfigRequest,
+ UpdateCellIdsRequest,
)
from marimo._server.router import APIRouter
from marimo._types.ids import ConsumerId
@@ -112,7 +110,7 @@ async def format_cell(request: Request) -> FormatResponse:
content:
application/json:
schema:
- $ref: "#/components/schemas/FormatRequest"
+ $ref: "#/components/schemas/FormatCellsRequest"
responses:
200:
description: Format code
@@ -121,7 +119,7 @@ async def format_cell(request: Request) -> FormatResponse:
schema:
$ref: "#/components/schemas/FormatResponse"
"""
- body = await parse_request(request, cls=FormatRequest)
+ body = await parse_request(request, cls=FormatCellsRequest)
formatter = DefaultFormatter(line_length=body.line_length)
return FormatResponse(codes=await formatter.format(body.codes))
@@ -135,7 +133,7 @@ async def set_cell_config(request: Request) -> BaseResponse:
content:
application/json:
schema:
- $ref: "#/components/schemas/SetCellConfigRequest"
+ $ref: "#/components/schemas/UpdateCellConfigRequest"
responses:
200:
description: Set the configuration of a cell
@@ -144,7 +142,7 @@ async def set_cell_config(request: Request) -> BaseResponse:
schema:
$ref: "#/components/schemas/SuccessResponse"
"""
- return await dispatch_control_request(request, SetCellConfigRequest)
+ return await dispatch_control_request(request, UpdateCellConfigRequest)
@router.post("/stdin")
@@ -179,7 +177,7 @@ async def install_missing_packages(request: Request) -> BaseResponse:
content:
application/json:
schema:
- $ref: "#/components/schemas/InstallMissingPackagesRequest"
+ $ref: "#/components/schemas/InstallPackagesRequest"
responses:
200:
description: Install missing packages
@@ -188,6 +186,4 @@ async def install_missing_packages(request: Request) -> BaseResponse:
schema:
$ref: "#/components/schemas/SuccessResponse"
"""
- return await dispatch_control_request(
- request, InstallMissingPackagesRequest
- )
+ return await dispatch_control_request(request, InstallPackagesRequest)
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index 5b0e5ee667..24ae11669d 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -10,14 +10,7 @@ from starlette.responses import JSONResponse
from marimo import _loggers
from marimo._messaging.notification import AlertNotification
-from marimo._runtime.requests import (
- ExecuteScratchpadRequest,
- FunctionCallRequest,
- HTTPRequest,
- PdbRequest,
- SetModelMessageRequest,
- SetUIElementValueRequest,
-)
+from marimo._runtime.commands import HTTPRequest
from marimo._server.api.deps import AppState
from marimo._server.api.endpoints.ws.ws_connection_validator import (
FILE_QUERY_PARAM_KEY,
@@ -27,10 +20,15 @@ from marimo._server.api.utils import dispatch_control_request, parse_request
from marimo._server.file_router import MarimoFileKey
from marimo._server.models.models import (
BaseResponse,
- InstantiateRequest,
- RunRequest,
+ DebugCellRequest,
+ ExecuteCellsRequest,
+ ExecuteScratchpadRequest,
+ InstantiateNotebookRequest,
+ InvokeFunctionRequest,
SuccessResponse,
- UpdateComponentValuesRequest,
+ UpdateUIElementRequest,
+ UpdateUIElementValuesRequest,
+ UpdateWidgetModelRequest,
)
from marimo._server.router import APIRouter
from marimo._server.uvicorn_utils import close_uvicorn
@@ -55,7 +53,7 @@ async def set_ui_element_values(
content:
application/json:
schema:
- $ref: "#/components/schemas/UpdateComponentValuesRequest"
+ $ref: "#/components/schemas/UpdateUIElementValuesRequest"
responses:
200:
description: Set UI element values
@@ -65,9 +63,9 @@ async def set_ui_element_values(
$ref: "#/components/schemas/SuccessResponse"
"""
app_state = AppState(request)
- body = await parse_request(request, cls=UpdateComponentValuesRequest)
+ body = await parse_request(request, cls=UpdateUIElementValuesRequest)
app_state.require_current_session().put_control_request(
- SetUIElementValueRequest(
+ UpdateUIElementRequest(
object_ids=body.object_ids,
values=body.values,
token=str(uuid4()),
@@ -89,7 +87,7 @@ async def set_model_values(
content:
application/json:
schema:
- $ref: "#/components/schemas/SetModelMessageRequest"
+ $ref: "#/components/schemas/UpdateWidgetModelRequest"
responses:
200:
description: Set model value
@@ -98,7 +96,7 @@ async def set_model_values(
schema:
$ref: "#/components/schemas/SuccessResponse"
"""
- return await dispatch_control_request(request, SetModelMessageRequest)
+ return await dispatch_control_request(request, UpdateWidgetModelRequest)
@router.post("/instantiate")
@@ -111,7 +109,7 @@ async def instantiate(
content:
application/json:
schema:
- $ref: "#/components/schemas/InstantiateRequest"
+ $ref: "#/components/schemas/InstantiateNotebookRequest"
responses:
200:
description: Instantiate a component
@@ -121,7 +119,7 @@ async def instantiate(
$ref: "#/components/schemas/SuccessResponse"
"""
app_state = AppState(request)
- body = await parse_request(request, cls=InstantiateRequest)
+ body = await parse_request(request, cls=InstantiateNotebookRequest)
app_state.require_current_session().instantiate(
body,
http_request=HTTPRequest.from_request(request),
@@ -140,7 +138,7 @@ async def function_call(
content:
application/json:
schema:
- $ref: "#/components/schemas/FunctionCallRequest"
+ $ref: "#/components/schemas/InvokeFunctionRequest"
responses:
200:
description: Invoke an RPC
@@ -149,7 +147,7 @@ async def function_call(
schema:
$ref: "#/components/schemas/SuccessResponse"
"""
- return await dispatch_control_request(request, FunctionCallRequest)
+ return await dispatch_control_request(request, InvokeFunctionRequest)
@router.post("/interrupt")
@@ -184,7 +182,7 @@ async def run_cell(
content:
application/json:
schema:
- $ref: "#/components/schemas/RunRequest"
+ $ref: "#/components/schemas/ExecuteCellsRequest"
responses:
200:
description: Run a cell. Updates cell code in the kernel if needed; registers new cells for unseen cell IDs. Only allowed in edit mode.
@@ -194,10 +192,10 @@ async def run_cell(
$ref: "#/components/schemas/SuccessResponse"
""" # noqa: E501
app_state = AppState(request)
- body = await parse_request(request, cls=RunRequest)
+ body = await parse_request(request, cls=ExecuteCellsRequest)
body.request = HTTPRequest.from_request(request)
app_state.require_current_session().put_control_request(
- body.as_execution_request(),
+ body.as_command(),
from_consumer_id=ConsumerId(app_state.require_current_session_id()),
)
@@ -238,7 +236,7 @@ async def run_post_mortem(
content:
application/json:
schema:
- $ref: "#/components/schemas/PdbRequest"
+ $ref: "#/components/schemas/DebugCellRequest"
responses:
200:
description: Run a post mortem on the most recent failed cell.
@@ -247,7 +245,7 @@ async def run_post_mortem(
schema:
$ref: "#/components/schemas/SuccessResponse"
""" # noqa: E501
- return await dispatch_control_request(request, PdbRequest)
+ return await dispatch_control_request(request, DebugCellRequest)
@router.post("/restart_session")
diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.py
index 1057d370c2..afeb9eda24 100644
--- a/marimo/_server/api/endpoints/files.py
+++ b/marimo/_server/api/endpoints/files.py
@@ -8,6 +8,7 @@ from starlette.exceptions import HTTPException
from starlette.responses import PlainTextResponse
from marimo import _loggers
+from marimo._runtime.commands import RenameNotebookCommand
from marimo._server.api.deps import AppState
from marimo._server.api.status import HTTPStatus
from marimo._server.api.utils import parse_request
@@ -15,13 +16,14 @@ from marimo._server.models.models import (
BaseResponse,
CopyNotebookRequest,
ReadCodeResponse,
- RenameFileRequest,
+ RenameNotebookRequest,
SaveAppConfigurationRequest,
SaveNotebookRequest,
SuccessResponse,
)
from marimo._server.router import APIRouter
from marimo._types.ids import ConsumerId
+from marimo._utils.async_path import abspath
if TYPE_CHECKING:
from starlette.requests import Request
@@ -74,7 +76,7 @@ async def rename_file(
content:
application/json:
schema:
- $ref: "#/components/schemas/RenameFileRequest"
+ $ref: "#/components/schemas/RenameNotebookRequest"
responses:
200:
description: Rename the current app
@@ -83,11 +85,13 @@ async def rename_file(
schema:
$ref: "#/components/schemas/SuccessResponse"
"""
- body = await parse_request(request, cls=RenameFileRequest)
+ body = await parse_request(request, cls=RenameNotebookRequest)
app_state = AppState(request)
+ # Convert to absolute path
+ command = RenameNotebookCommand(filename=await abspath(body.filename))
app_state.require_current_session().put_control_request(
- body.as_execution_request(),
+ command,
from_consumer_id=ConsumerId(app_state.require_current_session_id()),
)
diff --git a/marimo/_server/api/endpoints/secrets.py b/marimo/_server/api/endpoints/secrets.py
index 2ee25ef626..f48b920d95 100644
--- a/marimo/_server/api/endpoints/secrets.py
+++ b/marimo/_server/api/endpoints/secrets.py
@@ -6,14 +6,15 @@ from typing import TYPE_CHECKING
from starlette.authentication import requires
from marimo import _loggers
-from marimo._runtime.requests import (
- ListSecretKeysRequest,
- RefreshSecretsRequest,
-)
from marimo._secrets.secrets import write_secret
from marimo._server.api.deps import AppState
from marimo._server.api.utils import dispatch_control_request, parse_request
-from marimo._server.models.models import BaseResponse, SuccessResponse
+from marimo._server.models.models import (
+ BaseResponse,
+ ListSecretKeysRequest,
+ RefreshSecretsRequest,
+ SuccessResponse,
+)
from marimo._server.models.secrets import CreateSecretRequest
from marimo._server.router import APIRouter
from marimo._types.ids import ConsumerId
diff --git a/marimo/_server/api/endpoints/sql.py b/marimo/_server/api/endpoints/sql.py
index 7a2ebc3ae1..bfd6b6a803 100644
--- a/marimo/_server/api/endpoints/sql.py
+++ b/marimo/_server/api/endpoints/sql.py
@@ -5,9 +5,8 @@ from typing import TYPE_CHECKING
from starlette.authentication import requires
-from marimo._runtime.requests import ValidateSQLRequest
from marimo._server.api.utils import dispatch_control_request
-from marimo._server.models.models import BaseResponse
+from marimo._server.models.models import BaseResponse, ValidateSQLRequest
from marimo._server.router import APIRouter
if TYPE_CHECKING:
diff --git a/marimo/_server/api/utils.py b/marimo/_server/api/utils.py
index 2c2e8ebdb8..b081c6a202 100644
--- a/marimo/_server/api/utils.py
+++ b/marimo/_server/api/utils.py
@@ -7,9 +7,15 @@ import sys
import webbrowser
from pathlib import Path
from shutil import which
-from typing import TYPE_CHECKING, Optional, TypeVar
+from typing import (
+ TYPE_CHECKING,
+ Optional,
+ Protocol,
+ TypeVar,
+ runtime_checkable,
+)
-from marimo._runtime.requests import ControlRequest
+from marimo._runtime.commands import CommandMessage
from marimo._server.models.models import SuccessResponse
from marimo._types.ids import ConsumerId
from marimo._utils.parse_dataclass import parse_raw
@@ -27,9 +33,16 @@ async def parse_request(
)
+@runtime_checkable
+class RequestAsCommand(Protocol):
+ """Protocol for requests that can be converted to commands."""
+
+ def as_command(self) -> CommandMessage: ...
+
+
async def dispatch_control_request(
request: Request,
- cls: type[ControlRequest] | ControlRequest,
+ cls: type[CommandMessage] | CommandMessage,
) -> SuccessResponse:
"""
Parse a request and dispatch it to the current session.
@@ -41,6 +54,8 @@ async def dispatch_control_request(
body = await parse_request(request, cls)
else:
body = cls
+ if isinstance(body, RequestAsCommand):
+ body = body.as_command()
app_state.require_current_session().put_control_request(
body,
from_consumer_id=ConsumerId(app_state.require_current_session_id()),
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index 38a7b802df..e3cca0c514 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -22,12 +22,12 @@ from marimo._messaging.notification import (
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage
from marimo._output.hypertext import patch_html_for_non_interactive_output
-from marimo._runtime.requests import AppMetadata, SerializedCLIArgs
+from marimo._runtime.commands import AppMetadata, SerializedCLIArgs
from marimo._server.export.exporter import Exporter
from marimo._server.file_router import AppFileRouter
from marimo._server.model import ConnectionState, SessionMode
from marimo._server.models.export import ExportAsHTMLRequest
-from marimo._server.models.models import InstantiateRequest
+from marimo._server.models.models import InstantiateNotebookRequest
from marimo._server.notebook import AppFileManager
from marimo._types.ids import ConsumerId
from marimo._utils.marimo_path import MarimoPath
@@ -343,7 +343,7 @@ async def run_app_until_completion(
# Run the notebook to completion once
session.instantiate(
- InstantiateRequest(object_ids=[], values=[]),
+ InstantiateNotebookRequest(object_ids=[], values=[]),
http_request=None,
)
await instantiated_event.wait()
diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.py
index 51a58a6aab..0266baa8fe 100644
--- a/marimo/_server/models/models.py
+++ b/marimo/_server/models/models.py
@@ -7,23 +7,176 @@ from typing import Any, Literal, Optional
import msgspec
from marimo._ast.cell import CellConfig
-from marimo._runtime.requests import (
- ExecuteMultipleRequest,
+from marimo._runtime.commands import (
+ ClearCacheCommand,
+ CodeCompletionCommand,
+ DebugCellCommand,
+ DeleteCellCommand,
+ ExecuteCellsCommand,
+ ExecuteScratchpadCommand,
+ GetCacheInfoCommand,
HTTPRequest,
- RenameRequest,
+ InstallPackagesCommand,
+ InvokeFunctionCommand,
+ ListDataSourceConnectionCommand,
+ ListSecretKeysCommand,
+ ListSQLTablesCommand,
+ PreviewDatasetColumnCommand,
+ PreviewSQLTableCommand,
+ RefreshSecretsCommand,
+ UpdateCellConfigCommand,
+ UpdateUIElementCommand,
+ UpdateUserConfigCommand,
+ UpdateWidgetModelCommand,
+ ValidateSQLCommand,
)
from marimo._types.ids import CellId_t, UIElementId
-class UpdateComponentValuesRequest(msgspec.Struct, rename="camel"):
+class ListSecretKeysRequest(ListSecretKeysCommand, tag=False):
+ def as_command(self) -> ListSecretKeysCommand:
+ return ListSecretKeysCommand(request_id=self.request_id)
+
+
+class ClearCacheRequest(ClearCacheCommand, tag=False):
+ def as_command(self) -> ClearCacheCommand:
+ return ClearCacheCommand()
+
+
+class GetCacheInfoRequest(GetCacheInfoCommand, tag=False):
+ def as_command(self) -> GetCacheInfoCommand:
+ return GetCacheInfoCommand()
+
+
+class DebugCellRequest(DebugCellCommand, tag=False):
+ def as_command(self) -> DebugCellCommand:
+ return DebugCellCommand(cell_id=self.cell_id, request=self.request)
+
+
+class ExecuteScratchpadRequest(ExecuteScratchpadCommand, tag=False):
+ def as_command(self) -> ExecuteScratchpadCommand:
+ return ExecuteScratchpadCommand(code=self.code, request=self.request)
+
+
+class InvokeFunctionRequest(InvokeFunctionCommand, tag=False):
+ def as_command(self) -> InvokeFunctionCommand:
+ return InvokeFunctionCommand(
+ function_call_id=self.function_call_id,
+ namespace=self.namespace,
+ function_name=self.function_name,
+ args=self.args,
+ )
+
+
+class UpdateUIElementRequest(UpdateUIElementCommand, tag=False):
+ def as_command(self) -> UpdateUIElementCommand:
+ return UpdateUIElementCommand(
+ object_ids=self.object_ids,
+ values=self.values,
+ request=self.request,
+ token=self.token,
+ )
+
+
+class UpdateWidgetModelRequest(UpdateWidgetModelCommand, tag=False):
+ def as_command(self) -> UpdateWidgetModelCommand:
+ return UpdateWidgetModelCommand(
+ model_id=self.model_id,
+ message=self.message,
+ buffers=self.buffers,
+ )
+
+
+class RefreshSecretsRequest(RefreshSecretsCommand, tag=False):
+ def as_command(self) -> RefreshSecretsCommand:
+ return RefreshSecretsCommand()
+
+
+class ListDataSourceConnectionRequest(
+ ListDataSourceConnectionCommand, tag=False
+):
+ def as_command(self) -> ListDataSourceConnectionCommand:
+ return ListDataSourceConnectionCommand(engine=self.engine)
+
+
+class ListSQLTablesRequest(ListSQLTablesCommand, tag=False):
+ def as_command(self) -> ListSQLTablesCommand:
+ return ListSQLTablesCommand(
+ request_id=self.request_id,
+ engine=self.engine,
+ database=self.database,
+ schema=self.schema,
+ )
+
+
+class PreviewDatasetColumnRequest(PreviewDatasetColumnCommand, tag=False):
+ def as_command(self) -> PreviewDatasetColumnCommand:
+ return PreviewDatasetColumnCommand(
+ source_type=self.source_type,
+ source=self.source,
+ table_name=self.table_name,
+ column_name=self.column_name,
+ fully_qualified_table_name=self.fully_qualified_table_name,
+ )
+
+
+class PreviewSQLTableRequest(PreviewSQLTableCommand, tag=False):
+ def as_command(self) -> PreviewSQLTableCommand:
+ return PreviewSQLTableCommand(
+ request_id=self.request_id,
+ engine=self.engine,
+ database=self.database,
+ schema=self.schema,
+ table_name=self.table_name,
+ )
+
+
+class ValidateSQLRequest(ValidateSQLCommand, tag=False):
+ def as_command(self) -> ValidateSQLCommand:
+ return ValidateSQLCommand(
+ query=self.query,
+ only_parse=self.only_parse,
+ engine=self.engine,
+ dialect=self.dialect,
+ request_id=self.request_id,
+ )
+
+
+class UpdateUserConfigRequest(UpdateUserConfigCommand, tag=False):
+ def as_command(self) -> UpdateUserConfigCommand:
+ return UpdateUserConfigCommand(config=self.config)
+
+
+class DeleteCellRequest(DeleteCellCommand, tag=False):
+ def as_command(self) -> DeleteCellCommand:
+ return DeleteCellCommand(cell_id=self.cell_id)
+
+
+class InstallPackagesRequest(InstallPackagesCommand, tag=False):
+ def as_command(self) -> InstallPackagesCommand:
+ return InstallPackagesCommand(
+ manager=self.manager, versions=self.versions
+ )
+
+
+class UpdateCellConfigRequest(UpdateCellConfigCommand, tag=False):
+ def as_command(self) -> UpdateCellConfigCommand:
+ return UpdateCellConfigCommand(configs=self.configs)
+
+
+class CodeCompletionRequest(CodeCompletionCommand, tag=False):
+ def as_command(self) -> CodeCompletionCommand:
+ return CodeCompletionCommand(
+ id=self.id,
+ document=self.document,
+ cell_id=self.cell_id,
+ )
+
+
+class UpdateUIElementValuesRequest(msgspec.Struct, rename="camel"):
object_ids: list[UIElementId]
values: list[Any]
- def zip(
- self,
- ) -> 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), (
@@ -31,7 +184,7 @@ class UpdateComponentValuesRequest(msgspec.Struct, rename="camel"):
)
-class InstantiateRequest(UpdateComponentValuesRequest):
+class InstantiateNotebookRequest(UpdateUIElementValuesRequest):
auto_run: bool = True
@@ -48,7 +201,7 @@ class ErrorResponse(BaseResponse):
message: Optional[str] = None
-class FormatRequest(msgspec.Struct, rename="camel"):
+class FormatCellsRequest(msgspec.Struct, rename="camel"):
codes: dict[CellId_t, str]
line_length: int
@@ -61,14 +214,15 @@ class ReadCodeResponse(msgspec.Struct, rename="camel"):
contents: str
-class RenameFileRequest(msgspec.Struct, rename="camel"):
+class RenameNotebookRequest(msgspec.Struct, rename="camel"):
filename: str
- def as_execution_request(self) -> RenameRequest:
- return RenameRequest(filename=os.path.abspath(self.filename))
+
+class UpdateCellIdsRequest(msgspec.Struct, rename="camel"):
+ cell_ids: list[CellId_t]
-class RunRequest(msgspec.Struct, rename="camel"):
+class ExecuteCellsRequest(msgspec.Struct, rename="camel"):
# ids of cells to run
cell_ids: list[CellId_t]
# code to register/run for each cell
@@ -76,8 +230,8 @@ class RunRequest(msgspec.Struct, rename="camel"):
# incoming request, e.g. from Starlette or FastAPI
request: Optional[HTTPRequest] = None
- def as_execution_request(self) -> ExecuteMultipleRequest:
- return ExecuteMultipleRequest(
+ def as_command(self) -> ExecuteCellsCommand:
+ return ExecuteCellsCommand(
cell_ids=self.cell_ids,
codes=self.codes,
request=self.request,
diff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.py
index 72d248e9fe..79a982bd60 100644
--- a/marimo/_server/session/session_view.py
+++ b/marimo/_server/session/session_view.py
@@ -26,13 +26,13 @@ from marimo._messaging.notification import (
)
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage
-from marimo._runtime.requests import (
- ControlRequest,
- CreationRequest,
- ExecuteMultipleRequest,
- ExecutionRequest,
- SetUIElementValueRequest,
- SyncGraphRequest,
+from marimo._runtime.commands import (
+ CommandMessage,
+ CreateNotebookCommand,
+ ExecuteCellCommand,
+ ExecuteCellsCommand,
+ SyncGraphCommand,
+ UpdateUIElementCommand,
)
from marimo._sql.connection_utils import (
update_table_in_connection,
@@ -123,7 +123,7 @@ class SessionView:
def _add_ui_value(self, name: str, value: Any) -> None:
self.ui_values[name] = value
- def _add_last_run_code(self, req: ExecutionRequest) -> None:
+ def _add_last_run_code(self, req: ExecuteCellCommand) -> None:
self.last_executed_code[req.cell_id] = req.code
def add_raw_notification(self, raw_notification: KernelMessage) -> None:
@@ -131,16 +131,16 @@ class SessionView:
# Type ignore because NotificationMessage is a Union, not a class
self.add_notification(deserialize_kernel_message(raw_notification)) # type: ignore[arg-type]
- def add_control_request(self, request: ControlRequest) -> None:
+ def add_control_request(self, request: CommandMessage) -> None:
self._touch()
- if isinstance(request, SetUIElementValueRequest):
+ if isinstance(request, UpdateUIElementCommand):
for object_id, value in request.ids_and_values:
self._add_ui_value(object_id, value)
- elif isinstance(request, (ExecuteMultipleRequest, SyncGraphRequest)):
+ elif isinstance(request, (ExecuteCellsCommand, SyncGraphCommand)):
for execution_request in request.execution_requests:
self._add_last_run_code(execution_request)
- elif isinstance(request, CreationRequest):
+ elif isinstance(request, CreateNotebookCommand):
for (
object_id,
value,
diff --git a/marimo/_server/sessions/file_change_handler.py b/marimo/_server/sessions/file_change_handler.py
index fd26c01564..056e66e7a2 100644
--- a/marimo/_server/sessions/file_change_handler.py
+++ b/marimo/_server/sessions/file_change_handler.py
@@ -17,7 +17,7 @@ from marimo._messaging.notification import (
UpdateCellCodesNotification,
UpdateCellIdsNotification,
)
-from marimo._runtime.requests import DeleteCellRequest, SyncGraphRequest
+from marimo._runtime.commands import DeleteCellCommand, SyncGraphCommand
from marimo._server.model import SessionMode
from marimo._types.ids import CellId_t
from marimo._utils import async_path
@@ -101,7 +101,7 @@ class EditModeReloadStrategy(ReloadStrategy):
cells = dict(zip(cell_ids, codes))
session.put_control_request(
- SyncGraphRequest(
+ SyncGraphCommand(
cells=cells,
run_ids=changed_cell_ids_list,
delete_ids=list(deleted),
@@ -112,7 +112,7 @@ class EditModeReloadStrategy(ReloadStrategy):
# Just send deletes and code updates
for to_delete in deleted:
session.put_control_request(
- DeleteCellRequest(cell_id=to_delete),
+ DeleteCellCommand(cell_id=to_delete),
from_consumer_id=None,
)
if cell_ids:
diff --git a/marimo/_server/sessions/managers.py b/marimo/_server/sessions/managers.py
index 5114b6a11a..7dfc26a9ae 100644
--- a/marimo/_server/sessions/managers.py
+++ b/marimo/_server/sessions/managers.py
@@ -24,8 +24,8 @@ from marimo._config.manager import MarimoConfigReader
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._messaging.types import KernelMessage
from marimo._output.formatters.formatters import register_formatters
-from marimo._runtime import requests, runtime
-from marimo._runtime.requests import AppMetadata
+from marimo._runtime import commands, runtime
+from marimo._runtime.commands import AppMetadata
from marimo._server.model import SessionMode
from marimo._server.sessions.types import KernelManager, QueueManager
from marimo._server.types import ProcessLike
@@ -45,22 +45,22 @@ class QueueManagerImpl(QueueManager):
# Control messages for the kernel (run, set UI element, set config, etc
# ) are sent through the control queue
self.control_queue: Union[
- MPQueue[requests.ControlRequest],
- queue.Queue[requests.ControlRequest],
+ MPQueue[commands.CommandMessage],
+ queue.Queue[commands.CommandMessage],
] = context.Queue() if context is not None else queue.Queue()
# Set UI element queues are stored in both the control queue and
# this queue, so that the backend can merge/batch set-ui-element
# requests.
self.set_ui_element_queue: Union[
- MPQueue[requests.SetUIElementValueRequest],
- queue.Queue[requests.SetUIElementValueRequest],
+ MPQueue[commands.UpdateUIElementCommand],
+ queue.Queue[commands.UpdateUIElementCommand],
] = context.Queue() if context is not None else queue.Queue()
# Code completion requests are sent through a separate queue
self.completion_queue: Union[
- MPQueue[requests.CodeCompletionRequest],
- queue.Queue[requests.CodeCompletionRequest],
+ MPQueue[commands.CodeCompletionCommand],
+ queue.Queue[commands.CodeCompletionCommand],
] = context.Queue() if context is not None else queue.Queue()
self.win32_interrupt_queue: (
@@ -96,7 +96,7 @@ class QueueManagerImpl(QueueManager):
else:
# kernel thread cleans up read/write conn and IOloop handler on
# exit; we don't join the thread because we don't want to block
- self.control_queue.put(requests.StopRequest())
+ self.control_queue.put(commands.StopKernelCommand())
if isinstance(self.set_ui_element_queue, MPQueue):
self.set_ui_element_queue.cancel_join_thread()
@@ -115,14 +115,14 @@ class QueueManagerImpl(QueueManager):
self.win32_interrupt_queue.cancel_join_thread()
self.win32_interrupt_queue.close()
- def put_control_request(self, request: requests.ControlRequest) -> None:
+ def put_control_request(self, request: commands.CommandMessage) -> None:
"""Put a control request in the control queue."""
self.control_queue.put(request)
- if isinstance(request, requests.SetUIElementValueRequest):
+ if isinstance(request, commands.UpdateUIElementCommand):
self.set_ui_element_queue.put(request)
def put_completion_request(
- self, request: requests.CodeCompletionRequest
+ self, request: commands.CodeCompletionCommand
) -> None:
"""Put a code completion request in the completion queue."""
self.completion_queue.put(request)
@@ -302,11 +302,15 @@ class KernelManagerImpl(KernelManager):
if self.kernel_task.is_alive():
# We don't join the kernel thread because we don't want to server
# to block on it finishing
- self.queue_manager.put_control_request(requests.StopRequest())
+ self.queue_manager.put_control_request(
+ commands.StopKernelCommand()
+ )
else:
# otherwise we have something that is `ProcessLike`
if self.profile_path is not None and self.kernel_task.is_alive():
- self.queue_manager.put_control_request(requests.StopRequest())
+ self.queue_manager.put_control_request(
+ commands.StopKernelCommand()
+ )
# Hack: Wait for kernel to exit and write out profile;
# joining the process hangs, but not sure why.
print_(
diff --git a/marimo/_server/sessions/session.py b/marimo/_server/sessions/session.py
index 7b86630a66..6066a0fa71 100644
--- a/marimo/_server/sessions/session.py
+++ b/marimo/_server/sessions/session.py
@@ -19,19 +19,19 @@ from marimo._messaging.notification import (
)
from marimo._messaging.serde import serialize_kernel_message
from marimo._messaging.types import KernelMessage
-from marimo._runtime import requests
-from marimo._runtime.requests import (
+from marimo._runtime import commands
+from marimo._runtime.commands import (
AppMetadata,
- CreationRequest,
- ExecuteMultipleRequest,
- ExecutionRequest,
+ CreateNotebookCommand,
+ ExecuteCellCommand,
+ ExecuteCellsCommand,
HTTPRequest,
- SetUIElementValueRequest,
- SyncGraphRequest,
+ SyncGraphCommand,
+ UpdateUIElementCommand,
)
from marimo._server.consumer import SessionConsumer
from marimo._server.model import ConnectionState, SessionMode
-from marimo._server.models.models import InstantiateRequest
+from marimo._server.models.models import InstantiateNotebookRequest
from marimo._server.notebook import AppFileManager
from marimo._server.session.session_view import SessionView
from marimo._server.sessions.events import SessionEventBus
@@ -240,15 +240,15 @@ class SessionImpl(Session):
def put_control_request(
self,
- request: requests.ControlRequest,
+ request: commands.CommandMessage,
from_consumer_id: Optional[ConsumerId],
) -> None:
"""Put a control request in the control queue."""
self._queue_manager.put_control_request(request)
# Propagate the control request to the room
- if isinstance(request, (ExecuteMultipleRequest, SyncGraphRequest)):
- if isinstance(request, ExecuteMultipleRequest):
+ if isinstance(request, (ExecuteCellsCommand, SyncGraphCommand)):
+ if isinstance(request, ExecuteCellsCommand):
cell_ids = request.cell_ids
codes = request.codes
else:
@@ -273,7 +273,7 @@ class SessionImpl(Session):
self.session_view.add_control_request(request)
def put_completion_request(
- self, request: requests.CodeCompletionRequest
+ self, request: commands.CodeCompletionCommand
) -> None:
"""Put a code completion request in the completion queue."""
self._queue_manager.completion_queue.put(request)
@@ -363,13 +363,13 @@ class SessionImpl(Session):
def instantiate(
self,
- request: InstantiateRequest,
+ request: InstantiateNotebookRequest,
*,
http_request: Optional[HTTPRequest],
) -> None:
"""Instantiate the app."""
execution_requests = tuple(
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id=cell_data.cell_id,
code=cell_data.code,
request=http_request,
@@ -378,9 +378,9 @@ class SessionImpl(Session):
)
self.put_control_request(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=execution_requests,
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=UpdateUIElementCommand(
object_ids=request.object_ids,
values=request.values,
token=str(uuid4()),
diff --git a/marimo/_server/sessions/session_manager.py b/marimo/_server/sessions/session_manager.py
index 3f98506245..79bc5ad94d 100644
--- a/marimo/_server/sessions/session_manager.py
+++ b/marimo/_server/sessions/session_manager.py
@@ -14,7 +14,7 @@ from typing import TYPE_CHECKING, Optional, TypeVar
from marimo import _loggers
from marimo._config.manager import MarimoConfigManager
-from marimo._runtime.requests import (
+from marimo._runtime.commands import (
SerializedCLIArgs,
SerializedQueryParams,
)
@@ -166,7 +166,7 @@ class SessionManager:
)
# Create the session
- from marimo._runtime.requests import AppMetadata
+ from marimo._runtime.commands import AppMetadata
extensions: list[SessionExtension] = [
RecentsTrackerListener(self.recents)
diff --git a/marimo/_server/sessions/types.py b/marimo/_server/sessions/types.py
index 9ffca666da..348a1f7588 100644
--- a/marimo/_server/sessions/types.py
+++ b/marimo/_server/sessions/types.py
@@ -18,7 +18,7 @@ if TYPE_CHECKING:
from marimo._config.manager import MarimoConfigManager
from marimo._messaging.notification import NotificationMessage
from marimo._messaging.types import KernelMessage
- from marimo._runtime import requests
+ from marimo._runtime import commands
from marimo._server.consumer import SessionConsumer
from marimo._server.model import (
ConnectionState,
@@ -34,9 +34,9 @@ if TYPE_CHECKING:
class QueueManager(Protocol):
"""Protocol for queue management."""
- control_queue: QueueType[requests.ControlRequest]
- set_ui_element_queue: QueueType[requests.SetUIElementValueRequest]
- completion_queue: QueueType[requests.CodeCompletionRequest]
+ control_queue: QueueType[commands.CommandMessage]
+ set_ui_element_queue: QueueType[commands.UpdateUIElementCommand]
+ completion_queue: QueueType[commands.CodeCompletionCommand]
input_queue: QueueType[str]
stream_queue: Optional[QueueType[Union[KernelMessage, None]]]
win32_interrupt_queue: QueueType[bool] | None
@@ -45,12 +45,12 @@ class QueueManager(Protocol):
"""Close all queues."""
...
- def put_control_request(self, request: requests.ControlRequest) -> None:
+ def put_control_request(self, request: commands.CommandMessage) -> None:
"""Put a control request in the control queue."""
...
def put_completion_request(
- self, request: requests.CodeCompletionRequest
+ self, request: commands.CodeCompletionCommand
) -> None:
"""Put a code completion request in the completion queue."""
...
@@ -142,14 +142,14 @@ class Session(Protocol):
def put_control_request(
self,
- request: requests.ControlRequest,
+ request: commands.CommandMessage,
from_consumer_id: Optional[ConsumerId],
) -> None:
"""Put a control request in the control queue."""
...
def put_completion_request(
- self, request: requests.CodeCompletionRequest
+ self, request: commands.CodeCompletionCommand
) -> None:
"""Put a code completion request in the completion queue."""
...
@@ -188,7 +188,7 @@ class Session(Protocol):
self,
request: Any,
*,
- http_request: Optional[requests.HTTPRequest],
+ http_request: Optional[commands.HTTPRequest],
) -> None:
"""Instantiate the app."""
...
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index bd6ba8671e..dad180dbe4 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -15,7 +15,7 @@ from marimo._config.manager import get_default_config_manager
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._mcp.server.main import setup_mcp_server
from marimo._messaging.notification import StartupLogsNotification
-from marimo._runtime.requests import SerializedCLIArgs
+from marimo._runtime.commands import SerializedCLIArgs
from marimo._server.file_router import AppFileRouter
from marimo._server.lsp import CompositeLspServer, NoopLspServer
from marimo._server.main import create_starlette_app
diff --git a/marimo/_utils/dataclass_to_openapi.py b/marimo/_utils/dataclass_to_openapi.py
index faac7dd4b6..66ff0b8606 100644
--- a/marimo/_utils/dataclass_to_openapi.py
+++ b/marimo/_utils/dataclass_to_openapi.py
@@ -33,7 +33,7 @@ import msgspec.json
class PythonTypeToOpenAPI:
- def __init__(self, name_overrides: dict[Any, str], camel_case: bool):
+ def __init__(self, *, name_overrides: dict[Any, str], camel_case: bool):
self.name_overrides = name_overrides
self.camel_case = camel_case
self.optional_name_overrides = {
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index c798bd3eca..b4aca18315 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -348,14 +348,14 @@ components:
title: CellConfig
type: object
CellNotification:
- description: "Op to transition a cell.\n\n A CellNotification's data has some optional\
- \ fields:\n\n output - a CellOutput\n console - a CellOutput\
- \ (console msg to append), or a list of\n CellOutputs\n\
- \ status - execution status\n stale_inputs - whether the cell\
- \ has stale inputs (variables, modules, ...)\n run_id - the run\
- \ associated with this cell.\n serialization - the serialization status\
- \ of the cell\n\n Omitting a field means that its value should be unchanged!\n\
- \n And one required field:\n\n cell_id - the cell id"
+ description: "Op to transition a cell.\n\n A CellNotification's data has\
+ \ some optional fields:\n\n output - a CellOutput\n console \
+ \ - a CellOutput (console msg to append), or a list of\n \
+ \ CellOutputs\n status - execution status\n stale_inputs\
+ \ - whether the cell has stale inputs (variables, modules, ...)\n run_id\
+ \ - the run associated with this cell.\n serialization - the serialization\
+ \ status of the cell\n\n Omitting a field means that its value should be\
+ \ unchanged!\n\n And one required field:\n\n cell_id - the cell id"
properties:
cell_id:
type: string
@@ -558,11 +558,38 @@ components:
- messages
title: ChatRequest
type: object
+ ClearCacheCommand:
+ properties:
+ type:
+ enum:
+ - clear-cache
+ required:
+ - type
+ title: ClearCacheCommand
+ type: object
ClearCacheRequest:
properties: {}
required: []
title: ClearCacheRequest
type: object
+ CodeCompletionCommand:
+ properties:
+ cellId:
+ type: string
+ document:
+ type: string
+ id:
+ type: string
+ type:
+ enum:
+ - code-completion
+ required:
+ - type
+ - id
+ - document
+ - cellId
+ title: CodeCompletionCommand
+ type: object
CodeCompletionRequest:
properties:
cellId:
@@ -753,6 +780,31 @@ components:
- destination
title: CopyNotebookRequest
type: object
+ CreateNotebookCommand:
+ properties:
+ autoRun:
+ type: boolean
+ executionRequests:
+ items:
+ $ref: '#/components/schemas/ExecuteCellCommand'
+ type: array
+ request:
+ anyOf:
+ - $ref: '#/components/schemas/HTTPRequest'
+ - type: 'null'
+ default: null
+ setUiElementValueRequest:
+ $ref: '#/components/schemas/UpdateUIElementCommand'
+ type:
+ enum:
+ - create-notebook
+ required:
+ - type
+ - executionRequests
+ - setUiElementValueRequest
+ - autoRun
+ title: CreateNotebookCommand
+ type: object
CreateSecretRequest:
properties:
key:
@@ -1070,6 +1122,48 @@ components:
required: []
title: DatasourcesConfig
type: object
+ DebugCellCommand:
+ properties:
+ cellId:
+ type: string
+ request:
+ anyOf:
+ - $ref: '#/components/schemas/HTTPRequest'
+ - type: 'null'
+ default: null
+ type:
+ enum:
+ - debug-cell
+ required:
+ - type
+ - cellId
+ title: DebugCellCommand
+ type: object
+ DebugCellRequest:
+ properties:
+ cellId:
+ type: string
+ request:
+ anyOf:
+ - $ref: '#/components/schemas/HTTPRequest'
+ - type: 'null'
+ default: null
+ required:
+ - cellId
+ title: DebugCellRequest
+ type: object
+ DeleteCellCommand:
+ properties:
+ cellId:
+ type: string
+ type:
+ enum:
+ - delete-cell
+ required:
+ - type
+ - cellId
+ title: DeleteCellCommand
+ type: object
DeleteCellRequest:
properties:
cellId:
@@ -1191,7 +1285,29 @@ components:
- theme
title: DisplayConfig
type: object
- ExecuteMultipleRequest:
+ ExecuteCellCommand:
+ properties:
+ cellId:
+ type: string
+ code:
+ type: string
+ request:
+ anyOf:
+ - $ref: '#/components/schemas/HTTPRequest'
+ - type: 'null'
+ default: null
+ timestamp:
+ type: number
+ type:
+ enum:
+ - execute-cell
+ required:
+ - type
+ - cellId
+ - code
+ title: ExecuteCellCommand
+ type: object
+ ExecuteCellsCommand:
properties:
cellIds:
items:
@@ -1208,38 +1324,54 @@ components:
default: null
timestamp:
type: number
+ type:
+ enum:
+ - execute-cells
required:
+ - type
- cellIds
- codes
- title: ExecuteMultipleRequest
+ title: ExecuteCellsCommand
type: object
- ExecuteScratchpadRequest:
+ ExecuteCellsRequest:
properties:
- code:
- type: string
+ cellIds:
+ items:
+ type: string
+ type: array
+ codes:
+ items:
+ type: string
+ type: array
request:
anyOf:
- $ref: '#/components/schemas/HTTPRequest'
- type: 'null'
default: null
required:
- - code
- title: ExecuteScratchpadRequest
+ - cellIds
+ - codes
+ title: ExecuteCellsRequest
type: object
- ExecuteStaleRequest:
+ ExecuteScratchpadCommand:
properties:
+ code:
+ type: string
request:
anyOf:
- $ref: '#/components/schemas/HTTPRequest'
- type: 'null'
default: null
- required: []
- title: ExecuteStaleRequest
+ type:
+ enum:
+ - execute-scratchpad
+ required:
+ - type
+ - code
+ title: ExecuteScratchpadCommand
type: object
- ExecutionRequest:
+ ExecuteScratchpadRequest:
properties:
- cellId:
- type: string
code:
type: string
request:
@@ -1247,12 +1379,23 @@ components:
- $ref: '#/components/schemas/HTTPRequest'
- type: 'null'
default: null
- timestamp:
- type: number
required:
- - cellId
- code
- title: ExecutionRequest
+ title: ExecuteScratchpadRequest
+ type: object
+ ExecuteStaleCellsCommand:
+ properties:
+ request:
+ anyOf:
+ - $ref: '#/components/schemas/HTTPRequest'
+ - type: 'null'
+ default: null
+ type:
+ enum:
+ - execute-stale-cells
+ required:
+ - type
+ title: ExecuteStaleCellsCommand
type: object
ExportAsHTMLRequest:
properties:
@@ -1562,7 +1705,7 @@ components:
- cell_id
title: FocusCellNotification
type: object
- FormatRequest:
+ FormatCellsRequest:
properties:
codes:
additionalProperties:
@@ -1573,7 +1716,7 @@ components:
required:
- codes
- lineLength
- title: FormatRequest
+ title: FormatCellsRequest
type: object
FormatResponse:
properties:
@@ -1595,23 +1738,6 @@ components:
- line_length
title: FormattingConfig
type: object
- FunctionCallRequest:
- properties:
- args:
- type: object
- functionCallId:
- type: string
- functionName:
- type: string
- namespace:
- type: string
- required:
- - functionCallId
- - namespace
- - functionName
- - args
- title: FunctionCallRequest
- type: object
FunctionCallResultNotification:
description: Result of calling a function.
properties:
@@ -1630,6 +1756,15 @@ components:
- status
title: FunctionCallResultNotification
type: object
+ GetCacheInfoCommand:
+ properties:
+ type:
+ enum:
+ - get-cache-info
+ required:
+ - type
+ title: GetCacheInfoCommand
+ type: object
GetCacheInfoRequest:
properties: {}
required: []
@@ -1661,9 +1796,12 @@ components:
title: GoogleAiConfig
type: object
HTTPRequest:
+ description: 'A class that mimics the Request object from Starlette or FastAPI.
+
+
+ It is a subset and pickle-able version of the Request object.'
properties:
- baseUrl:
- additionalProperties: {}
+ base_url:
type: object
cookies:
additionalProperties:
@@ -1674,30 +1812,28 @@ components:
type: string
type: object
meta:
- additionalProperties: {}
type: object
- pathParams:
- additionalProperties: {}
+ path_params:
type: object
- queryParams:
+ query_params:
additionalProperties:
items:
type: string
type: array
type: object
url:
- additionalProperties: {}
type: object
user: {}
required:
- url
- - baseUrl
+ - base_url
- headers
- - queryParams
- - pathParams
+ - query_params
+ - path_params
- cookies
- meta
- user
+ title: HTTPRequest
type: object
HumanReadableStatus:
description: Human-readable status.
@@ -1737,7 +1873,24 @@ components:
- msg
title: ImportStarError
type: object
- InstallMissingPackagesRequest:
+ InstallPackagesCommand:
+ properties:
+ manager:
+ type: string
+ type:
+ enum:
+ - install-packages
+ versions:
+ additionalProperties:
+ type: string
+ type: object
+ required:
+ - type
+ - manager
+ - versions
+ title: InstallPackagesCommand
+ type: object
+ InstallPackagesRequest:
properties:
manager:
type: string
@@ -1748,7 +1901,7 @@ components:
required:
- manager
- versions
- title: InstallMissingPackagesRequest
+ title: InstallPackagesRequest
type: object
InstallingPackageAlertNotification:
properties:
@@ -1783,7 +1936,7 @@ components:
- packages
title: InstallingPackageAlertNotification
type: object
- InstantiateRequest:
+ InstantiateNotebookRequest:
properties:
autoRun:
default: true
@@ -1797,7 +1950,7 @@ components:
required:
- objectIds
- values
- title: InstantiateRequest
+ title: InstantiateNotebookRequest
type: object
InterruptedNotification:
description: Written when the kernel is interrupted by the user.
@@ -1838,6 +1991,44 @@ components:
- result
title: InvokeAiToolResponse
type: object
+ InvokeFunctionCommand:
+ properties:
+ args:
+ type: object
+ functionCallId:
+ type: string
+ functionName:
+ type: string
+ namespace:
+ type: string
+ type:
+ enum:
+ - invoke-function
+ required:
+ - type
+ - functionCallId
+ - namespace
+ - functionName
+ - args
+ title: InvokeFunctionCommand
+ type: object
+ InvokeFunctionRequest:
+ properties:
+ args:
+ type: object
+ functionCallId:
+ type: string
+ functionName:
+ type: string
+ namespace:
+ type: string
+ required:
+ - functionCallId
+ - namespace
+ - functionName
+ - args
+ title: InvokeFunctionRequest
+ type: object
KernelCapabilitiesNotification:
properties:
basedpyright:
@@ -1948,6 +2139,59 @@ components:
type: object
KnownUnions:
properties:
+ command:
+ anyOf:
+ - $ref: '#/components/schemas/CreateNotebookCommand'
+ - $ref: '#/components/schemas/RenameNotebookCommand'
+ - $ref: '#/components/schemas/ExecuteCellsCommand'
+ - $ref: '#/components/schemas/ExecuteScratchpadCommand'
+ - $ref: '#/components/schemas/ExecuteStaleCellsCommand'
+ - $ref: '#/components/schemas/DebugCellCommand'
+ - $ref: '#/components/schemas/DeleteCellCommand'
+ - $ref: '#/components/schemas/SyncGraphCommand'
+ - $ref: '#/components/schemas/UpdateCellConfigCommand'
+ - $ref: '#/components/schemas/InstallPackagesCommand'
+ - $ref: '#/components/schemas/UpdateUIElementCommand'
+ - $ref: '#/components/schemas/UpdateWidgetModelCommand'
+ - $ref: '#/components/schemas/InvokeFunctionCommand'
+ - $ref: '#/components/schemas/UpdateUserConfigCommand'
+ - $ref: '#/components/schemas/PreviewDatasetColumnCommand'
+ - $ref: '#/components/schemas/PreviewSQLTableCommand'
+ - $ref: '#/components/schemas/ListSQLTablesCommand'
+ - $ref: '#/components/schemas/ValidateSQLCommand'
+ - $ref: '#/components/schemas/ListDataSourceConnectionCommand'
+ - $ref: '#/components/schemas/ListSecretKeysCommand'
+ - $ref: '#/components/schemas/RefreshSecretsCommand'
+ - $ref: '#/components/schemas/ClearCacheCommand'
+ - $ref: '#/components/schemas/GetCacheInfoCommand'
+ - $ref: '#/components/schemas/StopKernelCommand'
+ discriminator:
+ mapping:
+ clear-cache: '#/components/schemas/ClearCacheCommand'
+ create-notebook: '#/components/schemas/CreateNotebookCommand'
+ debug-cell: '#/components/schemas/DebugCellCommand'
+ delete-cell: '#/components/schemas/DeleteCellCommand'
+ execute-cells: '#/components/schemas/ExecuteCellsCommand'
+ execute-scratchpad: '#/components/schemas/ExecuteScratchpadCommand'
+ execute-stale-cells: '#/components/schemas/ExecuteStaleCellsCommand'
+ get-cache-info: '#/components/schemas/GetCacheInfoCommand'
+ install-packages: '#/components/schemas/InstallPackagesCommand'
+ invoke-function: '#/components/schemas/InvokeFunctionCommand'
+ list-data-source-connection: '#/components/schemas/ListDataSourceConnectionCommand'
+ list-secret-keys: '#/components/schemas/ListSecretKeysCommand'
+ list-sql-tables: '#/components/schemas/ListSQLTablesCommand'
+ preview-dataset-column: '#/components/schemas/PreviewDatasetColumnCommand'
+ preview-sql-table: '#/components/schemas/PreviewSQLTableCommand'
+ refresh-secrets: '#/components/schemas/RefreshSecretsCommand'
+ rename-notebook: '#/components/schemas/RenameNotebookCommand'
+ stop-kernel: '#/components/schemas/StopKernelCommand'
+ sync-graph: '#/components/schemas/SyncGraphCommand'
+ update-cell-config: '#/components/schemas/UpdateCellConfigCommand'
+ update-ui-element: '#/components/schemas/UpdateUIElementCommand'
+ update-user-config: '#/components/schemas/UpdateUserConfigCommand'
+ update-widget-model: '#/components/schemas/UpdateWidgetModelCommand'
+ validate-sql: '#/components/schemas/ValidateSQLCommand'
+ propertyName: type
data_type:
enum:
- boolean
@@ -2062,6 +2306,7 @@ components:
propertyName: op
required:
- notification
+ - command
- error
- data_type
title: KnownUnions
@@ -2090,6 +2335,27 @@ components:
- data
title: LayoutConfig
type: object
+ ListDataSourceConnectionCommand:
+ description: Fetch a datasource connection
+ properties:
+ engine:
+ type: string
+ type:
+ enum:
+ - list-data-source-connection
+ required:
+ - type
+ - engine
+ title: ListDataSourceConnectionCommand
+ type: object
+ ListDataSourceConnectionRequest:
+ properties:
+ engine:
+ type: string
+ required:
+ - engine
+ title: ListDataSourceConnectionRequest
+ type: object
ListPackagesResponse:
properties:
packages:
@@ -2100,26 +2366,77 @@ components:
- packages
title: ListPackagesResponse
type: object
- ListSecretKeysRequest:
+ ListSQLTablesCommand:
+ description: Preview list of tables in an SQL schema
properties:
+ database:
+ type: string
+ engine:
+ type: string
requestId:
type: string
+ schema:
+ type: string
+ type:
+ enum:
+ - list-sql-tables
required:
+ - type
- requestId
- title: ListSecretKeysRequest
+ - engine
+ - database
+ - schema
+ title: ListSQLTablesCommand
type: object
- ListSecretKeysResponse:
+ ListSQLTablesRequest:
properties:
- keys:
- items:
- $ref: '#/components/schemas/SecretKeysWithProvider'
- type: array
+ database:
+ type: string
+ engine:
+ type: string
+ requestId:
+ type: string
+ schema:
+ type: string
required:
- - keys
- title: ListSecretKeysResponse
- type: object
- MCPConfig:
- description: 'Configuration for MCP servers
+ - requestId
+ - engine
+ - database
+ - schema
+ title: ListSQLTablesRequest
+ type: object
+ ListSecretKeysCommand:
+ properties:
+ requestId:
+ type: string
+ type:
+ enum:
+ - list-secret-keys
+ required:
+ - type
+ - requestId
+ title: ListSecretKeysCommand
+ type: object
+ ListSecretKeysRequest:
+ properties:
+ requestId:
+ type: string
+ required:
+ - requestId
+ title: ListSecretKeysRequest
+ type: object
+ ListSecretKeysResponse:
+ properties:
+ keys:
+ items:
+ $ref: '#/components/schemas/SecretKeysWithProvider'
+ type: array
+ required:
+ - keys
+ title: ListSecretKeysResponse
+ type: object
+ MCPConfig:
+ description: 'Configuration for MCP servers
Note: the field name `mcpServers` is camelCased to match MCP server
@@ -2560,27 +2877,35 @@ components:
- success
title: PackageOperationResponse
type: object
- PdbRequest:
+ PreviewDatasetColumnCommand:
properties:
- cellId:
+ columnName:
type: string
- request:
+ fullyQualifiedTableName:
anyOf:
- - $ref: '#/components/schemas/HTTPRequest'
+ - type: string
- type: 'null'
default: null
- required:
- - cellId
- title: PdbRequest
- type: object
- PreviewDataSourceConnectionRequest:
- description: Fetch a datasource connection
- properties:
- engine:
+ source:
type: string
+ sourceType:
+ enum:
+ - catalog
+ - connection
+ - duckdb
+ - local
+ tableName:
+ type: string
+ type:
+ enum:
+ - preview-dataset-column
required:
- - engine
- title: PreviewDataSourceConnectionRequest
+ - type
+ - sourceType
+ - source
+ - tableName
+ - columnName
+ title: PreviewDatasetColumnCommand
type: object
PreviewDatasetColumnRequest:
properties:
@@ -2608,8 +2933,8 @@ components:
- columnName
title: PreviewDatasetColumnRequest
type: object
- PreviewSQLTableListRequest:
- description: Preview list of tables in an SQL schema
+ PreviewSQLTableCommand:
+ description: Preview table details in an SQL database
properties:
database:
type: string
@@ -2619,15 +2944,21 @@ components:
type: string
schema:
type: string
+ tableName:
+ type: string
+ type:
+ enum:
+ - preview-sql-table
required:
+ - type
- requestId
- engine
- database
- schema
- title: PreviewSQLTableListRequest
+ - tableName
+ title: PreviewSQLTableCommand
type: object
PreviewSQLTableRequest:
- description: Preview table details in an SQL database
properties:
database:
type: string
@@ -2758,6 +3089,20 @@ components:
- op
title: ReconnectedNotification
type: object
+ RefreshSecretsCommand:
+ properties:
+ type:
+ enum:
+ - refresh-secrets
+ required:
+ - type
+ title: RefreshSecretsCommand
+ type: object
+ RefreshSecretsRequest:
+ properties: {}
+ required: []
+ title: RefreshSecretsRequest
+ type: object
ReloadNotification:
properties:
op:
@@ -2793,41 +3138,25 @@ components:
- cell_id
title: RemoveUIElementsNotification
type: object
- RenameFileRequest:
+ RenameNotebookCommand:
properties:
filename:
type: string
+ type:
+ enum:
+ - rename-notebook
required:
+ - type
- filename
- title: RenameFileRequest
+ title: RenameNotebookCommand
type: object
- RenameRequest:
+ RenameNotebookRequest:
properties:
filename:
type: string
required:
- filename
- title: RenameRequest
- type: object
- RunRequest:
- properties:
- cellIds:
- items:
- type: string
- type: array
- codes:
- items:
- type: string
- type: array
- request:
- anyOf:
- - $ref: '#/components/schemas/HTTPRequest'
- - type: 'null'
- default: null
- required:
- - cellIds
- - codes
- title: RunRequest
+ title: RenameNotebookRequest
type: object
RunningNotebooksResponse:
properties:
@@ -3145,37 +3474,6 @@ components:
- keys
title: SecretKeysWithProvider
type: object
- UIElementMessageNotification:
- description: Send a message to a UI element.
- properties:
- buffers:
- anyOf:
- - items:
- contentEncoding: base64
- type: string
- type: array
- - type: 'null'
- default: null
- message:
- type: object
- model_id:
- anyOf:
- - type: string
- - type: 'null'
- op:
- enum:
- - send-ui-element-message
- ui_element:
- anyOf:
- - type: string
- - type: 'null'
- required:
- - op
- - ui_element
- - model_id
- - message
- title: UIElementMessageNotification
- type: object
ServerConfig:
description: "Configuration for the server.\n\n **Keys.**\n\n - `browser`:\
\ the web browser to use. `\"default\"` or a browser registered\n with\
@@ -3195,62 +3493,6 @@ components:
- follow_symlink
title: ServerConfig
type: object
- SetCellConfigRequest:
- properties:
- configs:
- additionalProperties:
- type: object
- type: object
- required:
- - configs
- title: SetCellConfigRequest
- type: object
- SetModelMessageRequest:
- properties:
- buffers:
- anyOf:
- - items:
- type: string
- type: array
- - type: 'null'
- default: null
- message:
- $ref: '#/components/schemas/ModelMessage'
- modelId:
- type: string
- required:
- - modelId
- - message
- title: SetModelMessageRequest
- type: object
- SetUIElementValueRequest:
- properties:
- objectIds:
- items:
- type: string
- type: array
- request:
- anyOf:
- - $ref: '#/components/schemas/HTTPRequest'
- - type: 'null'
- default: null
- token:
- type: string
- values:
- type: array
- required:
- - objectIds
- - values
- title: SetUIElementValueRequest
- type: object
- SetUserConfigRequest:
- properties:
- config:
- $ref: '#/components/schemas/MarimoConfig'
- required:
- - config
- title: SetUserConfigRequest
- type: object
SetupRootError:
properties:
edges_with_vars:
@@ -3429,10 +3671,14 @@ components:
- text
title: StdinRequest
type: object
- StopRequest:
- properties: {}
- required: []
- title: StopRequest
+ StopKernelCommand:
+ properties:
+ type:
+ enum:
+ - stop-kernel
+ required:
+ - type
+ title: StopKernelCommand
type: object
StoreConfig:
description: Configuration for cache stores.
@@ -3456,6 +3702,32 @@ components:
required: []
title: SuccessResponse
type: object
+ SyncGraphCommand:
+ properties:
+ cells:
+ additionalProperties:
+ type: string
+ type: object
+ deleteIds:
+ items:
+ type: string
+ type: array
+ runIds:
+ items:
+ type: string
+ type: array
+ timestamp:
+ type: number
+ type:
+ enum:
+ - sync-graph
+ required:
+ - type
+ - cells
+ - runIds
+ - deleteIds
+ title: SyncGraphCommand
+ type: object
ToolDefinition:
description: Tool definition compatible with ai-sdk-ui format.
properties:
@@ -3498,6 +3770,37 @@ components:
required: []
title: TyLanguageServerConfig
type: object
+ UIElementMessageNotification:
+ description: Send a message to a UI element.
+ properties:
+ buffers:
+ anyOf:
+ - items:
+ contentEncoding: base64
+ type: string
+ type: array
+ - type: 'null'
+ default: null
+ message:
+ type: object
+ model_id:
+ anyOf:
+ - type: string
+ - type: 'null'
+ op:
+ enum:
+ - send-ui-element-message
+ ui_element:
+ anyOf:
+ - type: string
+ - type: 'null'
+ required:
+ - op
+ - ui_element
+ - model_id
+ - message
+ title: UIElementMessageNotification
+ type: object
UnknownError:
properties:
error_type:
@@ -3537,6 +3840,30 @@ components:
- code_is_stale
title: UpdateCellCodesNotification
type: object
+ UpdateCellConfigCommand:
+ properties:
+ configs:
+ additionalProperties:
+ type: object
+ type: object
+ type:
+ enum:
+ - update-cell-config
+ required:
+ - type
+ - configs
+ title: UpdateCellConfigCommand
+ type: object
+ UpdateCellConfigRequest:
+ properties:
+ configs:
+ additionalProperties:
+ type: object
+ type: object
+ required:
+ - configs
+ title: UpdateCellConfigRequest
+ type: object
UpdateCellIdsNotification:
description: 'Update the cell ID ordering of the cells in the notebook.
@@ -3567,21 +3894,153 @@ components:
- cellIds
title: UpdateCellIdsRequest
type: object
- UpdateComponentValuesRequest:
+ UpdateUIElementCommand:
properties:
objectIds:
items:
type: string
type: array
+ request:
+ anyOf:
+ - $ref: '#/components/schemas/HTTPRequest'
+ - type: 'null'
+ default: null
+ token:
+ type: string
+ type:
+ enum:
+ - update-ui-element
values:
type: array
required:
+ - type
- objectIds
- values
- title: UpdateComponentValuesRequest
+ title: UpdateUIElementCommand
type: object
- ValidateSQLRequest:
+ UpdateUIElementRequest:
+ properties:
+ objectIds:
+ items:
+ type: string
+ type: array
+ request:
+ anyOf:
+ - $ref: '#/components/schemas/HTTPRequest'
+ - type: 'null'
+ default: null
+ token:
+ type: string
+ values:
+ type: array
+ required:
+ - objectIds
+ - values
+ title: UpdateUIElementRequest
+ type: object
+ UpdateUIElementValuesRequest:
+ properties:
+ objectIds:
+ items:
+ type: string
+ type: array
+ values:
+ type: array
+ required:
+ - objectIds
+ - values
+ title: UpdateUIElementValuesRequest
+ type: object
+ UpdateUserConfigCommand:
+ properties:
+ config:
+ $ref: '#/components/schemas/MarimoConfig'
+ type:
+ enum:
+ - update-user-config
+ required:
+ - type
+ - config
+ title: UpdateUserConfigCommand
+ type: object
+ UpdateUserConfigRequest:
+ properties:
+ config:
+ $ref: '#/components/schemas/MarimoConfig'
+ required:
+ - config
+ title: UpdateUserConfigRequest
+ type: object
+ UpdateWidgetModelCommand:
+ properties:
+ buffers:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ default: null
+ message:
+ $ref: '#/components/schemas/ModelMessage'
+ modelId:
+ type: string
+ type:
+ enum:
+ - update-widget-model
+ required:
+ - type
+ - modelId
+ - message
+ title: UpdateWidgetModelCommand
+ type: object
+ UpdateWidgetModelRequest:
+ properties:
+ buffers:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ default: null
+ message:
+ $ref: '#/components/schemas/ModelMessage'
+ modelId:
+ type: string
+ required:
+ - modelId
+ - message
+ title: UpdateWidgetModelRequest
+ type: object
+ ValidateSQLCommand:
description: Validate an SQL query against the engine
+ properties:
+ dialect:
+ anyOf:
+ - type: string
+ - type: 'null'
+ default: null
+ engine:
+ anyOf:
+ - type: string
+ - type: 'null'
+ default: null
+ onlyParse:
+ type: boolean
+ query:
+ type: string
+ requestId:
+ type: string
+ type:
+ enum:
+ - validate-sql
+ required:
+ - type
+ - requestId
+ - query
+ - onlyParse
+ title: ValidateSQLCommand
+ type: object
+ ValidateSQLRequest:
properties:
dialect:
anyOf:
@@ -3803,13 +4262,13 @@ paths:
schema:
type: string
responses:
- '200':
+ 200:
content:
application/octet-stream:
schema:
type: string
description: Get a virtual file
- '404':
+ 404:
description: Invalid byte length in virtual file request
/api/ai/chat:
post:
@@ -3830,7 +4289,7 @@ paths:
description: The request body for AI completion
required: true
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -3847,7 +4306,7 @@ paths:
description: The request body for AI inline completion
required: true
responses:
- '200':
+ 200:
content:
text/plain:
schema:
@@ -3863,7 +4322,7 @@ paths:
description: The request body for tool invocation
required: true
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -3872,7 +4331,7 @@ paths:
/api/ai/mcp/refresh:
post:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -3881,7 +4340,7 @@ paths:
/api/ai/mcp/status:
get:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -3895,7 +4354,7 @@ paths:
schema:
$ref: '#/components/schemas/ClearCacheRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -3909,7 +4368,7 @@ paths:
schema:
$ref: '#/components/schemas/GetCacheInfoRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -3923,7 +4382,7 @@ paths:
schema:
$ref: '#/components/schemas/PreviewDatasetColumnRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -3935,9 +4394,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/PreviewDataSourceConnectionRequest'
+ $ref: '#/components/schemas/ListDataSourceConnectionRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -3951,7 +4410,7 @@ paths:
schema:
$ref: '#/components/schemas/PreviewSQLTableRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -3963,9 +4422,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/PreviewSQLTableListRequest'
+ $ref: '#/components/schemas/ListSQLTablesRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -3974,7 +4433,7 @@ paths:
/api/documentation/snippets:
get:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -3988,13 +4447,13 @@ paths:
schema:
$ref: '#/components/schemas/ExportAsHTMLRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
$ref: '#/components/schemas/SuccessResponse'
description: Export the notebook as HTML
- '400':
+ 400:
description: File must be saved before downloading
/api/export/auto_export/ipynb:
post:
@@ -4004,13 +4463,13 @@ paths:
schema:
$ref: '#/components/schemas/ExportAsIPYNBRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
$ref: '#/components/schemas/SuccessResponse'
description: Export the notebook as IPYNB
- '400':
+ 400:
description: File must be saved before downloading
/api/export/auto_export/markdown:
post:
@@ -4020,13 +4479,13 @@ paths:
schema:
$ref: '#/components/schemas/ExportAsMarkdownRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
$ref: '#/components/schemas/SuccessResponse'
description: Export the notebook as a markdown
- '400':
+ 400:
description: File must be saved before downloading
/api/export/html:
post:
@@ -4036,13 +4495,13 @@ paths:
schema:
$ref: '#/components/schemas/ExportAsHTMLRequest'
responses:
- '200':
+ 200:
content:
text/html:
schema:
type: string
description: Export the notebook as HTML
- '400':
+ 400:
description: File must be saved before downloading
/api/export/markdown:
post:
@@ -4052,13 +4511,13 @@ paths:
schema:
$ref: '#/components/schemas/ExportAsMarkdownRequest'
responses:
- '200':
+ 200:
content:
text/plain:
schema:
type: string
description: Export the notebook as a markdown
- '400':
+ 400:
description: File must be saved before downloading
/api/export/script:
post:
@@ -4068,13 +4527,13 @@ paths:
schema:
$ref: '#/components/schemas/ExportAsScriptRequest'
responses:
- '200':
+ 200:
content:
text/plain:
schema:
type: string
description: Export the notebook as a script
- '400':
+ 400:
description: File must be saved before downloading
/api/files/create:
post:
@@ -4084,7 +4543,7 @@ paths:
schema:
$ref: '#/components/schemas/FileCreateRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4098,7 +4557,7 @@ paths:
schema:
$ref: '#/components/schemas/FileDeleteRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4112,7 +4571,7 @@ paths:
schema:
$ref: '#/components/schemas/FileDetailsRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4126,7 +4585,7 @@ paths:
schema:
$ref: '#/components/schemas/FileListRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4140,7 +4599,7 @@ paths:
schema:
$ref: '#/components/schemas/FileMoveRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4154,7 +4613,7 @@ paths:
schema:
$ref: '#/components/schemas/FileOpenRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4168,7 +4627,7 @@ paths:
schema:
$ref: '#/components/schemas/FileSearchRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4182,7 +4641,7 @@ paths:
schema:
$ref: '#/components/schemas/FileUpdateRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4191,7 +4650,7 @@ paths:
/api/home/recent_files:
post:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4200,7 +4659,7 @@ paths:
/api/home/running_notebooks:
post:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4214,7 +4673,7 @@ paths:
schema:
$ref: '#/components/schemas/ShutdownSessionRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4228,7 +4687,7 @@ paths:
schema:
$ref: '#/components/schemas/OpenTutorialRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4242,7 +4701,7 @@ paths:
schema:
$ref: '#/components/schemas/WorkspaceFilesRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4256,7 +4715,7 @@ paths:
schema:
$ref: '#/components/schemas/CodeCompletionRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4270,7 +4729,7 @@ paths:
schema:
$ref: '#/components/schemas/CopyNotebookRequest'
responses:
- '200':
+ 200:
content:
text/plain:
schema:
@@ -4284,7 +4743,7 @@ paths:
schema:
$ref: '#/components/schemas/DeleteCellRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4296,9 +4755,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/FormatRequest'
+ $ref: '#/components/schemas/FormatCellsRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4310,9 +4769,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/FunctionCallRequest'
+ $ref: '#/components/schemas/InvokeFunctionRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4324,9 +4783,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/InstallMissingPackagesRequest'
+ $ref: '#/components/schemas/InstallPackagesRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4338,9 +4797,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/InstantiateRequest'
+ $ref: '#/components/schemas/InstantiateNotebookRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4349,7 +4808,7 @@ paths:
/api/kernel/interrupt:
post:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4361,9 +4820,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/PdbRequest'
+ $ref: '#/components/schemas/DebugCellRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4372,13 +4831,13 @@ paths:
/api/kernel/read_code:
post:
responses:
- '200':
+ 200:
content:
application/json:
schema:
$ref: '#/components/schemas/ReadCodeResponse'
description: Read the code from the server
- '400':
+ 400:
description: File must be saved before downloading
/api/kernel/rename:
post:
@@ -4386,9 +4845,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/RenameFileRequest'
+ $ref: '#/components/schemas/RenameNotebookRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4397,7 +4856,7 @@ paths:
/api/kernel/restart_session:
post:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4409,9 +4868,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/RunRequest'
+ $ref: '#/components/schemas/ExecuteCellsRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4426,7 +4885,7 @@ paths:
schema:
$ref: '#/components/schemas/SaveNotebookRequest'
responses:
- '200':
+ 200:
content:
text/plain:
schema:
@@ -4440,7 +4899,7 @@ paths:
schema:
$ref: '#/components/schemas/SaveAppConfigurationRequest'
responses:
- '200':
+ 200:
content:
text/plain:
schema:
@@ -4454,7 +4913,7 @@ paths:
schema:
$ref: '#/components/schemas/SaveUserConfigurationRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4469,7 +4928,7 @@ paths:
schema:
$ref: '#/components/schemas/ExecuteScratchpadRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4481,9 +4940,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/SetCellConfigRequest'
+ $ref: '#/components/schemas/UpdateCellConfigRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4495,9 +4954,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/SetModelMessageRequest'
+ $ref: '#/components/schemas/UpdateWidgetModelRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4509,9 +4968,9 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/UpdateComponentValuesRequest'
+ $ref: '#/components/schemas/UpdateUIElementValuesRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4520,7 +4979,7 @@ paths:
/api/kernel/shutdown:
post:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4534,7 +4993,7 @@ paths:
schema:
$ref: '#/components/schemas/StdinRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4548,7 +5007,7 @@ paths:
schema:
$ref: '#/components/schemas/UpdateCellIdsRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4557,7 +5016,7 @@ paths:
/api/kernel/takeover:
post:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4574,7 +5033,7 @@ paths:
schema:
$ref: '#/components/schemas/AddPackageRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4583,7 +5042,7 @@ paths:
/api/packages/list:
get:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4597,7 +5056,7 @@ paths:
schema:
$ref: '#/components/schemas/RemovePackageRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4606,7 +5065,7 @@ paths:
/api/packages/tree:
get:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4621,7 +5080,7 @@ paths:
$ref: '#/components/schemas/CreateSecretRequest'
required: true
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4630,7 +5089,7 @@ paths:
/api/secrets/delete:
post:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4645,7 +5104,7 @@ paths:
$ref: '#/components/schemas/ListSecretKeysRequest'
required: true
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4659,7 +5118,7 @@ paths:
schema:
$ref: '#/components/schemas/ValidateSQLRequest'
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4668,7 +5127,7 @@ paths:
/api/status:
get:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4698,7 +5157,7 @@ paths:
/api/status/connections:
get:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4710,7 +5169,7 @@ paths:
/api/usage:
get:
responses:
- '200':
+ 200:
content:
application/json:
schema:
@@ -4790,7 +5249,7 @@ paths:
/api/version:
get:
responses:
- '200':
+ 200:
content:
text/plain:
schema:
@@ -4808,13 +5267,13 @@ paths:
type: string
type: object
responses:
- '200':
+ 200:
content:
text/html:
schema:
type: string
description: Login page
- '302':
+ 302:
description: Redirect to the next URL
headers:
Location:
@@ -4823,3 +5282,4 @@ paths:
summary: Submit login form
tags:
- auth
+
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 7180e6b2ca..0f3291b9f3 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -406,7 +406,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["PreviewDataSourceConnectionRequest"];
+ "application/json": components["schemas"]["ListDataSourceConnectionRequest"];
};
};
responses: {
@@ -484,7 +484,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["PreviewSQLTableListRequest"];
+ "application/json": components["schemas"]["ListSQLTablesRequest"];
};
};
responses: {
@@ -1450,7 +1450,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["FormatRequest"];
+ "application/json": components["schemas"]["FormatCellsRequest"];
};
};
responses: {
@@ -1489,7 +1489,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["FunctionCallRequest"];
+ "application/json": components["schemas"]["InvokeFunctionRequest"];
};
};
responses: {
@@ -1528,7 +1528,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["InstallMissingPackagesRequest"];
+ "application/json": components["schemas"]["InstallPackagesRequest"];
};
};
responses: {
@@ -1567,7 +1567,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["InstantiateRequest"];
+ "application/json": components["schemas"]["InstantiateNotebookRequest"];
};
};
responses: {
@@ -1641,7 +1641,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["PdbRequest"];
+ "application/json": components["schemas"]["DebugCellRequest"];
};
};
responses: {
@@ -1722,7 +1722,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["RenameFileRequest"];
+ "application/json": components["schemas"]["RenameNotebookRequest"];
};
};
responses: {
@@ -1796,7 +1796,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["RunRequest"];
+ "application/json": components["schemas"]["ExecuteCellsRequest"];
};
};
responses: {
@@ -1991,7 +1991,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["SetCellConfigRequest"];
+ "application/json": components["schemas"]["UpdateCellConfigRequest"];
};
};
responses: {
@@ -2030,7 +2030,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["SetModelMessageRequest"];
+ "application/json": components["schemas"]["UpdateWidgetModelRequest"];
};
};
responses: {
@@ -2069,7 +2069,7 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["UpdateComponentValuesRequest"];
+ "application/json": components["schemas"]["UpdateUIElementValuesRequest"];
};
};
responses: {
@@ -3118,8 +3118,21 @@ export interface components {
/** @default null */
variables?: (string | components["schemas"]["VariableContext"])[] | null;
};
+ /** ClearCacheCommand */
+ ClearCacheCommand: {
+ /** @enum {unknown} */
+ type: "clear-cache";
+ };
/** ClearCacheRequest */
ClearCacheRequest: Record<string, any>;
+ /** CodeCompletionCommand */
+ CodeCompletionCommand: {
+ cellId: string;
+ document: string;
+ id: string;
+ /** @enum {unknown} */
+ type: "code-completion";
+ };
/** CodeCompletionRequest */
CodeCompletionRequest: {
cellId: string;
@@ -3214,6 +3227,16 @@ export interface components {
destination: string;
source: string;
};
+ /** CreateNotebookCommand */
+ CreateNotebookCommand: {
+ autoRun: boolean;
+ executionRequests: components["schemas"]["ExecuteCellCommand"][];
+ /** @default null */
+ request?: components["schemas"]["HTTPRequest"] | null;
+ setUiElementValueRequest: components["schemas"]["UpdateUIElementCommand"];
+ /** @enum {unknown} */
+ type: "create-notebook";
+ };
/** CreateSecretRequest */
CreateSecretRequest: {
key: string;
@@ -3384,6 +3407,26 @@ export interface components {
auto_discover_schemas?: boolean | "auto";
auto_discover_tables?: boolean | "auto";
};
+ /** DebugCellCommand */
+ DebugCellCommand: {
+ cellId: string;
+ /** @default null */
+ request?: components["schemas"]["HTTPRequest"] | null;
+ /** @enum {unknown} */
+ type: "debug-cell";
+ };
+ /** DebugCellRequest */
+ DebugCellRequest: {
+ cellId: string;
+ /** @default null */
+ request?: components["schemas"]["HTTPRequest"] | null;
+ };
+ /** DeleteCellCommand */
+ DeleteCellCommand: {
+ cellId: string;
+ /** @enum {unknown} */
+ type: "delete-cell";
+ };
/** DeleteCellRequest */
DeleteCellRequest: {
cellId: string;
@@ -3450,32 +3493,53 @@ export interface components {
/** @enum {unknown} */
theme: "dark" | "light" | "system";
};
- /** ExecuteMultipleRequest */
- ExecuteMultipleRequest: {
+ /** ExecuteCellCommand */
+ ExecuteCellCommand: {
+ cellId: string;
+ code: string;
+ /** @default null */
+ request?: components["schemas"]["HTTPRequest"] | null;
+ timestamp?: number;
+ /** @enum {unknown} */
+ type: "execute-cell";
+ };
+ /** ExecuteCellsCommand */
+ ExecuteCellsCommand: {
cellIds: string[];
codes: string[];
/** @default null */
request?: components["schemas"]["HTTPRequest"] | null;
timestamp?: number;
+ /** @enum {unknown} */
+ type: "execute-cells";
};
- /** ExecuteScratchpadRequest */
- ExecuteScratchpadRequest: {
- code: string;
+ /** ExecuteCellsRequest */
+ ExecuteCellsRequest: {
+ cellIds: string[];
+ codes: string[];
/** @default null */
request?: components["schemas"]["HTTPRequest"] | null;
};
- /** ExecuteStaleRequest */
- ExecuteStaleRequest: {
+ /** ExecuteScratchpadCommand */
+ ExecuteScratchpadCommand: {
+ code: string;
/** @default null */
request?: components["schemas"]["HTTPRequest"] | null;
+ /** @enum {unknown} */
+ type: "execute-scratchpad";
};
- /** ExecutionRequest */
- ExecutionRequest: {
- cellId: string;
+ /** ExecuteScratchpadRequest */
+ ExecuteScratchpadRequest: {
code: string;
/** @default null */
request?: components["schemas"]["HTTPRequest"] | null;
- timestamp?: number;
+ };
+ /** ExecuteStaleCellsCommand */
+ ExecuteStaleCellsCommand: {
+ /** @default null */
+ request?: components["schemas"]["HTTPRequest"] | null;
+ /** @enum {unknown} */
+ type: "execute-stale-cells";
};
/** ExportAsHTMLRequest */
ExportAsHTMLRequest: {
@@ -3616,8 +3680,8 @@ export interface components {
/** @enum {unknown} */
op: "focus-cell";
};
- /** FormatRequest */
- FormatRequest: {
+ /** FormatCellsRequest */
+ FormatCellsRequest: {
codes: {
[key: string]: string;
};
@@ -3640,13 +3704,6 @@ export interface components {
FormattingConfig: {
line_length: number;
};
- /** FunctionCallRequest */
- FunctionCallRequest: {
- args: Record<string, any>;
- functionCallId: string;
- functionName: string;
- namespace: string;
- };
/**
* FunctionCallResultNotification
* @description Result of calling a function.
@@ -3658,6 +3715,11 @@ export interface components {
return_value: unknown;
status: components["schemas"]["HumanReadableStatus"];
};
+ /** GetCacheInfoCommand */
+ GetCacheInfoCommand: {
+ /** @enum {unknown} */
+ type: "get-cache-info";
+ };
/** GetCacheInfoRequest */
GetCacheInfoRequest: Record<string, any>;
/**
@@ -3688,28 +3750,26 @@ export interface components {
GoogleAiConfig: {
api_key?: string;
};
+ /**
+ * HTTPRequest
+ * @description A class that mimics the Request object from Starlette or FastAPI.
+ *
+ * It is a subset and pickle-able version of the Request object.
+ */
HTTPRequest: {
- baseUrl: {
- [key: string]: unknown;
- };
+ base_url: Record<string, any>;
cookies: {
[key: string]: string;
};
headers: {
[key: string]: string;
};
- meta: {
- [key: string]: unknown;
- };
- pathParams: {
- [key: string]: unknown;
- };
- queryParams: {
+ meta: Record<string, any>;
+ path_params: Record<string, any>;
+ query_params: {
[key: string]: string[];
};
- url: {
- [key: string]: unknown;
- };
+ url: Record<string, any>;
user: unknown;
};
/**
@@ -3732,8 +3792,17 @@ export interface components {
/** @enum {unknown} */
type: "import-star";
};
- /** InstallMissingPackagesRequest */
- InstallMissingPackagesRequest: {
+ /** InstallPackagesCommand */
+ InstallPackagesCommand: {
+ manager: string;
+ /** @enum {unknown} */
+ type: "install-packages";
+ versions: {
+ [key: string]: string;
+ };
+ };
+ /** InstallPackagesRequest */
+ InstallPackagesRequest: {
manager: string;
versions: {
[key: string]: string;
@@ -3753,8 +3822,8 @@ export interface components {
[key: string]: "failed" | "installed" | "installing" | "queued";
};
};
- /** InstantiateRequest */
- InstantiateRequest: {
+ /** InstantiateNotebookRequest */
+ InstantiateNotebookRequest: {
/** @default true */
autoRun?: boolean;
objectIds: string[];
@@ -3781,6 +3850,22 @@ export interface components {
success: boolean;
toolName: string;
};
+ /** InvokeFunctionCommand */
+ InvokeFunctionCommand: {
+ args: Record<string, any>;
+ functionCallId: string;
+ functionName: string;
+ namespace: string;
+ /** @enum {unknown} */
+ type: "invoke-function";
+ };
+ /** InvokeFunctionRequest */
+ InvokeFunctionRequest: {
+ args: Record<string, any>;
+ functionCallId: string;
+ functionName: string;
+ namespace: string;
+ };
/** KernelCapabilitiesNotification */
KernelCapabilitiesNotification: {
/** @default false */
@@ -3838,6 +3923,31 @@ export interface components {
};
/** KnownUnions */
KnownUnions: {
+ command:
+ | components["schemas"]["CreateNotebookCommand"]
+ | components["schemas"]["RenameNotebookCommand"]
+ | components["schemas"]["ExecuteCellsCommand"]
+ | components["schemas"]["ExecuteScratchpadCommand"]
+ | components["schemas"]["ExecuteStaleCellsCommand"]
+ | components["schemas"]["DebugCellCommand"]
+ | components["schemas"]["DeleteCellCommand"]
+ | components["schemas"]["SyncGraphCommand"]
+ | components["schemas"]["UpdateCellConfigCommand"]
+ | components["schemas"]["InstallPackagesCommand"]
+ | components["schemas"]["UpdateUIElementCommand"]
+ | components["schemas"]["UpdateWidgetModelCommand"]
+ | components["schemas"]["InvokeFunctionCommand"]
+ | components["schemas"]["UpdateUserConfigCommand"]
+ | components["schemas"]["PreviewDatasetColumnCommand"]
+ | components["schemas"]["PreviewSQLTableCommand"]
+ | components["schemas"]["ListSQLTablesCommand"]
+ | components["schemas"]["ValidateSQLCommand"]
+ | components["schemas"]["ListDataSourceConnectionCommand"]
+ | components["schemas"]["ListSecretKeysCommand"]
+ | components["schemas"]["RefreshSecretsCommand"]
+ | components["schemas"]["ClearCacheCommand"]
+ | components["schemas"]["GetCacheInfoCommand"]
+ | components["schemas"]["StopKernelCommand"];
/** @enum {unknown} */
data_type:
| "boolean"
@@ -3915,10 +4025,48 @@ export interface components {
data: Record<string, any>;
type: string;
};
+ /**
+ * ListDataSourceConnectionCommand
+ * @description Fetch a datasource connection
+ */
+ ListDataSourceConnectionCommand: {
+ engine: string;
+ /** @enum {unknown} */
+ type: "list-data-source-connection";
+ };
+ /** ListDataSourceConnectionRequest */
+ ListDataSourceConnectionRequest: {
+ engine: string;
+ };
/** ListPackagesResponse */
ListPackagesResponse: {
packages: components["schemas"]["PackageDescription"][];
};
+ /**
+ * ListSQLTablesCommand
+ * @description Preview list of tables in an SQL schema
+ */
+ ListSQLTablesCommand: {
+ database: string;
+ engine: string;
+ requestId: string;
+ schema: string;
+ /** @enum {unknown} */
+ type: "list-sql-tables";
+ };
+ /** ListSQLTablesRequest */
+ ListSQLTablesRequest: {
+ database: string;
+ engine: string;
+ requestId: string;
+ schema: string;
+ };
+ /** ListSecretKeysCommand */
+ ListSecretKeysCommand: {
+ requestId: string;
+ /** @enum {unknown} */
+ type: "list-secret-keys";
+ };
/** ListSecretKeysRequest */
ListSecretKeysRequest: {
requestId: string;
@@ -4157,18 +4305,17 @@ export interface components {
error?: string | null;
success: boolean;
};
- /** PdbRequest */
- PdbRequest: {
- cellId: string;
+ /** PreviewDatasetColumnCommand */
+ PreviewDatasetColumnCommand: {
+ columnName: string;
/** @default null */
- request?: components["schemas"]["HTTPRequest"] | null;
- };
- /**
- * PreviewDataSourceConnectionRequest
- * @description Fetch a datasource connection
- */
- PreviewDataSourceConnectionRequest: {
- engine: string;
+ fullyQualifiedTableName?: string | null;
+ source: string;
+ /** @enum {unknown} */
+ sourceType: "catalog" | "connection" | "duckdb" | "local";
+ tableName: string;
+ /** @enum {unknown} */
+ type: "preview-dataset-column";
};
/** PreviewDatasetColumnRequest */
PreviewDatasetColumnRequest: {
@@ -4181,19 +4328,19 @@ export interface components {
tableName: string;
};
/**
- * PreviewSQLTableListRequest
- * @description Preview list of tables in an SQL schema
+ * PreviewSQLTableCommand
+ * @description Preview table details in an SQL database
*/
- PreviewSQLTableListRequest: {
+ PreviewSQLTableCommand: {
database: string;
engine: string;
requestId: string;
schema: string;
+ tableName: string;
+ /** @enum {unknown} */
+ type: "preview-sql-table";
};
- /**
- * PreviewSQLTableRequest
- * @description Preview table details in an SQL database
- */
+ /** PreviewSQLTableRequest */
PreviewSQLTableRequest: {
database: string;
engine: string;
@@ -4258,6 +4405,13 @@ export interface components {
/** @enum {unknown} */
op: "reconnected";
};
+ /** RefreshSecretsCommand */
+ RefreshSecretsCommand: {
+ /** @enum {unknown} */
+ type: "refresh-secrets";
+ };
+ /** RefreshSecretsRequest */
+ RefreshSecretsRequest: Record<string, any>;
/** ReloadNotification */
ReloadNotification: {
/** @enum {unknown} */
@@ -4278,21 +4432,16 @@ export interface components {
/** @enum {unknown} */
op: "remove-ui-elements";
};
- /** RenameFileRequest */
- RenameFileRequest: {
+ /** RenameNotebookCommand */
+ RenameNotebookCommand: {
filename: string;
+ /** @enum {unknown} */
+ type: "rename-notebook";
};
- /** RenameRequest */
- RenameRequest: {
+ /** RenameNotebookRequest */
+ RenameNotebookRequest: {
filename: string;
};
- /** RunRequest */
- RunRequest: {
- cellIds: string[];
- codes: string[];
- /** @default null */
- request?: components["schemas"]["HTTPRequest"] | null;
- };
/** RunningNotebooksResponse */
RunningNotebooksResponse: {
files: components["schemas"]["MarimoFile"][];
@@ -4467,19 +4616,6 @@ export interface components {
/** @enum {unknown} */
provider: "dotenv" | "env";
};
- /**
- * UIElementMessageNotification
- * @description Send a message to a UI element.
- */
- UIElementMessageNotification: {
- /** @default null */
- buffers?: string[] | null;
- message: Record<string, any>;
- model_id: string | null;
- /** @enum {unknown} */
- op: "send-ui-element-message";
- ui_element: string | null;
- };
/**
* ServerConfig
* @description Configuration for the server.
@@ -4495,31 +4631,6 @@ export interface components {
browser: "default" | string;
follow_symlink: boolean;
};
- /** SetCellConfigRequest */
- SetCellConfigRequest: {
- configs: {
- [key: string]: Record<string, any>;
- };
- };
- /** SetModelMessageRequest */
- SetModelMessageRequest: {
- /** @default null */
- buffers?: string[] | null;
- message: components["schemas"]["ModelMessage"];
- modelId: string;
- };
- /** SetUIElementValueRequest */
- SetUIElementValueRequest: {
- objectIds: string[];
- /** @default null */
- request?: components["schemas"]["HTTPRequest"] | null;
- token?: string;
- values: unknown[];
- };
- /** SetUserConfigRequest */
- SetUserConfigRequest: {
- config: components["schemas"]["MarimoConfig"];
- };
/** SetupRootError */
SetupRootError: {
edges_with_vars: [string, string[], string][];
@@ -4621,8 +4732,11 @@ export interface components {
StdinRequest: {
text: string;
};
- /** StopRequest */
- StopRequest: Record<string, any>;
+ /** StopKernelCommand */
+ StopKernelCommand: {
+ /** @enum {unknown} */
+ type: "stop-kernel";
+ };
/**
* StoreConfig
* @description Configuration for cache stores.
@@ -4637,6 +4751,17 @@ export interface components {
/** @default true */
success?: boolean;
};
+ /** SyncGraphCommand */
+ SyncGraphCommand: {
+ cells: {
+ [key: string]: string;
+ };
+ deleteIds: string[];
+ runIds: string[];
+ timestamp?: number;
+ /** @enum {unknown} */
+ type: "sync-graph";
+ };
/**
* ToolDefinition
* @description Tool definition compatible with ai-sdk-ui format.
@@ -4659,6 +4784,19 @@ export interface components {
TyLanguageServerConfig: {
enabled?: boolean;
};
+ /**
+ * UIElementMessageNotification
+ * @description Send a message to a UI element.
+ */
+ UIElementMessageNotification: {
+ /** @default null */
+ buffers?: string[] | null;
+ message: Record<string, any>;
+ model_id: string | null;
+ /** @enum {unknown} */
+ op: "send-ui-element-message";
+ ui_element: string | null;
+ };
/** UnknownError */
UnknownError: {
/** @default null */
@@ -4675,6 +4813,20 @@ export interface components {
/** @enum {unknown} */
op: "update-cell-codes";
};
+ /** UpdateCellConfigCommand */
+ UpdateCellConfigCommand: {
+ configs: {
+ [key: string]: Record<string, any>;
+ };
+ /** @enum {unknown} */
+ type: "update-cell-config";
+ };
+ /** UpdateCellConfigRequest */
+ UpdateCellConfigRequest: {
+ configs: {
+ [key: string]: Record<string, any>;
+ };
+ };
/**
* UpdateCellIdsNotification
* @description Update the cell ID ordering of the cells in the notebook.
@@ -4691,15 +4843,71 @@ export interface components {
UpdateCellIdsRequest: {
cellIds: string[];
};
- /** UpdateComponentValuesRequest */
- UpdateComponentValuesRequest: {
+ /** UpdateUIElementCommand */
+ UpdateUIElementCommand: {
+ objectIds: string[];
+ /** @default null */
+ request?: components["schemas"]["HTTPRequest"] | null;
+ token?: string;
+ /** @enum {unknown} */
+ type: "update-ui-element";
+ values: unknown[];
+ };
+ /** UpdateUIElementRequest */
+ UpdateUIElementRequest: {
objectIds: string[];
+ /** @default null */
+ request?: components["schemas"]["HTTPRequest"] | null;
+ token?: string;
values: unknown[];
};
+ /** UpdateUIElementValuesRequest */
+ UpdateUIElementValuesRequest: {
+ objectIds: string[];
+ values: unknown[];
+ };
+ /** UpdateUserConfigCommand */
+ UpdateUserConfigCommand: {
+ config: components["schemas"]["MarimoConfig"];
+ /** @enum {unknown} */
+ type: "update-user-config";
+ };
+ /** UpdateUserConfigRequest */
+ UpdateUserConfigRequest: {
+ config: components["schemas"]["MarimoConfig"];
+ };
+ /** UpdateWidgetModelCommand */
+ UpdateWidgetModelCommand: {
+ /** @default null */
+ buffers?: string[] | null;
+ message: components["schemas"]["ModelMessage"];
+ modelId: string;
+ /** @enum {unknown} */
+ type: "update-widget-model";
+ };
+ /** UpdateWidgetModelRequest */
+ UpdateWidgetModelRequest: {
+ /** @default null */
+ buffers?: string[] | null;
+ message: components["schemas"]["ModelMessage"];
+ modelId: string;
+ };
/**
- * ValidateSQLRequest
+ * ValidateSQLCommand
* @description Validate an SQL query against the engine
*/
+ ValidateSQLCommand: {
+ /** @default null */
+ dialect?: string | null;
+ /** @default null */
+ engine?: string | null;
+ onlyParse: boolean;
+ query: string;
+ requestId: string;
+ /** @enum {unknown} */
+ type: "validate-sql";
+ };
+ /** ValidateSQLRequest */
ValidateSQLRequest: {
/** @default null */
dialect?: string | null;
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index a294f61137..e2a4b428e0 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -31,7 +31,7 @@ from marimo._convert.converters import MarimoConvert
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.stateless.flex import vstack
from marimo._runtime.context.types import get_context
-from marimo._runtime.requests import SetUIElementValueRequest
+from marimo._runtime.commands import UpdateUIElementCommand
from marimo._schemas.serialization import (
AppInstantiation,
CellDef,
@@ -1307,7 +1307,7 @@ class TestAppComposition:
assert token[0] == 1
assert await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values(
+ UpdateUIElementCommand.from_ids_and_values(
[(dropdown_element._id, ["second"])]
)
)
@@ -1361,7 +1361,7 @@ class TestAppComposition:
# testing that only descendants of the updated UI elements run,
# and that the other UI element is not reset
assert await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values([(x._id, 2)])
+ UpdateUIElementCommand.from_ids_and_values([(x._id, 2)])
)
assert app_kernel_runner == app._get_kernel_runner()
@@ -1370,7 +1370,7 @@ class TestAppComposition:
assert y.value == 1
assert await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values([(y._id, 3)])
+ UpdateUIElementCommand.from_ids_and_values([(y._id, 3)])
)
assert x.value == 2
diff --git a/tests/_data/test_preview_column.py b/tests/_data/test_preview_column.py
index b00402cea8..80fe34b60b 100644
--- a/tests/_data/test_preview_column.py
+++ b/tests/_data/test_preview_column.py
@@ -17,7 +17,7 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.charts.altair_transformer import (
register_transformers,
)
-from marimo._runtime.requests import PreviewDatasetColumnRequest
+from marimo._runtime.commands import PreviewDatasetColumnCommand
from marimo._utils.platform import is_windows
from tests._data.mocks import create_dataframes
from tests.mocks import snapshotter
@@ -73,7 +73,7 @@ def test_get_column_preview_for_dataframe(df: Any) -> None:
for column_name in ["A", "B"]:
result = get_column_preview_for_dataframe(
df,
- request=PreviewDatasetColumnRequest(
+ request=PreviewDatasetColumnCommand(
source="source",
table_name="table",
column_name=column_name,
diff --git a/tests/_ipc/test_kernel_communication.py b/tests/_ipc/test_kernel_communication.py
index 7e5404ced4..9fc4441b80 100644
--- a/tests/_ipc/test_kernel_communication.py
+++ b/tests/_ipc/test_kernel_communication.py
@@ -16,9 +16,9 @@ from marimo._ast.cell import CellConfig
from marimo._config.config import DEFAULT_CONFIG
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._dependencies.dependencies import DependencyManager
-from marimo._runtime.requests import (
+from marimo._runtime.commands import (
AppMetadata,
- ExecuteMultipleRequest,
+ ExecuteCellsCommand,
)
from marimo._types.ids import CellId_t
@@ -31,7 +31,7 @@ def test_kernel_launch_and_execute_cells():
"""Test launching a kernel and executing cells with stdout/stderr."""
from marimo._ipc import KernelArgs, QueueManager
- execute_request = ExecuteMultipleRequest(
+ execute_request = ExecuteCellsCommand(
cell_ids=[CellId_t("cell1")],
codes=[
"""\
@@ -252,7 +252,7 @@ def test_queue_manager_connection():
host_manager, connection_info = QueueManager.create()
client_manager = QueueManager.connect(connection_info)
- test_request = ExecuteMultipleRequest(
+ test_request = ExecuteCellsCommand(
cell_ids=[CellId_t("cell1")],
codes=["print('test')"],
)
diff --git a/tests/_messaging/test_messaging_context.py b/tests/_messaging/test_messaging_context.py
index be8458a1f8..a9715f7b98 100644
--- a/tests/_messaging/test_messaging_context.py
+++ b/tests/_messaging/test_messaging_context.py
@@ -11,7 +11,7 @@ from marimo._messaging.context import (
http_request_context,
run_id_context,
)
-from marimo._runtime.requests import HTTPRequest
+from marimo._runtime.commands import HTTPRequest
class TestRunIDContext:
diff --git a/tests/_messaging/test_messaging_context_vars.py b/tests/_messaging/test_messaging_context_vars.py
index e28a1cee92..ffa5659a55 100644
--- a/tests/_messaging/test_messaging_context_vars.py
+++ b/tests/_messaging/test_messaging_context_vars.py
@@ -11,7 +11,7 @@ from marimo._messaging.context import (
http_request_context,
run_id_context,
)
-from marimo._runtime.requests import HTTPRequest
+from marimo._runtime.commands import HTTPRequest
class TestMessagingContextVarsRunID:
diff --git a/tests/_plugins/stateless/test_mpl.py b/tests/_plugins/stateless/test_mpl.py
index 9123ca6bf2..555f28b4cb 100644
--- a/tests/_plugins/stateless/test_mpl.py
+++ b/tests/_plugins/stateless/test_mpl.py
@@ -11,7 +11,7 @@ from marimo._plugins.stateless.mpl._mpl import (
_get_remote_url,
_template,
)
-from marimo._runtime.requests import DeleteCellRequest
+from marimo._runtime.commands import DeleteCellCommand
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -50,7 +50,7 @@ async def test_mpl_interactive(k: Kernel, exec_req: ExecReqProvider) -> None:
interactive = k.globals["interactive"]
assert isinstance(interactive, Html)
assert interactive.text.startswith("<iframe srcdoc=")
- await k.delete_cell(DeleteCellRequest(cell_id=cell.cell_id))
+ await k.delete_cell(DeleteCellCommand(cell_id=cell.cell_id))
@pytest.mark.skipif(
diff --git a/tests/_plugins/ui/_impl/chat/test_chat.py b/tests/_plugins/ui/_impl/chat/test_chat.py
index 2a8f7aa60b..057d02f4da 100644
--- a/tests/_plugins/ui/_impl/chat/test_chat.py
+++ b/tests/_plugins/ui/_impl/chat/test_chat.py
@@ -17,8 +17,8 @@ from marimo._plugins.ui._impl.chat.chat import (
DeleteChatMessageRequest,
SendMessageRequest,
)
+from marimo._runtime.commands import UpdateUIElementCommand
from marimo._runtime.functions import EmptyArgs
-from marimo._runtime.requests import SetUIElementValueRequest
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -421,7 +421,7 @@ async def test_chat_send_message_enqueues_ui_element_request(
k: Kernel, exec_req: ExecReqProvider
) -> None:
# assert that the RPC which updates the chatbot history triggers
- # a SetUIElementValueRequest
+ # a UpdateUIElementRequest
control_requests = []
# the RPC uses enqueue_control_request() to trigger the UI Element update
@@ -448,4 +448,4 @@ async def test_chat_send_message_enqueues_ui_element_request(
)
await chatbot._send_prompt(request)
assert len(control_requests) == 1
- assert isinstance(control_requests[0], SetUIElementValueRequest)
+ assert isinstance(control_requests[0], UpdateUIElementCommand)
diff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.py
index c26de6c2cf..e3b9f03f68 100644
--- a/tests/_plugins/ui/_impl/test_anywidget.py
+++ b/tests/_plugins/ui/_impl/test_anywidget.py
@@ -16,7 +16,7 @@ from marimo._plugins.ui._impl.from_anywidget import (
encode_to_wire,
from_anywidget,
)
-from marimo._runtime.requests import SetUIElementValueRequest
+from marimo._runtime.commands import UpdateUIElementCommand
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -134,7 +134,7 @@ x = as_marimo_element.count
assert ui_element.value == {"count": 10}
await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values(
+ UpdateUIElementCommand.from_ids_and_values(
[(ui_element._id, {"count": 5})]
)
)
@@ -297,7 +297,7 @@ x = as_marimo_element.count
# Simulate a change from the frontend
await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values(
+ UpdateUIElementCommand.from_ids_and_values(
[(ui_element._id, {"value": 42})]
)
)
diff --git a/tests/_plugins/ui/_impl/test_run_button.py b/tests/_plugins/ui/_impl/test_run_button.py
index eb9ef93acd..865208e654 100644
--- a/tests/_plugins/ui/_impl/test_run_button.py
+++ b/tests/_plugins/ui/_impl/test_run_button.py
@@ -1,5 +1,7 @@
+from __future__ import annotations
+
from marimo._plugins import ui
-from marimo._runtime.requests import SetUIElementValueRequest
+from marimo._runtime.commands import UpdateUIElementCommand
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -31,9 +33,7 @@ async def test_run_button_set_to_true_on_click(
run_button = k.globals["b"]
assert not run_button.value
- await k.set_ui_element_value(
- SetUIElementValueRequest([run_button._id], [1])
- )
+ await k.set_ui_element_value(UpdateUIElementCommand([run_button._id], [1]))
if not k.lazy():
assert k.globals["x"] == 1
@@ -80,13 +80,13 @@ async def test_run_buttons_in_array(
assert count[0] == 0
# Just one button pushed
- await k.set_ui_element_value(SetUIElementValueRequest([arr[0]._id], [1]))
+ await k.set_ui_element_value(UpdateUIElementCommand([arr[0]._id], [1]))
assert count[0] == 1
assert not arr.value[0]
assert not arr.value[1]
# Push another button, first button's value should be false, so just an
# increment by 1
- await k.set_ui_element_value(SetUIElementValueRequest([arr[1]._id], [1]))
+ await k.set_ui_element_value(UpdateUIElementCommand([arr[1]._id], [1]))
assert count[0] == 2
assert not arr.value[0]
assert not arr.value[1]
@@ -124,13 +124,13 @@ async def test_run_buttons_in_dict(
assert count[0] == 0
# Just one button pushed
- await k.set_ui_element_value(SetUIElementValueRequest([hoc["0"]._id], [1]))
+ await k.set_ui_element_value(UpdateUIElementCommand([hoc["0"]._id], [1]))
assert count[0] == 1
assert not hoc.value["0"]
assert not hoc.value["1"]
# Push another button, first button's value should be false, so just an
# increment by 1
- await k.set_ui_element_value(SetUIElementValueRequest([hoc["1"]._id], [1]))
+ await k.set_ui_element_value(UpdateUIElementCommand([hoc["1"]._id], [1]))
assert count[0] == 2
assert not hoc.value["0"]
assert not hoc.value["1"]
diff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.py
index b482bfd610..5114a6d996 100644
--- a/tests/_pyodide/test_pyodide_session.py
+++ b/tests/_pyodide/test_pyodide_session.py
@@ -17,29 +17,35 @@ from marimo._pyodide.pyodide_session import (
AsyncQueueManager,
PyodideBridge,
PyodideSession,
- parse_wasm_control_request,
+ parse_command,
)
-from marimo._runtime.context.types import teardown_context
-from marimo._runtime.requests import (
+from marimo._runtime.commands import (
AppMetadata,
- CreationRequest,
- DeleteCellRequest,
- ExecuteMultipleRequest,
- ExecuteScratchpadRequest,
- FunctionCallRequest,
- InstallMissingPackagesRequest,
- ListSecretKeysRequest,
- PreviewDatasetColumnRequest,
- PreviewDataSourceConnectionRequest,
- PreviewSQLTableListRequest,
- PreviewSQLTableRequest,
- RenameRequest,
- SetCellConfigRequest,
- SetModelMessageRequest,
- SetUIElementValueRequest,
- StopRequest,
- SyncGraphRequest,
+ ClearCacheCommand,
+ CreateNotebookCommand,
+ DebugCellCommand,
+ DeleteCellCommand,
+ ExecuteCellsCommand,
+ ExecuteScratchpadCommand,
+ ExecuteStaleCellsCommand,
+ GetCacheInfoCommand,
+ InstallPackagesCommand,
+ InvokeFunctionCommand,
+ ListDataSourceConnectionCommand,
+ ListSecretKeysCommand,
+ ListSQLTablesCommand,
+ PreviewDatasetColumnCommand,
+ PreviewSQLTableCommand,
+ RefreshSecretsCommand,
+ RenameNotebookCommand,
+ StopKernelCommand,
+ SyncGraphCommand,
+ UpdateCellConfigCommand,
+ UpdateUIElementCommand,
+ UpdateWidgetModelCommand,
+ ValidateSQLCommand,
)
+from marimo._runtime.context.types import teardown_context
from marimo._server.model import SessionMode
from marimo._server.notebook import AppFileManager
from marimo._types.ids import CellId_t, UIElementId
@@ -132,8 +138,8 @@ async def pyodide_session(
async def test_async_queue_manager() -> None:
async_queue_manager = AsyncQueueManager()
# Test putting and getting from queues
- stop_request = StopRequest()
- set_ui_element_request = SetUIElementValueRequest(
+ stop_request = StopKernelCommand()
+ set_ui_element_request = UpdateUIElementCommand(
object_ids=[UIElementId("test")], values=["test"]
)
@@ -168,11 +174,11 @@ async def test_pyodide_session_put_control_request(
pyodide_session: PyodideSession,
) -> None:
# Test putting control requests
- execution_request = ExecuteMultipleRequest(
+ execution_request = ExecuteCellsCommand(
cell_ids=[CellId_t("test")],
codes=["test"],
)
- set_ui_element_request = SetUIElementValueRequest(
+ set_ui_element_request = UpdateUIElementCommand(
object_ids=[UIElementId("test")], values=["test"]
)
@@ -241,84 +247,116 @@ async def test_pyodide_session_put_input(
@pytest.mark.parametrize(
("json_payload", "expected_type"),
[
- # Most specific requests with many required fields
+ # Notebook operations
(
- '{"executionRequests": [{"cellId": "cell-1", "code": "print(1)"}], '
- '"setUiElementValueRequest": {"objectIds": [], "values": []}, '
+ '{"type": "create-notebook", "executionRequests": [{"cellId": "cell-1", "code": "print(1)", "type": "execute-cell"}], '
+ '"setUiElementValueRequest": {"objectIds": [], "values": [], "type": "update-ui-element"}, '
'"autoRun": true}',
- CreationRequest,
+ CreateNotebookCommand,
),
(
- '{"cellIds": ["cell-1"], "codes": ["print(1)"]}',
- ExecuteMultipleRequest,
+ '{"type": "rename-notebook", "filename": "test.py"}',
+ RenameNotebookCommand,
),
+ # Cell execution and management
(
- '{"manager": "pip", "packages": ["numpy"], "versions": {}}',
- InstallMissingPackagesRequest,
+ '{"type": "execute-cells", "cellIds": ["cell-1"], "codes": ["print(1)"]}',
+ ExecuteCellsCommand,
),
(
- '{"sourceType": "duckdb", "source": "test.db", "tableName": "users", "columnName": "id"}',
- PreviewDatasetColumnRequest,
+ '{"type": "execute-cells", "cellIds": ["cell-1", "cell-2"], "codes": ["x=1", "y=2"]}',
+ ExecuteCellsCommand,
),
(
- '{"requestId": "req-1", "engine": "duckdb", "database": "test.db", '
- '"schema": "main", "tableName": "users"}',
- PreviewSQLTableRequest,
+ '{"type": "execute-scratchpad", "code": "print(1)"}',
+ ExecuteScratchpadCommand,
+ ),
+ ('{"type": "execute-stale-cells"}', ExecuteStaleCellsCommand),
+ ('{"type": "debug-cell", "cellId": "cell-1"}', DebugCellCommand),
+ ('{"type": "delete-cell", "cellId": "cell-1"}', DeleteCellCommand),
+ (
+ '{"type": "sync-graph", "cells": {"cell-1": "x=1"}, "runIds": ["cell-1"], "deleteIds": []}',
+ SyncGraphCommand,
+ ),
+ (
+ '{"type": "update-cell-config", "configs": {"cell-1": {"hide_code": true}}}',
+ UpdateCellConfigCommand,
),
+ # Package management
(
- '{"requestId": "req-2", "engine": "duckdb", "database": "test.db", "schema": "main"}',
- PreviewSQLTableListRequest,
+ '{"type": "install-packages", "manager": "pip", "versions": {}}',
+ InstallPackagesCommand,
),
- # SetUIElementValueRequest - has specific fields
(
- '{"objectIds": ["test-1"], "values": [42], "token": "test-token"}',
- SetUIElementValueRequest,
+ '{"type": "install-packages", "manager": "pip", "versions": {"numpy": "1.24.0"}}',
+ InstallPackagesCommand,
),
+ # UI element and widget model operations
(
- '{"objectIds": ["test-1"], "values": [42]}', # Without token
- SetUIElementValueRequest,
+ '{"type": "update-ui-element", "objectIds": ["test-1"], "values": [42], "token": "test-token"}',
+ UpdateUIElementCommand,
),
(
- '{"modelId": "model-1", "message": {"state": {}, "bufferPaths": []}}',
- SetModelMessageRequest,
+ '{"type": "update-ui-element", "objectIds": ["test-1"], "values": [42]}',
+ UpdateUIElementCommand,
),
(
- '{"functionCallId": "fc-1", "namespace": "test", "functionName": "foo", "args": {}}',
- FunctionCallRequest,
+ '{"type": "update-ui-element", "objectIds": [], "values": []}',
+ UpdateUIElementCommand,
),
- # Requests with single or few required fields
- # DeleteCellRequest comes before PdbRequest
- # Note: Can't test PdbRequest since DeleteCellRequest will always match first
- ('{"cellId": "cell-1"}', DeleteCellRequest),
- ('{"code": "print(1)"}', ExecuteScratchpadRequest),
(
- '{"cells": {"cell-1": "x=1"}, "runIds": ["cell-1"], "deleteIds": []}',
- SyncGraphRequest,
+ '{"type": "update-widget-model", "modelId": "model-1", "message": {"state": {}, "bufferPaths": []}}',
+ UpdateWidgetModelCommand,
),
- ('{"filename": "test.py"}', RenameRequest),
- ('{"configs": {"cell-1": {"hide_code": true}}}', SetCellConfigRequest),
- ('{"requestId": "req-1"}', ListSecretKeysRequest),
- ('{"engine": "duckdb"}', PreviewDataSourceConnectionRequest),
- # Note: Can't test SetUserConfigRequest or ValidateSQLRequest uniquely
- # - SetUserConfigRequest requires a full MarimoConfig which is complex
- # - ValidateSQLRequest has requestId which matches ListSecretKeysRequest first
- # Empty objects - StopRequest matches first among the empty requests
- # Note: Can't test RefreshSecretsRequest, ClearCacheRequest, GetCacheInfoRequest,
- # or ExecuteStaleRequest since StopRequest will always match first (they all have no required fields)
- ("{}", StopRequest),
+ (
+ '{"type": "invoke-function", "functionCallId": "fc-1", "namespace": "test", "functionName": "foo", "args": {}}',
+ InvokeFunctionCommand,
+ ),
+ # Data/SQL operations
+ (
+ '{"type": "preview-dataset-column", "sourceType": "duckdb", "source": "test.db", "tableName": "users", "columnName": "id"}',
+ PreviewDatasetColumnCommand,
+ ),
+ (
+ '{"type": "preview-sql-table", "requestId": "req-1", "engine": "duckdb", "database": "test.db", '
+ '"schema": "main", "tableName": "users"}',
+ PreviewSQLTableCommand,
+ ),
+ (
+ '{"type": "list-sql-tables", "requestId": "req-2", "engine": "duckdb", "database": "test.db", "schema": "main"}',
+ ListSQLTablesCommand,
+ ),
+ (
+ '{"type": "validate-sql", "requestId": "req-3", "query": "SELECT * FROM users", "onlyParse": false}',
+ ValidateSQLCommand,
+ ),
+ (
+ '{"type": "validate-sql", "requestId": "req-4", "query": "SELECT * FROM users", "onlyParse": true, "dialect": "postgres"}',
+ ValidateSQLCommand,
+ ),
+ (
+ '{"type": "list-data-source-connection", "engine": "duckdb"}',
+ ListDataSourceConnectionCommand,
+ ),
+ # Secrets management
+ (
+ '{"type": "list-secret-keys", "requestId": "req-1"}',
+ ListSecretKeysCommand,
+ ),
+ ('{"type": "refresh-secrets"}', RefreshSecretsCommand),
+ # Cache management
+ ('{"type": "clear-cache"}', ClearCacheCommand),
+ ('{"type": "get-cache-info"}', GetCacheInfoCommand),
+ # Kernel operations
+ ('{"type": "stop-kernel"}', StopKernelCommand),
],
)
-def test_control_request_parsing_order(
+def test_command_parsing_with_discriminator(
json_payload: str, expected_type: type
) -> None:
- """Test that ControlRequest types are parsed in the correct order.
-
- This is critical for WASM/Pyodide where we iterate through types until
- one successfully parses. Types with overlapping structures must be
- ordered correctly.
- """
+ """Test that Command types are parsed correctly using the type discriminator."""
- parsed = parse_wasm_control_request(json_payload)
+ parsed = parse_command(json_payload)
assert type(parsed) is expected_type, (
f"Expected {expected_type.__name__} but got {type(parsed).__name__} "
f"for payload: {json_payload}"
@@ -328,7 +366,7 @@ def test_control_request_parsing_order(
def test_control_request_parsing_invalid() -> None:
"""Test that invalid JSON raises DecodeError."""
with pytest.raises(msgspec.DecodeError):
- parse_wasm_control_request("invalid json")
+ parse_command("invalid json")
async def test_async_queue_manager_close() -> None:
@@ -337,7 +375,7 @@ async def test_async_queue_manager_close() -> None:
manager.close_queues()
request = await manager.control_queue.get()
- assert isinstance(request, StopRequest)
+ assert isinstance(request, StopKernelCommand)
async def test_pyodide_session_on_message(
@@ -363,9 +401,9 @@ async def test_pyodide_session_put_completion_request(
pyodide_session: PyodideSession,
) -> None:
"""Test putting completion requests."""
- from marimo._runtime.requests import CodeCompletionRequest
+ from marimo._runtime.commands import CodeCompletionCommand
- completion_request = CodeCompletionRequest(
+ completion_request = CodeCompletionCommand(
id="test",
document="test code",
cell_id=CellId_t("test"),
@@ -399,7 +437,7 @@ def test_pyodide_bridge_put_control_request(
pyodide_bridge: PyodideBridge,
) -> None:
"""Test putting control requests through the bridge."""
- request_json = '{"cellIds": ["cell-1"], "codes": ["print(1)"]}'
+ request_json = '{"type": "execute-cells", "cellIds": ["cell-1"], "codes": ["print(1)"]}'
pyodide_bridge.put_control_request(request_json)
assert not pyodide_bridge.session._queue_manager.control_queue.empty()
@@ -500,7 +538,7 @@ def test_pyodide_bridge_save_user_config(
pyodide_bridge.save_user_config(request_json)
- # Should have put a SetUserConfigRequest in the queue
+ # Should have put a UpdateUserConfigRequest in the queue
assert not pyodide_bridge.session._queue_manager.control_queue.empty()
diff --git a/tests/_runtime/reload/test_module_watcher.py b/tests/_runtime/reload/test_module_watcher.py
index 68623908a4..263e1a8425 100644
--- a/tests/_runtime/reload/test_module_watcher.py
+++ b/tests/_runtime/reload/test_module_watcher.py
@@ -13,13 +13,13 @@ from reload_test_utils import random_modname, update_file
from marimo._config.config import DEFAULT_CONFIG
from marimo._dependencies.dependencies import DependencyManager
+from marimo._runtime.commands import UpdateUserConfigCommand
from marimo._runtime.reload.autoreload import ModuleReloader
from marimo._runtime.reload.module_watcher import (
_check_modules,
_depends_on,
_get_excluded_modules,
)
-from marimo._runtime.requests import SetUserConfigRequest
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -59,7 +59,7 @@ async def test_reload_function(
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
await k.run(
[
er_1 := exec_req.get(f"from {py_modname} import foo"),
@@ -112,18 +112,18 @@ async def test_disable_and_reenable_reload(
config = copy.deepcopy(DEFAULT_CONFIG)
# enable reloading ...
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
# disable it ...
config["runtime"]["auto_reload"] = "off"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
# TODO: Invesitigate flaky on minimal CI
await asyncio.sleep(INTERVAL / 2)
# ... and reenable it
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
await k.run(
[
er_1 := exec_req.get(f"from {py_modname} import foo"),
@@ -184,7 +184,7 @@ async def test_reload_nested_module_function(
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
await k.run(
[
er_1 := exec_req.get(f"from {py_modname} import foo"),
@@ -239,7 +239,7 @@ async def test_reload_nested_module_import_module(
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
await k.run(
[
er_1 := exec_req.get(f"from {py_modname} import foo"),
@@ -296,7 +296,7 @@ async def test_reload_nested_module_import_module_autorun(
k.enqueue_control_request = lambda req: queue.put(req)
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "autorun"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
await k.run(
[
er_1 := exec_req.get(f"from {py_modname} import foo"),
@@ -344,7 +344,7 @@ async def test_reload_package(
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
await k.run(
[
er_1 := exec_req.get(f"import {b_name}"),
@@ -396,7 +396,7 @@ async def test_reload_third_party(
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
await k.run(
[
er_1 := exec_req.get(f"from {py_modname} import foo"),
@@ -451,7 +451,7 @@ async def test_reload_with_modified_cell(
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
await k.run(
[
er_1 := exec_req.get(f"from {py_modname} import foo"),
@@ -509,7 +509,7 @@ async def test_reload_function_in_import_block(
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
await k.run(
[
# We will modify py_modname but not "random" ...
@@ -879,7 +879,7 @@ class TestModuleWatcherStop:
k = execution_kernel
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
# Give watcher time to start
await asyncio.sleep(INTERVAL)
@@ -901,7 +901,7 @@ class TestModuleWatcherStop:
k = execution_kernel
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
# Give watcher time to start
await asyncio.sleep(INTERVAL)
@@ -936,7 +936,7 @@ class TestModuleWatcherEdgeCases:
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
await k.run(
[
@@ -980,7 +980,7 @@ class TestModuleWatcherEdgeCases:
config = copy.deepcopy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = "lazy"
- k.set_user_config(SetUserConfigRequest(config=config))
+ k.set_user_config(UpdateUserConfigCommand(config=config))
# Run a cell with import
await k.run([er_1 := exec_req.get(f"from {py_modname} import foo")])
diff --git a/tests/_runtime/test_commands.py b/tests/_runtime/test_commands.py
new file mode 100644
index 0000000000..881b396fb1
--- /dev/null
+++ b/tests/_runtime/test_commands.py
@@ -0,0 +1,10 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._runtime.commands import kebab_case
+
+
+def test_kebab_case() -> None:
+ assert kebab_case("SomeSQLCommand") == "some-sql"
+ assert kebab_case("SomeSQL") == "some-sql"
+ assert kebab_case("MyNotificationCommand") == "my-notification"
diff --git a/tests/_runtime/test_complete.py b/tests/_runtime/test_complete.py
index dc817ff030..151c0ef49a 100644
--- a/tests/_runtime/test_complete.py
+++ b/tests/_runtime/test_complete.py
@@ -16,6 +16,7 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.notification import CompletionResultNotification
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage, Stream
+from marimo._runtime.commands import CodeCompletionCommand
from marimo._runtime.complete import (
_build_docstring_cached,
_maybe_get_key_options,
@@ -23,7 +24,6 @@ from marimo._runtime.complete import (
complete,
)
from marimo._runtime.patches import patch_jedi_parameter_completion
-from marimo._runtime.requests import CodeCompletionRequest
from marimo._types.ids import CellId_t
from tests.mocks import snapshotter
@@ -469,7 +469,7 @@ mixed_keys = {"static_key": "foo", str(random.randint(0, 10)): "bar"}
lock = threading.RLock()
local_stream = CaptureStream()
- completion_request = CodeCompletionRequest(
+ completion_request = CodeCompletionCommand(
id="request_id",
document=document,
cell_id=current_cell_id,
diff --git a/tests/_runtime/test_control_flow.py b/tests/_runtime/test_control_flow.py
index 783c00b30e..c420a30a08 100644
--- a/tests/_runtime/test_control_flow.py
+++ b/tests/_runtime/test_control_flow.py
@@ -2,7 +2,7 @@
from __future__ import annotations
from marimo._runtime import control_flow
-from marimo._runtime.requests import ExecutionRequest
+from marimo._runtime.commands import ExecuteCellCommand
from marimo._runtime.runner import cell_runner
from marimo._runtime.runtime import Kernel
@@ -11,11 +11,11 @@ async def test_stop_false(execution_kernel: Kernel) -> None:
k = execution_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code="import marimo as mo; x = 0; mo.stop(False); y = 1",
),
- ExecutionRequest(cell_id="1", code="z = y + 1"),
+ ExecuteCellCommand(cell_id="1", code="z = y + 1"),
]
)
assert k.globals["x"] == 0
@@ -28,8 +28,8 @@ async def test_stop_true(execution_kernel: Kernel) -> None:
# Populate the kernel and its globals
await k.run(
[
- ExecutionRequest(cell_id="0", code="x = 0; y = 1"),
- ExecutionRequest(cell_id="1", code="z = y + 1"),
+ ExecuteCellCommand(cell_id="0", code="x = 0; y = 1"),
+ ExecuteCellCommand(cell_id="1", code="z = y + 1"),
]
)
assert k.globals["x"] == 0
@@ -39,7 +39,7 @@ async def test_stop_true(execution_kernel: Kernel) -> None:
# Force cell 0 to stop
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code="import marimo as mo; x = 0; mo.stop(True); y = 1",
),
@@ -58,7 +58,7 @@ async def test_stop_output(execution_kernel: Kernel) -> None:
# Run a cell through the kernel to populate graph
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code="import marimo as mo; x = 0; mo.stop(True, 'stopped!'); y = 1", # noqa: E501
),
diff --git a/tests/_runtime/test_dotenv.py b/tests/_runtime/test_dotenv.py
index 878774b264..cf4bae0e3e 100644
--- a/tests/_runtime/test_dotenv.py
+++ b/tests/_runtime/test_dotenv.py
@@ -6,9 +6,9 @@ import tempfile
import pytest
from marimo._config.config import merge_default_config
-from marimo._runtime.requests import (
- CreationRequest,
- SetUIElementValueRequest,
+from marimo._runtime.commands import (
+ CreateNotebookCommand,
+ UpdateUIElementCommand,
)
from marimo._utils.platform import is_windows
from tests.conftest import MockedKernel
@@ -82,9 +82,9 @@ async def test_load_dotenv_on_instantiate(mocked_kernel: MockedKernel):
mocked_kernel.k.user_config = custom_config
# Create a CreationRequest
- request = CreationRequest(
+ request = CreateNotebookCommand(
execution_requests=(),
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
values=[],
),
diff --git a/tests/_runtime/test_manage_script_metadata.py b/tests/_runtime/test_manage_script_metadata.py
index c4f755d1e1..bf9861277e 100644
--- a/tests/_runtime/test_manage_script_metadata.py
+++ b/tests/_runtime/test_manage_script_metadata.py
@@ -16,16 +16,16 @@ from marimo._messaging.notification import (
InstallingPackageAlertNotification,
MissingPackageAlertNotification,
)
+from marimo._runtime.commands import (
+ CommandMessage,
+ InstallPackagesCommand,
+)
from marimo._runtime.packages.package_managers import create_package_manager
from marimo._runtime.packages.pypi_package_manager import (
MicropipPackageManager,
PipPackageManager,
)
from marimo._runtime.packages.utils import is_python_isolated
-from marimo._runtime.requests import (
- ControlRequest,
- InstallMissingPackagesRequest,
-)
from marimo._runtime.runner import cell_runner
from tests.conftest import MockedKernel
@@ -235,7 +235,7 @@ async def test_install_missing_packages_micropip(
with patch("micropip.install", new_callable=AsyncMock) as mock_install:
await k.packages_callbacks.install_missing_packages(
- InstallMissingPackagesRequest(
+ InstallPackagesCommand(
manager="micropip",
versions={"barbaz": "", "foobar": ""},
)
@@ -255,7 +255,7 @@ async def test_install_missing_packages_micropip_with_versions(
with patch("micropip.install", new_callable=AsyncMock) as mock_install:
await k.packages_callbacks.install_missing_packages(
- InstallMissingPackagesRequest(
+ InstallPackagesCommand(
manager="micropip",
versions={"numpy": "1.22.0", "pandas": "1.5.0"},
)
@@ -279,7 +279,7 @@ async def test_install_missing_packages_micropip_other_modules(
with patch("micropip.install", new_callable=AsyncMock) as mock_install:
await k.packages_callbacks.install_missing_packages(
- InstallMissingPackagesRequest(
+ InstallPackagesCommand(
manager="micropip",
versions={},
)
@@ -297,12 +297,12 @@ async def test_missing_packages_hook(
) -> None:
"""Test that missing_packages_hook correctly handles missing packages for micropip"""
k = mocked_kernel.k
- control_requests: list[ControlRequest] = []
+ control_requests: list[CommandMessage] = []
broadcast_messages: list[
InstallingPackageAlertNotification | MissingPackageAlertNotification
] = []
- def mock_enqueue(request: ControlRequest) -> None:
+ def mock_enqueue(request: CommandMessage) -> None:
control_requests.append(request)
def mock_broadcast(
@@ -354,7 +354,7 @@ async def test_missing_packages_hook(
# Should create install request
assert len(control_requests) == 1
request = control_requests[0]
- assert isinstance(request, InstallMissingPackagesRequest)
+ assert isinstance(request, InstallPackagesCommand)
assert request.manager == package_manager.name
assert request.versions == {
"numpy": "",
@@ -397,7 +397,7 @@ async def test_missing_packages_hook(
# Should create install request with all missing packages
assert len(control_requests) == 1
request = control_requests[0]
- assert isinstance(request, InstallMissingPackagesRequest)
+ assert isinstance(request, InstallPackagesCommand)
assert request.manager == package_manager.name
assert request.versions == {
"grouped-one": "",
@@ -419,7 +419,7 @@ async def test_missing_packages_hook(
# Should only include packages not yet attempted
assert len(control_requests) == 1
request = control_requests[0]
- assert isinstance(request, InstallMissingPackagesRequest)
+ assert isinstance(request, InstallPackagesCommand)
assert request.manager == package_manager.name
assert request.versions == {
"grouped-one": "",
@@ -435,12 +435,12 @@ def test_missing_packages_hook_pip(
) -> None:
"""Test that missing_packages_hook correctly handles missing packages for pip"""
k = mocked_kernel.k
- control_requests: list[ControlRequest] = []
+ control_requests: list[CommandMessage] = []
broadcast_messages: list[
InstallingPackageAlertNotification | MissingPackageAlertNotification
] = []
- def mock_enqueue(request: ControlRequest) -> None:
+ def mock_enqueue(request: CommandMessage) -> None:
control_requests.append(request)
def mock_broadcast(
@@ -509,7 +509,7 @@ def test_missing_packages_hook_pip(
# Should create install request with all missing packages
assert len(control_requests) == 1
request = control_requests[0]
- assert isinstance(request, InstallMissingPackagesRequest)
+ assert isinstance(request, InstallPackagesCommand)
assert request.manager == "pip"
assert request.versions == {
"ibis-framework[duckdb]": "",
@@ -560,9 +560,7 @@ async def test_install_missing_packages_with_streaming_logs(
),
):
# Create install request
- request = InstallMissingPackagesRequest(
- manager="pip", versions={"numpy": ""}
- )
+ request = InstallPackagesCommand(manager="pip", versions={"numpy": ""})
await k.packages_callbacks.install_missing_packages(request)
@@ -634,7 +632,7 @@ async def test_install_missing_packages_streaming_logs_failure(
"marimo._runtime.runtime.broadcast_notification", mock_broadcast
),
):
- request = InstallMissingPackagesRequest(
+ request = InstallPackagesCommand(
manager="pip", versions={"nonexistent-package": ""}
)
@@ -697,7 +695,7 @@ async def test_install_missing_packages_streaming_logs_multiple_packages(
"marimo._runtime.runtime.broadcast_notification", mock_broadcast
),
):
- request = InstallMissingPackagesRequest(
+ request = InstallPackagesCommand(
manager="pip", versions={"numpy": "", "pandas": "", "scipy": ""}
)
@@ -771,7 +769,7 @@ async def test_install_missing_packages_no_logs_backward_compatibility(
"marimo._runtime.runtime.broadcast_notification", mock_broadcast
),
):
- request = InstallMissingPackagesRequest(
+ request = InstallPackagesCommand(
manager="pip", versions={"requests": ""}
)
diff --git a/tests/_runtime/test_requests.py b/tests/_runtime/test_requests.py
index a4202a1964..9171a28148 100644
--- a/tests/_runtime/test_requests.py
+++ b/tests/_runtime/test_requests.py
@@ -6,7 +6,7 @@ from typing import Any, Optional
from starlette.datastructures import URL, Headers, QueryParams
from starlette.requests import HTTPConnection
-from marimo._runtime.requests import HTTPRequest
+from marimo._runtime.commands import HTTPRequest
class MockHTTPConnection(HTTPConnection):
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 304645a165..33e0257e81 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -31,18 +31,18 @@ from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import NoopStream
from marimo._plugins.ui._core.ids import IDProvider
from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._runtime.commands import (
+ AppMetadata,
+ CreateNotebookCommand,
+ DeleteCellCommand,
+ ExecuteCellCommand,
+ UpdateCellConfigCommand,
+ UpdateUIElementCommand,
+)
from marimo._runtime.context.kernel_context import initialize_kernel_context
from marimo._runtime.context.types import teardown_context
from marimo._runtime.dataflow import EdgeWithVar
from marimo._runtime.patches import create_main_module
-from marimo._runtime.requests import (
- AppMetadata,
- CreationRequest,
- DeleteCellRequest,
- ExecutionRequest,
- SetCellConfigRequest,
- SetUIElementValueRequest,
-)
from marimo._runtime.runtime import Kernel, notebook_dir, notebook_location
from marimo._runtime.scratch import SCRATCH_CELL_ID
from marimo._server.model import SessionMode
@@ -69,7 +69,7 @@ class TestExecution:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0", code="assert __file__; success = 1"
)
]
@@ -94,9 +94,9 @@ class TestExecution:
# x, y --> z
await k.run(
[
- ExecutionRequest(cell_id="0", code="x = 1"),
- er1 := ExecutionRequest(cell_id="1", code="y = x + 1"),
- er2 := ExecutionRequest(cell_id="2", code="z = x + y"),
+ ExecuteCellCommand(cell_id="0", code="x = 1"),
+ er1 := ExecuteCellCommand(cell_id="1", code="y = x + 1"),
+ er2 := ExecuteCellCommand(cell_id="2", code="z = x + y"),
]
)
@@ -105,7 +105,7 @@ class TestExecution:
assert k.globals["y"] == 2
assert k.globals["z"] == 3
- await k.run([ExecutionRequest(cell_id="0", code="x = 2")])
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 2")])
assert not k.graph.cells["0"].stale
assert k.globals["x"] == 2
if k.lazy():
@@ -125,7 +125,7 @@ class TestExecution:
assert not k.graph.cells["1"].stale
assert not k.graph.cells["2"].stale
- await k.run([ExecutionRequest(cell_id="1", code="y = 0")])
+ await k.run([ExecuteCellCommand(cell_id="1", code="y = 0")])
assert not k.graph.cells["0"].stale
assert not k.graph.cells["1"].stale
assert k.globals["x"] == 2
@@ -135,7 +135,7 @@ class TestExecution:
await k.run([er2])
assert k.globals["z"] == 2
- await k.delete_cell(DeleteCellRequest(cell_id="1"))
+ await k.delete_cell(DeleteCellCommand(cell_id="1"))
assert k.globals["x"] == 2
assert "y" not in k.globals
if k.lazy():
@@ -143,7 +143,7 @@ class TestExecution:
await k.run([er2])
assert "z" not in k.globals
- await k.delete_cell(DeleteCellRequest(cell_id="0"))
+ await k.delete_cell(DeleteCellCommand(cell_id="0"))
assert "x" not in k.globals
assert "y" not in k.globals
assert "z" not in k.globals
@@ -156,9 +156,9 @@ class TestExecution:
# as stale
await k.run(
[
- ExecutionRequest(cell_id="0", code="x = 1"),
- er1 := ExecutionRequest(cell_id="1", code="x"),
- er2 := ExecutionRequest(cell_id="2", code="x"),
+ ExecuteCellCommand(cell_id="0", code="x = 1"),
+ er1 := ExecuteCellCommand(cell_id="1", code="x"),
+ er2 := ExecuteCellCommand(cell_id="2", code="x"),
]
)
assert not graph.get_stale()
@@ -172,23 +172,23 @@ class TestExecution:
async def test_set_ui_element_value(self, any_kernel: Kernel) -> None:
k = any_kernel
await k.run(
- [ExecutionRequest(cell_id="0", code="import marimo as mo")]
+ [ExecuteCellCommand(cell_id="0", code="import marimo as mo")]
)
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1", code="s = mo.ui.slider(0, 10, value=1); s"
)
]
)
await k.run(
- [er2 := ExecutionRequest(cell_id="2", code="x = s.value + 1")]
+ [er2 := ExecuteCellCommand(cell_id="2", code="x = s.value + 1")]
)
assert k.globals["x"] == 2
element_id = k.globals["s"]._id
await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values([(element_id, 5)])
+ UpdateUIElementCommand.from_ids_and_values([(element_id, 5)])
)
assert k.globals["s"].value == 5
@@ -231,7 +231,7 @@ class TestExecution:
# Set a child of the array to 5 ...
child_id = k.globals["array"][0]._id
await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values([(child_id, 5)])
+ UpdateUIElementCommand.from_ids_and_values([(child_id, 5)])
)
# Make sure the array and its child are updated
@@ -269,9 +269,7 @@ class TestExecution:
array_id = k.globals["array"]._id
await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values(
- [(array_id, {"0": 5})]
- )
+ UpdateUIElementCommand.from_ids_and_values([(array_id, {"0": 5})])
)
assert k.globals["array"].value == [5]
if k.lazy():
@@ -302,7 +300,7 @@ class TestExecution:
# called
child_id = k.globals["array"][0]._id
await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values([(child_id, 5)])
+ UpdateUIElementCommand.from_ids_and_values([(child_id, 5)])
)
if k.lazy():
assert k.graph.cells[er.cell_id].stale
@@ -315,9 +313,9 @@ class TestExecution:
self, any_kernel: Kernel
) -> None:
k = any_kernel
- await k.run([ExecutionRequest("0", "import marimo as mo")])
+ await k.run([ExecuteCellCommand("0", "import marimo as mo")])
await k.run(
- [ExecutionRequest("1", "_s = mo.ui.slider(0, 10, value=1); _s")]
+ [ExecuteCellCommand("1", "_s = mo.ui.slider(0, 10, value=1); _s")]
)
# _s's name is mangled to _cell_1_s because it is local
assert k.globals["_cell_1_s"].value == 1
@@ -326,7 +324,7 @@ class TestExecution:
# This shouldn't crash the kernel, and s's value should still be
# updated
await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values([(element_id, 5)])
+ UpdateUIElementCommand.from_ids_and_values([(element_id, 5)])
)
assert k.globals["_cell_1_s"].value == 5
@@ -336,14 +334,16 @@ class TestExecution:
k = any_kernel
id_provider = IDProvider(prefix="1")
await k.instantiate(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(
- ExecutionRequest(cell_id="0", code="import marimo as mo"),
- ExecutionRequest(
+ ExecuteCellCommand(
+ cell_id="0", code="import marimo as mo"
+ ),
+ ExecuteCellCommand(
cell_id="1", code="s = mo.ui.slider(0, 10, value=1)"
),
),
- set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[(id_provider.take_id(), 2)]
),
auto_run=True,
@@ -354,13 +354,13 @@ class TestExecution:
async def test_instantiate_autorun_false(self, any_kernel: Kernel) -> None:
k = any_kernel
await k.instantiate(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(
- ExecutionRequest(cell_id="0", code="x=0"),
- er1 := ExecutionRequest(cell_id="1", code="y=x+1"),
- er2 := ExecutionRequest(cell_id="2", code="z=x+2"),
+ ExecuteCellCommand(cell_id="0", code="x=0"),
+ er1 := ExecuteCellCommand(cell_id="1", code="y=x+1"),
+ er2 := ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
- set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
auto_run=False,
@@ -389,13 +389,13 @@ class TestExecution:
) -> None:
k = any_kernel
await k.instantiate(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="y=x+1"),
- ExecutionRequest(cell_id="2", code="z=x+2"),
+ ExecuteCellCommand(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code="y=x+1"),
+ ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
- set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
auto_run=False,
@@ -416,13 +416,13 @@ class TestExecution:
) -> None:
k = any_kernel
await k.instantiate(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(
- er1 := ExecutionRequest(cell_id="0", code="x=0"),
- er2 := ExecutionRequest(cell_id="1", code="y=x+1"),
- er3 := ExecutionRequest(cell_id="2", code="z=x+2"),
+ er1 := ExecuteCellCommand(cell_id="0", code="x=0"),
+ er2 := ExecuteCellCommand(cell_id="1", code="y=x+1"),
+ er3 := ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
- set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
auto_run=False,
@@ -444,13 +444,13 @@ class TestExecution:
"""Tests that cells are set to not stale before they start running."""
k = any_kernel
await k.instantiate(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(
- er1 := ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="y=x+1"),
- ExecutionRequest(cell_id="2", code="z=x+2"),
+ er1 := ExecuteCellCommand(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code="y=x+1"),
+ ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
- set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
auto_run=False,
@@ -486,13 +486,13 @@ class TestExecution:
) -> None:
k = any_kernel
await k.instantiate(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="y=x+1"),
- ExecutionRequest(cell_id="2", code="z=x+2"),
+ ExecuteCellCommand(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code="y=x+1"),
+ ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
- set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
auto_run=False,
@@ -500,13 +500,13 @@ class TestExecution:
)
assert len(k._uninstantiated_execution_requests) == 3
- await k.delete_cell(DeleteCellRequest(cell_id="0"))
+ await k.delete_cell(DeleteCellCommand(cell_id="0"))
assert len(k._uninstantiated_execution_requests) == 2
- await k.delete_cell(DeleteCellRequest(cell_id="1"))
+ await k.delete_cell(DeleteCellCommand(cell_id="1"))
assert len(k._uninstantiated_execution_requests) == 1
- await k.delete_cell(DeleteCellRequest(cell_id="2"))
+ await k.delete_cell(DeleteCellCommand(cell_id="2"))
assert not k._uninstantiated_execution_requests
async def test_instantiate_autorun_false_run_different_code(
@@ -514,13 +514,13 @@ class TestExecution:
) -> None:
k = any_kernel
await k.instantiate(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(
- ExecutionRequest(cell_id="0", code="x=0"),
- er1 := ExecutionRequest(cell_id="1", code="y=x+1"),
- er2 := ExecutionRequest(cell_id="2", code="z=x+2"),
+ ExecuteCellCommand(cell_id="0", code="x=0"),
+ er1 := ExecuteCellCommand(cell_id="1", code="y=x+1"),
+ er2 := ExecuteCellCommand(cell_id="2", code="z=x+2"),
),
- set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
auto_run=False,
@@ -530,7 +530,7 @@ class TestExecution:
# modify an uninstantiated cell before running it; make sure the old
# er gets evicted.
- await k.run([ExecutionRequest(cell_id="0", code="x = 1")])
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
assert len(k._uninstantiated_execution_requests) == 2
assert k.globals["x"] == 1
@@ -548,14 +548,14 @@ class TestExecution:
"""Tests that empty cells are not marked as stale during instantiation."""
k = any_kernel
await k.instantiate(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code=""),
- ExecutionRequest(cell_id="2", code=" \n "),
- ExecutionRequest(cell_id="3", code="y=x+1"),
+ ExecuteCellCommand(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code=""),
+ ExecuteCellCommand(cell_id="2", code=" \n "),
+ ExecuteCellCommand(cell_id="3", code="y=x+1"),
),
- set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
auto_run=False,
@@ -596,8 +596,8 @@ class TestExecution:
k = any_kernel
await k.run(
[
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="x=1"),
+ ExecuteCellCommand(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code="x=1"),
]
)
@@ -611,18 +611,18 @@ class TestExecution:
any_kernel: Kernel,
) -> None:
k = any_kernel
- await k.run([ExecutionRequest(cell_id="0", code="x=0")])
+ await k.run([ExecuteCellCommand(cell_id="0", code="x=0")])
assert k.globals["x"] == 0
assert not k.errors
# cell 0 should not be invalidated by the introduction of cell 1
- await k.run([ExecutionRequest(cell_id="1", code="x=0")])
+ await k.run([ExecuteCellCommand(cell_id="1", code="x=0")])
assert k.globals["x"] == 0
assert set(k.errors.keys()) == {"1"}
assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
# re-running cell 0 should invalidate it
- await k.run([ExecutionRequest(cell_id="0", code="x=0")])
+ await k.run([ExecuteCellCommand(cell_id="0", code="x=0")])
assert "x" not in k.globals
assert set(k.errors.keys()) == {"0", "1"}
assert k.errors["0"] == (MultipleDefinitionError("x", ("1",)),)
@@ -634,8 +634,8 @@ class TestExecution:
k = any_kernel
await k.run(
[
- er := ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="x=1"),
+ er := ExecuteCellCommand(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code="x=1"),
]
)
assert "x" not in k.globals
@@ -645,7 +645,7 @@ class TestExecution:
# Rename second occurrence of x to y; should eliminate error and run
# both cells
- await k.run([ExecutionRequest(cell_id="1", code="y=1")])
+ await k.run([ExecuteCellCommand(cell_id="1", code="y=1")])
assert k.globals["y"] == 1
if k.lazy():
assert k.graph.cells["0"].stale
@@ -660,8 +660,8 @@ class TestExecution:
k = any_kernel
await k.run(
[
- er := ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="x=1"),
+ er := ExecuteCellCommand(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code="x=1"),
]
)
assert "x" not in k.globals
@@ -670,7 +670,7 @@ class TestExecution:
assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
# issue delete request for cell 1 to clear error and run cell 0
- await k.delete_cell(DeleteCellRequest(cell_id="1"))
+ await k.delete_cell(DeleteCellCommand(cell_id="1"))
if k.lazy():
assert k.graph.cells[er.cell_id].stale
await k.run([er])
@@ -682,13 +682,13 @@ class TestExecution:
self, any_kernel: Kernel
) -> None:
k = any_kernel
- await k.run([ExecutionRequest(cell_id="0", code="x=0")])
- await k.run([ExecutionRequest(cell_id="1", code="x, y = 1, 2")])
+ await k.run([ExecuteCellCommand(cell_id="0", code="x=0")])
+ await k.run([ExecuteCellCommand(cell_id="1", code="x, y = 1, 2")])
assert set(k.errors.keys()) == {"1"}
assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
# errors propagated back to cell 1, even though we are not running it
- await k.run([ExecutionRequest(cell_id="2", code="x, y = 3, 4")])
+ await k.run([ExecuteCellCommand(cell_id="2", code="x, y = 3, 4")])
assert set(k.errors.keys()) == {"1", "2"}
assert k.errors["1"] == (
MultipleDefinitionError("x", ("0", "2")),
@@ -705,9 +705,9 @@ class TestExecution:
k = any_kernel
await k.run(
[
- ExecutionRequest(cell_id="0", code="x=y"),
- ExecutionRequest(cell_id="1", code="y=x"),
- er := ExecutionRequest(cell_id="2", code="z = x + 1"),
+ ExecuteCellCommand(cell_id="0", code="x=y"),
+ ExecuteCellCommand(cell_id="1", code="y=x"),
+ er := ExecuteCellCommand(cell_id="2", code="z = x + 1"),
]
)
assert "x" not in k.globals
@@ -730,7 +730,7 @@ class TestExecution:
)
# break cycle by modifying cell
- await k.run([ExecutionRequest(cell_id="1", code="y=1")])
+ await k.run([ExecuteCellCommand(cell_id="1", code="y=1")])
if k.lazy():
assert k.graph.cells["0"].stale
assert k.graph.cells["2"].stale
@@ -749,8 +749,8 @@ class TestExecution:
k = any_kernel
await k.run(
[
- ExecutionRequest(cell_id="0", code="x=y"),
- ExecutionRequest(cell_id="1", code="y=x"),
+ ExecuteCellCommand(cell_id="0", code="x=y"),
+ ExecuteCellCommand(cell_id="1", code="y=x"),
]
)
assert "x" not in k.globals
@@ -763,7 +763,7 @@ class TestExecution:
)
# break cycle by deleting cell
- await k.delete_cell(DeleteCellRequest(cell_id="1"))
+ await k.delete_cell(DeleteCellCommand(cell_id="1"))
if k.execution_type == "strict":
# Still invalid in strict mode because y is missing.
assert set(k.errors.keys()) == {"0"}
@@ -782,9 +782,9 @@ class TestExecution:
)
await k.run(
[
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="del x; y = 1"),
- er := ExecutionRequest(cell_id="2", code="z = y + 1"),
+ ExecuteCellCommand(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code="del x; y = 1"),
+ er := ExecuteCellCommand(cell_id="2", code="z = y + 1"),
]
)
assert "x" not in k.globals
@@ -795,8 +795,8 @@ class TestExecution:
async def test_delete_nonlocal_multiple_not_ok(self, k: Kernel) -> None:
await k.run(
[
- ExecutionRequest(cell_id="0", code="del x"),
- ExecutionRequest(cell_id="1", code="del x"),
+ ExecuteCellCommand(cell_id="0", code="del x"),
+ ExecuteCellCommand(cell_id="1", code="del x"),
]
)
assert set(k.errors.keys()) == {"0", "1"}
@@ -812,8 +812,8 @@ class TestExecution:
) -> None:
await k.run(
[
- er := ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="del x; y = 1"),
+ er := ExecuteCellCommand(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code="del x; y = 1"),
]
)
assert "x" not in k.globals
@@ -822,7 +822,7 @@ class TestExecution:
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="2",
code="""
try:
@@ -851,7 +851,7 @@ except NameError:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code="import sys as _sys; msize = _sys.maxsize",
),
@@ -867,22 +867,22 @@ except NameError:
k = lazy_kernel
await k.run(
[
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="x"),
+ ExecuteCellCommand(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code="x"),
]
)
# make cell 1 stale
await k.run(
[
- ExecutionRequest(cell_id="0", code="x=1"),
+ ExecuteCellCommand(cell_id="0", code="x=1"),
]
)
# introduce an error to cell 1; it shouldn't be stale
await k.run(
[
- ExecutionRequest(cell_id="1", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code="x=0"),
]
)
assert set(k.errors.keys()) == {"1"}
@@ -894,15 +894,15 @@ except NameError:
k = lazy_kernel
await k.run(
[
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="x"),
+ ExecuteCellCommand(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="1", code="x"),
]
)
# make cell 1 stale
await k.run(
[
- ExecutionRequest(cell_id="0", code="x=1"),
+ ExecuteCellCommand(cell_id="0", code="x=1"),
]
)
cell = k.graph.cells["1"]
@@ -911,7 +911,7 @@ except NameError:
# introduce a syntax error to cell 1; it shouldn't be stale
await k.run(
[
- ExecutionRequest(cell_id="1", code="x ^ !"),
+ ExecuteCellCommand(cell_id="1", code="x ^ !"),
]
)
assert set(k.errors.keys()) == {"1"}
@@ -929,7 +929,7 @@ except NameError:
# Syntax error on line 3 of multiline code
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0", code="x = 1\ny = 2\nz ^ !\nw = 4"
),
]
@@ -946,7 +946,7 @@ except NameError:
# Single line syntax error (should be line 1)
await k.run(
[
- ExecutionRequest(cell_id="0", code="!"),
+ ExecuteCellCommand(cell_id="0", code="!"),
]
)
assert set(k.errors.keys()) == {"0"}
@@ -962,7 +962,7 @@ except NameError:
k = any_kernel
await k.run(
[
- ExecutionRequest(cell_id="0", code="!pip install pandas"),
+ ExecuteCellCommand(cell_id="0", code="!pip install pandas"),
]
)
assert set(k.errors.keys()) == {"0"}
@@ -976,7 +976,7 @@ except NameError:
k = any_kernel
await k.run(
[
- ExecutionRequest(cell_id="0", code="!ls -la"),
+ ExecuteCellCommand(cell_id="0", code="!ls -la"),
]
)
assert set(k.errors.keys()) == {"0"}
@@ -990,7 +990,7 @@ except NameError:
k = any_kernel
await k.run(
[
- ExecutionRequest(cell_id="0", code="%timeit x = 1"),
+ ExecuteCellCommand(cell_id="0", code="%timeit x = 1"),
]
)
assert set(k.errors.keys()) == {"0"}
@@ -1005,14 +1005,14 @@ except NameError:
k = any_kernel
await k.run(
[
- ExecutionRequest(cell_id="0", code="x=0"),
+ ExecuteCellCommand(cell_id="0", code="x=0"),
]
)
# multiple definition error
await k.run(
[
- ExecutionRequest(cell_id="1", code="y; x=1"),
+ ExecuteCellCommand(cell_id="1", code="y; x=1"),
]
)
@@ -1020,7 +1020,7 @@ except NameError:
# is errored and its error is up-to-date, so don't mark it as stale.
await k.run(
[
- ExecutionRequest(cell_id="0", code="y = 0; x=1"),
+ ExecuteCellCommand(cell_id="0", code="y = 0; x=1"),
]
)
@@ -1034,9 +1034,9 @@ except NameError:
await k.run(
[
- ExecutionRequest(cell_id=SETUP_CELL_NAME, code="x=0"),
+ ExecuteCellCommand(cell_id=SETUP_CELL_NAME, code="x=0"),
# NB. no explicit tie from setup to er.
- er := ExecutionRequest(cell_id="1", code="y=1"),
+ er := ExecuteCellCommand(cell_id="1", code="y=1"),
]
)
assert not k.graph.get_stale()
@@ -1044,7 +1044,7 @@ except NameError:
assert k.globals["y"] == 1
assert not k.errors
- await k.run([ExecutionRequest(cell_id=SETUP_CELL_NAME, code="x=")])
+ await k.run([ExecuteCellCommand(cell_id=SETUP_CELL_NAME, code="x=")])
assert SETUP_CELL_NAME not in k.graph.cells
assert "1" in k.graph.cells
assert "x" not in k.globals
@@ -1057,7 +1057,7 @@ except NameError:
assert "y" in k.globals
# fix syntax error
- await k.run([ExecutionRequest(cell_id=SETUP_CELL_NAME, code="x=0")])
+ await k.run([ExecuteCellCommand(cell_id=SETUP_CELL_NAME, code="x=0")])
assert k.globals["x"] == 0
assert SETUP_CELL_NAME in k.graph.cells
assert "1" in k.graph.cells
@@ -1079,8 +1079,8 @@ except NameError:
k = any_kernel
await k.run(
[
- ExecutionRequest(cell_id="0", code="x=0"),
- er := ExecutionRequest(cell_id="1", code="x; y = 1"),
+ ExecuteCellCommand(cell_id="0", code="x=0"),
+ er := ExecuteCellCommand(cell_id="1", code="x; y = 1"),
]
)
assert not k.graph.get_stale()
@@ -1088,7 +1088,7 @@ except NameError:
assert k.globals["y"] == 1
assert not k.errors
- await k.run([ExecutionRequest(cell_id="0", code="x=")])
+ await k.run([ExecuteCellCommand(cell_id="0", code="x=")])
assert "0" not in k.graph.cells
assert "1" in k.graph.cells
assert "x" not in k.globals
@@ -1099,7 +1099,7 @@ except NameError:
assert "y" not in k.globals
# fix syntax error
- await k.run([ExecutionRequest(cell_id="0", code="x=0")])
+ await k.run([ExecuteCellCommand(cell_id="0", code="x=0")])
assert k.globals["x"] == 0
assert "0" in k.graph.cells
assert "1" in k.graph.cells
@@ -1127,7 +1127,7 @@ except NameError:
# "y" should not be computed, and its global state should have been
# invalidated
await k.run(
- [ExecutionRequest(er_1.cell_id, "x = 0; raise RuntimeError")]
+ [ExecuteCellCommand(er_1.cell_id, "x = 0; raise RuntimeError")]
)
if k.lazy():
assert graph.get_stale() == set([er_2.cell_id])
@@ -1173,7 +1173,7 @@ except NameError:
element_id = k.globals["defs"]["slider"]._id
await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values([(element_id, 5)])
+ UpdateUIElementCommand.from_ids_and_values([(element_id, 5)])
)
assert k.globals["defs"]["slider"].value == 5
if k.lazy():
@@ -1192,7 +1192,7 @@ except NameError:
# smoke test -- this shouldn't raise an exception
k = any_kernel
await k.set_ui_element_value(
- SetUIElementValueRequest.from_ids_and_values(
+ UpdateUIElementCommand.from_ids_and_values(
[("does not exist", None)]
)
)
@@ -1546,7 +1546,7 @@ except NameError:
k = any_kernel
er_1 = exec_req.get("x = 0")
await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ UpdateCellConfigCommand(configs={er_1.cell_id: {"disabled": True}})
)
await k.run([er_1])
assert k.graph.cells[er_1.cell_id].config.disabled
@@ -1621,7 +1621,7 @@ except NameError:
k = execution_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -1633,7 +1633,7 @@ except NameError:
"""
),
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1",
code=textwrap.dedent(
"""
@@ -1756,7 +1756,7 @@ except NameError:
) -> None:
await k.run([er := exec_req.get("_x = 1")])
assert k.globals[f"_cell_{er.cell_id}_x"] == 1
- await k.run([ExecutionRequest(er.cell_id, "None")])
+ await k.run([ExecuteCellCommand(er.cell_id, "None")])
assert f"_cell_{er.cell_id}_x" not in k.globals
async def test_has_run_id(
@@ -1790,9 +1790,9 @@ except NameError:
# Setup: Create initial graph state with dependencies
await k.run(
[
- ExecutionRequest(cell_id="0", code="x = 1"),
- ExecutionRequest(cell_id="1", code="y = x + 1"),
- ExecutionRequest(cell_id="2", code="z = y + 1"),
+ ExecuteCellCommand(cell_id="0", code="x = 1"),
+ ExecuteCellCommand(cell_id="1", code="y = x + 1"),
+ ExecuteCellCommand(cell_id="2", code="z = y + 1"),
]
)
assert k.globals["x"] == 1
@@ -1818,9 +1818,9 @@ except NameError:
# Setup: Create 3 cells
await k.run(
[
- ExecutionRequest(cell_id="0", code="x = 1"),
- ExecutionRequest(cell_id="1", code="y = x + 1"),
- ExecutionRequest(cell_id="2", code="z = y + 1"),
+ ExecuteCellCommand(cell_id="0", code="x = 1"),
+ ExecuteCellCommand(cell_id="1", code="y = x + 1"),
+ ExecuteCellCommand(cell_id="2", code="z = y + 1"),
]
)
assert "z" in k.globals
@@ -1849,10 +1849,10 @@ except NameError:
# Setup: Kernel has A, B, C, D
await k.run(
[
- ExecutionRequest(cell_id="0", code="a = 1"),
- ExecutionRequest(cell_id="1", code="b = 2"),
- ExecutionRequest(cell_id="2", code="c = 3"),
- ExecutionRequest(cell_id="3", code="d = 4"),
+ ExecuteCellCommand(cell_id="0", code="a = 1"),
+ ExecuteCellCommand(cell_id="1", code="b = 2"),
+ ExecuteCellCommand(cell_id="2", code="c = 3"),
+ ExecuteCellCommand(cell_id="3", code="d = 4"),
]
)
assert len(k.graph.cells) == 4
@@ -1883,13 +1883,13 @@ except NameError:
k = any_kernel
# Setup: Instantiate with autorun=False, then run some cells
await k.instantiate(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(
- ExecutionRequest(cell_id="0", code="x = 0"),
- ExecutionRequest(cell_id="1", code="y = 1"),
- ExecutionRequest(cell_id="2", code="z = 2"),
+ ExecuteCellCommand(cell_id="0", code="x = 0"),
+ ExecuteCellCommand(cell_id="1", code="y = 1"),
+ ExecuteCellCommand(cell_id="2", code="z = 2"),
),
- set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
auto_run=False,
@@ -1900,8 +1900,8 @@ except NameError:
# Run cells 0 and 1 to add them to graph, keeping cell 2 uninstantiated
await k.run(
[
- ExecutionRequest(cell_id="0", code="x = 0"),
- ExecutionRequest(cell_id="1", code="y = 1"),
+ ExecuteCellCommand(cell_id="0", code="x = 0"),
+ ExecuteCellCommand(cell_id="1", code="y = 1"),
]
)
# Cell 2 is still uninstantiated, cells 0 and 1 are in graph
@@ -1932,9 +1932,9 @@ except NameError:
# Setup: Create A→B→C dependency chain
await k.run(
[
- ExecutionRequest(cell_id="0", code="x = 1"),
- ExecutionRequest(cell_id="1", code="y = x + 1"),
- ExecutionRequest(cell_id="2", code="z = y + 1"),
+ ExecuteCellCommand(cell_id="0", code="x = 1"),
+ ExecuteCellCommand(cell_id="1", code="y = x + 1"),
+ ExecuteCellCommand(cell_id="2", code="z = y + 1"),
]
)
assert k.globals["z"] == 3
@@ -1964,7 +1964,7 @@ except NameError:
# Setup: Cell 0 defines x
await k.run(
[
- ExecutionRequest(cell_id="0", code="x = 1"),
+ ExecuteCellCommand(cell_id="0", code="x = 1"),
]
)
assert "x" in k.globals
@@ -1990,8 +1990,8 @@ except NameError:
# Setup: Create cells
await k.run(
[
- ExecutionRequest(cell_id="0", code="x = 1"),
- ExecutionRequest(cell_id="1", code="y = 2"),
+ ExecuteCellCommand(cell_id="0", code="x = 1"),
+ ExecuteCellCommand(cell_id="1", code="y = 2"),
]
)
assert k.globals["x"] == 1
@@ -2013,7 +2013,7 @@ except NameError:
async def test_missing_module_detected(self, any_kernel: Kernel) -> None:
k = any_kernel
await k.run(
- [er := ExecutionRequest(cell_id="0", code="import foobar")]
+ [er := ExecuteCellCommand(cell_id="0", code="import foobar")]
)
cell = k.graph.cells[er.cell_id]
assert cell.exception is not None
@@ -2021,7 +2021,7 @@ except NameError:
assert cell.exception.name == "foobar"
await k.run(
- [er := ExecutionRequest(cell_id="0", code="import marimo")]
+ [er := ExecuteCellCommand(cell_id="0", code="import marimo")]
)
cell = k.graph.cells[er.cell_id]
assert cell.exception is None
@@ -2204,7 +2204,7 @@ class TestStrictExecution:
k = execution_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -2237,7 +2237,7 @@ class TestStrictExecution:
# succeed
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -2249,7 +2249,7 @@ class TestStrictExecution:
"""
),
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1",
code=textwrap.dedent(
"""
@@ -2271,7 +2271,7 @@ class TestStrictExecution:
# succeed
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -2283,7 +2283,7 @@ class TestStrictExecution:
"""
),
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1",
code=textwrap.dedent(
"""
@@ -2331,7 +2331,7 @@ class TestImports:
# of already imported modules
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id=er.cell_id, code="import random; import time"
)
]
@@ -2350,7 +2350,7 @@ class TestImports:
)
assert "x" not in k.globals
- await k.delete_cell(DeleteCellRequest(cell_id=er.cell_id))
+ await k.delete_cell(DeleteCellCommand(cell_id=er.cell_id))
assert "x" in k.globals
async def test_different_import_same_def(
@@ -2364,7 +2364,7 @@ class TestImports:
# er.cell_id is still an import block, still defines random,
# but brings random from another place; descendant should run
await k.run(
- [ExecutionRequest(er.cell_id, code="from random import random")]
+ [ExecuteCellCommand(er.cell_id, code="from random import random")]
)
assert "random" in k.globals
# randint is on toplevel random, not random.random
@@ -2381,7 +2381,7 @@ class TestImports:
)
assert "x" not in k.globals
- await k.run([ExecutionRequest(er.cell_id, code="import time")])
+ await k.run([ExecuteCellCommand(er.cell_id, code="import time")])
assert k.globals["x"] == 1
@@ -2590,14 +2590,16 @@ class TestDisable:
# shouldn't have passed through stale status
# disable cell 2
await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
+ UpdateCellConfigCommand(configs={er_2.cell_id: {"disabled": True}})
)
assert k.globals["ns"].count == 1
assert not graph.get_stale()
# re-enable cell 2
await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
+ UpdateCellConfigCommand(
+ configs={er_2.cell_id: {"disabled": False}}
+ )
)
# cell 2 should **not** have re-run
assert k.globals["ns"].count == 1
@@ -2629,7 +2631,7 @@ class TestDisable:
# disable and re-enable cell 2, making it stale in between;
# cell 2 should re-run on enable
await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
+ UpdateCellConfigCommand(configs={er_2.cell_id: {"disabled": True}})
)
await k.run(
[
@@ -2652,7 +2654,9 @@ class TestDisable:
# re-enable cell 2
await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
+ UpdateCellConfigCommand(
+ configs={er_2.cell_id: {"disabled": False}}
+ )
)
if k.lazy():
assert k.graph.get_stale() == set([er_2.cell_id])
@@ -2687,10 +2691,10 @@ class TestDisable:
# disable cell 2
await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
+ UpdateCellConfigCommand(configs={er_2.cell_id: {"disabled": True}})
)
- await k.run([ExecutionRequest(cell_id=er_1.cell_id, code="x = 2")])
+ await k.run([ExecuteCellCommand(cell_id=er_1.cell_id, code="x = 2")])
assert k.globals["x"] == 2
if k.lazy():
assert graph.get_stale() == set(
@@ -2704,7 +2708,9 @@ class TestDisable:
# enable cell 2: should run stale cells as a side-effect
await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
+ UpdateCellConfigCommand(
+ configs={er_2.cell_id: {"disabled": False}}
+ )
)
assert k.globals["x"] == 2
assert k.globals["zzz"] == 3
@@ -2737,10 +2743,10 @@ class TestDisable:
# disable both cells
await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ UpdateCellConfigCommand(configs={er_1.cell_id: {"disabled": True}})
)
await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
+ UpdateCellConfigCommand(configs={er_2.cell_id: {"disabled": True}})
)
# update the code of cell 1 -- both cells stale
await k.run([er_1 := exec_req.get_with_id(er_1.cell_id, "x = 2")])
@@ -2748,7 +2754,9 @@ class TestDisable:
# enable cell 1, but 2 still disabled
await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
+ UpdateCellConfigCommand(
+ configs={er_1.cell_id: {"disabled": False}}
+ )
)
if k.lazy():
assert graph.get_stale() == set([er_1.cell_id, er_2.cell_id])
@@ -2759,7 +2767,9 @@ class TestDisable:
# enable cell 2
await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
+ UpdateCellConfigCommand(
+ configs={er_2.cell_id: {"disabled": False}}
+ )
)
if k.lazy():
assert graph.get_stale() == set([er_2.cell_id])
@@ -2783,7 +2793,7 @@ class TestDisable:
# disable cell
await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ UpdateCellConfigCommand(configs={er_1.cell_id: {"disabled": True}})
)
# add a syntax error
@@ -2797,7 +2807,9 @@ class TestDisable:
# enable: should run
await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
+ UpdateCellConfigCommand(
+ configs={er_1.cell_id: {"disabled": False}}
+ )
)
if k.lazy():
assert graph.cells[er_1.cell_id].stale
@@ -2817,16 +2829,18 @@ class TestDisable:
]
)
await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ UpdateCellConfigCommand(configs={er_1.cell_id: {"disabled": True}})
)
assert k.graph.cells[er_1.cell_id].config.disabled
assert k.graph.cells[er_2.cell_id].disabled_transitively
await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
+ UpdateCellConfigCommand(configs={er_2.cell_id: {"disabled": True}})
)
await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
+ UpdateCellConfigCommand(
+ configs={er_1.cell_id: {"disabled": False}}
+ )
)
assert k.graph.cells[er_1.cell_id].disabled_transitively
assert k.graph.cells[er_2.cell_id].config.disabled
@@ -2837,7 +2851,7 @@ class TestDisable:
assert k.graph.cells[er_2.cell_id].config.disabled
# breaking the cycle should re-enable
- await k.run([ExecutionRequest(cell_id=er_1.cell_id, code="a = 0")])
+ await k.run([ExecuteCellCommand(cell_id=er_1.cell_id, code="a = 0")])
assert not k.graph.cells[er_1.cell_id].stale
assert not k.graph.cells[er_1.cell_id].disabled_transitively
@@ -2852,7 +2866,7 @@ class TestDisable:
k = any_kernel
await k.run([er_1 := exec_req.get("a = b")])
await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ UpdateCellConfigCommand(configs={er_1.cell_id: {"disabled": True}})
)
assert k.graph.cells[er_1.cell_id].config.disabled
@@ -2870,13 +2884,15 @@ class TestDisable:
]
)
await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ UpdateCellConfigCommand(configs={er_1.cell_id: {"disabled": True}})
)
assert k.graph.cells[er_1.cell_id].config.disabled
assert k.graph.cells[er_2.cell_id].disabled_transitively
await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
+ UpdateCellConfigCommand(
+ configs={er_1.cell_id: {"disabled": False}}
+ )
)
assert not k.graph.cells[er_1.cell_id].config.disabled
assert not k.graph.cells[er_2.cell_id].disabled_transitively
@@ -3112,11 +3128,11 @@ class TestSQL:
async def test_sql_table(self, k: Kernel) -> None:
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code="import marimo as mo",
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1", code="df = mo.sql('SELECT * from t1')"
),
]
@@ -3125,13 +3141,13 @@ class TestSQL:
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="2",
code="import polars as pl; t1_df = pl.from_dict({'a': [42]})", # noqa: E501
),
# cell 1 should automatically execute due to the definition of
# t1
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="3",
code="mo.sql('CREATE OR REPLACE TABLE t1 as SELECT * FROM t1_df')", # noqa: E501
),
@@ -3141,7 +3157,7 @@ class TestSQL:
# make sure cell 1 executed, defining df
assert k.globals["t1_df"].to_dict(as_series=False) == {"a": [42]}
- await k.delete_cell(DeleteCellRequest(cell_id="3"))
+ await k.delete_cell(DeleteCellCommand(cell_id="3"))
# t1 should be dropped since it's an in-memory table;
# cell 1 should re-run but will fail to find t1
assert "df" not in k.globals
@@ -3149,11 +3165,11 @@ class TestSQL:
async def test_sql_table_with_duckdb(self, k: Kernel) -> None:
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code="import marimo as mo",
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1", code="df = duckdb.sql('SELECT * from t1')"
),
]
@@ -3162,13 +3178,13 @@ class TestSQL:
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="2",
code="import polars as pl; t1_df = pl.from_dict({'a': [42]})", # noqa: E501
),
# cell 1 should automatically execute due to the definition of
# t1
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="3",
code="duckdb.sql('CREATE OR REPLACE TABLE t1 as SELECT * FROM t1_df')", # noqa: E501
),
@@ -3178,7 +3194,7 @@ class TestSQL:
# make sure cell 1 executed, defining df
assert k.globals["t1_df"].to_dict(as_series=False) == {"a": [42]}
- await k.delete_cell(DeleteCellRequest(cell_id="3"))
+ await k.delete_cell(DeleteCellCommand(cell_id="3"))
# t1 should be dropped since it's an in-memory table;
# cell 1 should re-run but will fail to find t1
assert "df" not in k.globals
@@ -3186,11 +3202,11 @@ class TestSQL:
async def test_sql_view(self, k: Kernel) -> None:
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code="import marimo as mo",
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1", code="df = mo.sql('SELECT * from view')"
),
]
@@ -3201,7 +3217,7 @@ class TestSQL:
[
# cell 1 should automatically execute due to the definition of
# t1
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="2",
code="mo.sql('CREATE OR REPLACE VIEW view as SELECT 42')", # noqa: E501
),
@@ -3212,7 +3228,7 @@ class TestSQL:
# make sure cell 1 executed, defining df
assert "df" in k.globals
- await k.delete_cell(DeleteCellRequest(cell_id="2"))
+ await k.delete_cell(DeleteCellCommand(cell_id="2"))
# view should be dropped since it's an in-memory table;
# cell 1 should re-run but will fail to find t1
assert "df" not in k.globals
@@ -3220,15 +3236,15 @@ class TestSQL:
async def test_sql_query_as_local_df(self, k: Kernel) -> None:
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code="import marimo as mo; import polars as pl",
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1",
code="source_df = pl.DataFrame({'val': [42]})",
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="2",
code="df = mo.sql('SELECT * FROM source_df')",
),
@@ -3239,13 +3255,13 @@ class TestSQL:
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="3",
code="""
import duckdb
conn = duckdb.connect()""",
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="4",
code="df2 = mo.sql('SELECT * FROM source_df', engine=conn)",
),
@@ -3505,7 +3521,7 @@ class TestStateTransitions:
# Deleting a cell should broadcast Variables
stream.messages.clear()
- await k.delete_cell(DeleteCellRequest(cell_id=er_2.cell_id))
+ await k.delete_cell(DeleteCellCommand(cell_id=er_2.cell_id))
assert (
sum(
1
@@ -3661,32 +3677,24 @@ class TestMarkdownHandling:
regular_cell_code = "x = 1"
execution_requests = [
- ExecutionRequest(cell_id="md_cell", code=markdown_cell_code),
- ExecutionRequest(cell_id="regular_cell", code=regular_cell_code),
+ ExecuteCellCommand(cell_id="md_cell", code=markdown_cell_code),
+ ExecuteCellCommand(cell_id="regular_cell", code=regular_cell_code),
]
- # Create a creation request with auto_run=False to trigger the markdown handling
- creation_request = CreationRequest(
- execution_requests=execution_requests,
- auto_run=False,
- set_ui_element_value_request=SetUIElementValueRequest(
- object_ids=[],
- values=[],
- ),
- )
-
# Clear stream before instantiate
stream.messages.clear()
# Add a cell that exports 'mo' to enable markdown processing
# This simulates the scenario where marimo has been imported
execution_requests.append(
- ExecutionRequest(cell_id="mo_import", code="import marimo as mo")
+ ExecuteCellCommand(cell_id="mo_import", code="import marimo as mo")
)
- creation_request = CreationRequest(
+
+ # Create a creation request with auto_run=False to trigger the markdown handling
+ creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
auto_run=False,
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
values=[],
),
@@ -3766,22 +3774,24 @@ class TestMarkdownHandling:
t_markdown_cell_code_escaped = "mo.md(t'{{mo}}')"
execution_requests = [
- ExecutionRequest(cell_id="md_cell_r", code=r_markdown_cell_code),
- ExecutionRequest(cell_id="md_cell_f", code=f_markdown_cell_code),
- ExecutionRequest(cell_id="md_cell_t", code=t_markdown_cell_code),
- ExecutionRequest(
+ ExecuteCellCommand(cell_id="md_cell_r", code=r_markdown_cell_code),
+ ExecuteCellCommand(cell_id="md_cell_f", code=f_markdown_cell_code),
+ ExecuteCellCommand(cell_id="md_cell_t", code=t_markdown_cell_code),
+ ExecuteCellCommand(
cell_id="md_cell_fe", code=f_markdown_cell_code_escaped
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="md_cell_te", code=t_markdown_cell_code_escaped
),
- ExecutionRequest(cell_id="mo_import", code="import marimo as mo"),
+ ExecuteCellCommand(
+ cell_id="mo_import", code="import marimo as mo"
+ ),
]
- creation_request = CreationRequest(
+ creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
auto_run=False,
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
values=[],
),
@@ -3811,15 +3821,17 @@ class TestMarkdownHandling:
regular_cell_code = "x = 0"
execution_requests = [
- ExecutionRequest(cell_id="md_cell", code=markdown_cell_code),
- ExecutionRequest(cell_id="regular_cell", code=regular_cell_code),
- ExecutionRequest(cell_id="mo_import", code="import marimo as mo"),
+ ExecuteCellCommand(cell_id="md_cell", code=markdown_cell_code),
+ ExecuteCellCommand(cell_id="regular_cell", code=regular_cell_code),
+ ExecuteCellCommand(
+ cell_id="mo_import", code="import marimo as mo"
+ ),
]
- creation_request = CreationRequest(
+ creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
auto_run=False,
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
values=[],
),
@@ -3843,14 +3855,14 @@ class TestMarkdownHandling:
# Create execution requests with only regular cells
execution_requests = [
- ExecutionRequest(cell_id="cell1", code="x = 1"),
- ExecutionRequest(cell_id="cell2", code="y = 2"),
+ ExecuteCellCommand(cell_id="cell1", code="x = 1"),
+ ExecuteCellCommand(cell_id="cell2", code="y = 2"),
]
- creation_request = CreationRequest(
+ creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
auto_run=False,
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
values=[],
),
@@ -3892,32 +3904,24 @@ class TestMarkdownHandling:
# Create execution requests with malformed markdown cell
execution_requests = [
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="bad_cell", code="mo.md("
), # Syntax error
- ExecutionRequest(cell_id="good_md", code='mo.md("# Good")'),
+ ExecuteCellCommand(cell_id="good_md", code='mo.md("# Good")'),
]
- creation_request = CreationRequest(
- execution_requests=execution_requests,
- auto_run=False,
- set_ui_element_value_request=SetUIElementValueRequest(
- object_ids=[],
- values=[],
- ),
- )
-
stream.messages.clear()
# Add a cell that exports 'mo' to enable markdown processing
# This simulates the scenario where marimo has been imported
execution_requests.append(
- ExecutionRequest(cell_id="mo_import", code="import marimo as mo")
+ ExecuteCellCommand(cell_id="mo_import", code="import marimo as mo")
)
- creation_request = CreationRequest(
+
+ creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
auto_run=False,
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
values=[],
),
@@ -3967,15 +3971,15 @@ class TestMarkdownHandling:
# Create execution requests with markdown cells
execution_requests = [
- ExecutionRequest(cell_id="md_cell1", code='mo.md("# Hello")'),
- ExecutionRequest(cell_id="md_cell2", code='mo.md("## World")'),
- ExecutionRequest(cell_id="regular_cell", code="x = 1"),
+ ExecuteCellCommand(cell_id="md_cell1", code='mo.md("# Hello")'),
+ ExecuteCellCommand(cell_id="md_cell2", code='mo.md("## World")'),
+ ExecuteCellCommand(cell_id="regular_cell", code="x = 1"),
]
- creation_request = CreationRequest(
+ creation_request = CreateNotebookCommand(
execution_requests=execution_requests,
auto_run=False,
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[],
values=[],
),
diff --git a/tests/_runtime/test_runtime_datasets.py b/tests/_runtime/test_runtime_datasets.py
index d34f9e44d4..4a5eef6cbc 100644
--- a/tests/_runtime/test_runtime_datasets.py
+++ b/tests/_runtime/test_runtime_datasets.py
@@ -12,12 +12,12 @@ from marimo._messaging.notification import (
SQLTablePreviewNotification,
ValidateSQLResultNotification,
)
-from marimo._runtime.requests import (
- ExecutionRequest,
- PreviewDataSourceConnectionRequest,
- PreviewSQLTableListRequest,
- PreviewSQLTableRequest,
- ValidateSQLRequest,
+from marimo._runtime.commands import (
+ ExecuteCellCommand,
+ ListDataSourceConnectionCommand,
+ ListSQLTablesCommand,
+ PreviewSQLTableCommand,
+ ValidateSQLCommand,
)
from marimo._sql.engines.duckdb import INTERNAL_DUCKDB_ENGINE
from marimo._sql.parse import SqlCatalogCheckResult, SqlParseResult
@@ -32,15 +32,15 @@ SQLITE_CONN = "sqlite_conn"
@pytest.fixture
-async def connection_requests() -> list[ExecutionRequest]:
+async def connection_requests() -> list[ExecuteCellCommand]:
return [
- ExecutionRequest(cell_id=CellId_t("0"), code="import duckdb"),
- ExecutionRequest(
+ ExecuteCellCommand(cell_id=CellId_t("0"), code="import duckdb"),
+ ExecuteCellCommand(
cell_id=CellId_t("1"),
code=f"{DUCKDB_CONN} = duckdb.connect(':memory:')",
),
- ExecutionRequest(cell_id=CellId_t("2"), code="import sqlite3"),
- ExecutionRequest(
+ ExecuteCellCommand(cell_id=CellId_t("2"), code="import sqlite3"),
+ ExecuteCellCommand(
cell_id=CellId_t("3"),
code=f"{SQLITE_CONN} = sqlite3.connect(':memory:')",
),
@@ -61,7 +61,7 @@ async def connection_requests() -> list[ExecutionRequest]:
# async def test_created_engine(
# self,
# mocked_kernel: MockedKernel,
-# connection_requests: list[ExecutionRequest],
+# connection_requests: list[ExecuteCellCommand],
# ) -> None:
# k = mocked_kernel.k
@@ -86,7 +86,7 @@ class TestPreviewSQLTable:
k = mocked_kernel.k
stream = mocked_kernel.stream
- preview_sql_table_request = PreviewSQLTableRequest(
+ preview_sql_table_request = PreviewSQLTableCommand(
request_id=RequestId("0"),
engine=DUCKDB_CONN,
database="test",
@@ -114,14 +114,14 @@ class TestPreviewSQLTable:
async def test_catalog_engine(
self,
mocked_kernel: MockedKernel,
- connection_requests: list[ExecutionRequest],
+ connection_requests: list[ExecuteCellCommand],
) -> None:
k = mocked_kernel.k
stream = mocked_kernel.stream
await k.run(connection_requests)
- preview_sql_table_request = PreviewSQLTableRequest(
+ preview_sql_table_request = PreviewSQLTableCommand(
request_id=RequestId("0"),
engine=DUCKDB_CONN,
database="test",
@@ -149,14 +149,14 @@ class TestPreviewSQLTable:
async def test_query_engine(
self,
mocked_kernel: MockedKernel,
- connection_requests: list[ExecutionRequest],
+ connection_requests: list[ExecuteCellCommand],
) -> None:
k = mocked_kernel.k
stream = mocked_kernel.stream
await k.run(connection_requests)
- preview_sql_table_request = PreviewSQLTableRequest(
+ preview_sql_table_request = PreviewSQLTableCommand(
request_id=RequestId("0"),
engine=SQLITE_CONN,
database="test",
@@ -190,7 +190,7 @@ class TestPreviewSQLTableList:
k = mocked_kernel.k
stream = mocked_kernel.stream
- preview_sql_table_list_request = PreviewSQLTableListRequest(
+ preview_sql_table_list_request = ListSQLTablesCommand(
request_id=RequestId("0"),
engine=DUCKDB_CONN,
database="test",
@@ -216,14 +216,14 @@ class TestPreviewSQLTableList:
async def test_catalog_engine(
self,
mocked_kernel: MockedKernel,
- connection_requests: list[ExecutionRequest],
+ connection_requests: list[ExecuteCellCommand],
) -> None:
k = mocked_kernel.k
stream = mocked_kernel.stream
await k.run(connection_requests)
- preview_sql_table_list_request = PreviewSQLTableListRequest(
+ preview_sql_table_list_request = ListSQLTablesCommand(
request_id=RequestId("0"),
engine=DUCKDB_CONN,
database="test",
@@ -250,14 +250,14 @@ class TestPreviewSQLTableList:
async def test_query_engine(
self,
mocked_kernel: MockedKernel,
- connection_requests: list[ExecutionRequest],
+ connection_requests: list[ExecuteCellCommand],
) -> None:
k = mocked_kernel.k
stream = mocked_kernel.stream
await k.run(connection_requests)
- preview_sql_table_list_request = PreviewSQLTableListRequest(
+ preview_sql_table_list_request = ListSQLTablesCommand(
request_id=RequestId("0"),
engine=SQLITE_CONN,
database="test",
@@ -290,7 +290,7 @@ class TestPreviewDatasourceConnection:
stream = mocked_kernel.stream
preview_datasource_connection_request = (
- PreviewDataSourceConnectionRequest(engine=DUCKDB_CONN)
+ ListDataSourceConnectionCommand(engine=DUCKDB_CONN)
)
await k.handle_message(preview_datasource_connection_request)
preview_datasource_connection_results = [
@@ -306,7 +306,7 @@ class TestPreviewDatasourceConnection:
async def test_engines(
self,
mocked_kernel: MockedKernel,
- connection_requests: list[ExecutionRequest],
+ connection_requests: list[ExecuteCellCommand],
) -> None:
k = mocked_kernel.k
stream = mocked_kernel.stream
@@ -314,7 +314,7 @@ class TestPreviewDatasourceConnection:
await k.run(connection_requests)
preview_datasource_connection_request = (
- PreviewDataSourceConnectionRequest(engine=DUCKDB_CONN)
+ ListDataSourceConnectionCommand(engine=DUCKDB_CONN)
)
await k.handle_message(preview_datasource_connection_request)
@@ -335,7 +335,7 @@ class TestSQLValidate:
stream = mocked_kernel.stream
# Non-existent engine
- validate_sql_request = ValidateSQLRequest(
+ validate_sql_request = ValidateSQLCommand(
request_id=RequestId("0"),
engine=DUCKDB_CONN,
query="SELECT * from t1",
@@ -363,7 +363,7 @@ class TestSQLValidate:
stream = mocked_kernel.stream
# Internal engine and valid query
- validate_sql_request = ValidateSQLRequest(
+ validate_sql_request = ValidateSQLCommand(
request_id=RequestId("1"),
engine=INTERNAL_DUCKDB_ENGINE,
query="SELECT 1, 2",
@@ -391,7 +391,7 @@ class TestSQLValidate:
stream = mocked_kernel.stream
# Internal engine and invalid query
- validate_sql_request = ValidateSQLRequest(
+ validate_sql_request = ValidateSQLCommand(
request_id=RequestId("2"),
engine=INTERNAL_DUCKDB_ENGINE,
query="SELECT * FROM t1",
@@ -424,14 +424,14 @@ class TestSQLValidate:
async def test_other_engine_and_valid_query(
self,
mocked_kernel: MockedKernel,
- connection_requests: list[ExecutionRequest],
+ connection_requests: list[ExecuteCellCommand],
) -> None:
k = mocked_kernel.k
stream = mocked_kernel.stream
# Handle other engines
await k.run(connection_requests)
- validate_sql_request = ValidateSQLRequest(
+ validate_sql_request = ValidateSQLCommand(
request_id=RequestId("3"),
engine=SQLITE_CONN,
query="SELECT 1, 2",
@@ -458,14 +458,14 @@ class TestSQLValidate:
async def test_only_parse_with_no_dialect(
self,
mocked_kernel: MockedKernel,
- connection_requests: list[ExecutionRequest],
+ connection_requests: list[ExecuteCellCommand],
) -> None:
k = mocked_kernel.k
stream = mocked_kernel.stream
await k.run(connection_requests)
- validate_sql_request = ValidateSQLRequest(
+ validate_sql_request = ValidateSQLCommand(
request_id=RequestId("4"),
engine=SQLITE_CONN,
query="SELECT 1, 2",
@@ -488,14 +488,14 @@ class TestSQLValidate:
async def test_only_parse_unsupported_dialect(
self,
mocked_kernel: MockedKernel,
- connection_requests: list[ExecutionRequest],
+ connection_requests: list[ExecuteCellCommand],
) -> None:
k = mocked_kernel.k
stream = mocked_kernel.stream
await k.run(connection_requests)
- validate_sql_request = ValidateSQLRequest(
+ validate_sql_request = ValidateSQLCommand(
request_id=RequestId("5"),
dialect="sqlite",
query="SELECT 1, 2",
@@ -518,14 +518,14 @@ class TestSQLValidate:
async def test_only_parse_duckdb(
self,
mocked_kernel: MockedKernel,
- connection_requests: list[ExecutionRequest],
+ connection_requests: list[ExecuteCellCommand],
) -> None:
k = mocked_kernel.k
stream = mocked_kernel.stream
await k.run(connection_requests)
- validate_sql_request = ValidateSQLRequest(
+ validate_sql_request = ValidateSQLCommand(
request_id=RequestId("6"),
dialect="duckdb",
query="SELECT 1, 2",
@@ -548,14 +548,14 @@ class TestSQLValidate:
async def test_validate_but_no_engine(
self,
mocked_kernel: MockedKernel,
- connection_requests: list[ExecutionRequest],
+ connection_requests: list[ExecuteCellCommand],
) -> None:
k = mocked_kernel.k
stream = mocked_kernel.stream
await k.run(connection_requests)
- validate_sql_request = ValidateSQLRequest(
+ validate_sql_request = ValidateSQLCommand(
request_id=RequestId("7"),
query="SELECT 1, 2",
only_parse=False,
diff --git a/tests/_runtime/test_runtime_secrets.py b/tests/_runtime/test_runtime_secrets.py
index 65492e70a9..bdb209e42e 100644
--- a/tests/_runtime/test_runtime_secrets.py
+++ b/tests/_runtime/test_runtime_secrets.py
@@ -6,9 +6,9 @@ from unittest.mock import MagicMock
import pytest
from marimo._messaging.notification import SecretKeysResultNotification
-from marimo._runtime.requests import (
- ListSecretKeysRequest,
- RefreshSecretsRequest,
+from marimo._runtime.commands import (
+ ListSecretKeysCommand,
+ RefreshSecretsCommand,
)
from marimo._runtime.runtime import SecretsCallbacks
from marimo._types.ids import RequestId
@@ -30,7 +30,7 @@ async def test_list_secrets_with_values(
mocked_kernel.k._original_environ = os.environ.copy()
await secrets_callbacks.list_secrets(
- ListSecretKeysRequest(request_id=RequestId("test"))
+ ListSecretKeysCommand(request_id=RequestId("test"))
)
# Check that the broadcast message was sent with the correct secrets
@@ -64,7 +64,7 @@ async def test_refresh_secrets(
original_load_dotenv = mocked_kernel.k.load_dotenv
mocked_kernel.k.load_dotenv = MagicMock(wraps=original_load_dotenv)
- await secrets_callbacks.refresh_secrets(RefreshSecretsRequest())
+ await secrets_callbacks.refresh_secrets(RefreshSecretsCommand())
# Check that load_dotenv was called
assert mocked_kernel.k.load_dotenv.call_count == 1
diff --git a/tests/_runtime/test_threads.py b/tests/_runtime/test_threads.py
index 15dc83b73d..90018a59e4 100644
--- a/tests/_runtime/test_threads.py
+++ b/tests/_runtime/test_threads.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import time
-from marimo._runtime.requests import DeleteCellRequest
+from marimo._runtime.commands import DeleteCellCommand
from marimo._runtime.runtime import Kernel
from tests._messaging.mocks import MockStream
from tests.conftest import ExecReqProvider
@@ -236,5 +236,5 @@ async def test_thread_should_exit_on_deletion(
thread = k.globals["thread"]
assert not thread.should_exit
- await k.delete_cell(DeleteCellRequest(er.cell_id))
+ await k.delete_cell(DeleteCellCommand(er.cell_id))
assert thread.should_exit
diff --git a/tests/_runtime/test_trace.py b/tests/_runtime/test_trace.py
index 8d93a66322..c3759e1c4b 100644
--- a/tests/_runtime/test_trace.py
+++ b/tests/_runtime/test_trace.py
@@ -7,8 +7,8 @@ import subprocess
import sys
import textwrap
-from marimo._runtime.requests import (
- ExecutionRequest,
+from marimo._runtime.commands import (
+ ExecuteCellCommand,
)
from marimo._runtime.runtime import Kernel
from marimo._utils import async_path
@@ -148,7 +148,7 @@ class TestAppTrace:
k = execution_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -192,7 +192,7 @@ class TestAppTrace:
k = execution_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -206,7 +206,7 @@ class TestAppTrace:
"""
),
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1",
code="foo()",
),
@@ -241,7 +241,7 @@ class TestAppTrace:
k = execution_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -253,7 +253,7 @@ class TestAppTrace:
"""
),
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1",
code=textwrap.dedent(
"""
@@ -295,7 +295,7 @@ class TestEmbedTrace:
) -> None:
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -305,7 +305,7 @@ class TestEmbedTrace:
"""
),
),
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1",
code=textwrap.dedent(
"""
diff --git a/tests/_runtime/test_virtual_file.py b/tests/_runtime/test_virtual_file.py
index 2baf81820d..1c627e9b12 100644
--- a/tests/_runtime/test_virtual_file.py
+++ b/tests/_runtime/test_virtual_file.py
@@ -1,8 +1,8 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from marimo._runtime.commands import DeleteCellCommand
from marimo._runtime.context import get_context
-from marimo._runtime.requests import DeleteCellRequest
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -48,7 +48,7 @@ async def test_virtual_file_deletion(
for fname in get_context().virtual_file_registry.registry.keys():
assert fname.endswith(".pdf")
- await k.delete_cell(DeleteCellRequest(cell_id=er.cell_id))
+ await k.delete_cell(DeleteCellCommand(cell_id=er.cell_id))
assert not get_context().virtual_file_registry.registry
@@ -89,8 +89,8 @@ async def test_cached_virtual_file_not_deleted(
assert len(get_context().virtual_file_registry.registry) == 2
# Remove the cells that create the vfiles
- await k.delete_cell(DeleteCellRequest(cell_id=create_vfile_1.cell_id))
- await k.delete_cell(DeleteCellRequest(cell_id=create_vfile_2.cell_id))
+ await k.delete_cell(DeleteCellCommand(cell_id=create_vfile_1.cell_id))
+ await k.delete_cell(DeleteCellCommand(cell_id=create_vfile_2.cell_id))
# Reset the vfile cache
await k.run([vfile_cache])
@@ -124,7 +124,7 @@ async def test_cell_deletion_clears_vfiles(
assert len(get_context().virtual_file_registry.registry) == 1
# Delete the vfile cache: virtual file registry should be empty
- await k.delete_cell(DeleteCellRequest(cell_id=vfile_cache.cell_id))
+ await k.delete_cell(DeleteCellCommand(cell_id=vfile_cache.cell_id))
assert len(get_context().virtual_file_registry.registry) == 0
diff --git a/tests/_runtime/utils/test_set_ui_element_request_manager.py b/tests/_runtime/utils/test_set_ui_element_request_manager.py
index 69d4aaa29f..2dbd4d8a19 100644
--- a/tests/_runtime/utils/test_set_ui_element_request_manager.py
+++ b/tests/_runtime/utils/test_set_ui_element_request_manager.py
@@ -6,7 +6,7 @@ import queue
import threading
import time
-from marimo._runtime.requests import SetUIElementValueRequest
+from marimo._runtime.commands import UpdateUIElementCommand
from marimo._runtime.utils.set_ui_element_request_manager import (
SetUIElementRequestManager,
)
@@ -14,14 +14,14 @@ from marimo._runtime.utils.set_ui_element_request_manager import (
def test_process_request_dedupes_by_token() -> None:
"""Test that duplicate tokens are properly deduplicated."""
- q: queue.Queue[SetUIElementValueRequest] = queue.Queue()
+ q: queue.Queue[UpdateUIElementCommand] = queue.Queue()
manager = SetUIElementRequestManager(q)
# Create two requests with the same token
- request1 = SetUIElementValueRequest(
+ request1 = UpdateUIElementCommand(
object_ids=["obj1"], values=[1], token="token1"
)
- request2 = SetUIElementValueRequest(
+ request2 = UpdateUIElementCommand(
object_ids=["obj2"], values=[2], token="token1"
)
@@ -39,13 +39,13 @@ def test_process_request_dedupes_by_token() -> None:
def test_process_request_merges_different_tokens() -> None:
"""Test that requests with different tokens are merged."""
- q: queue.Queue[SetUIElementValueRequest] = queue.Queue()
+ q: queue.Queue[UpdateUIElementCommand] = queue.Queue()
manager = SetUIElementRequestManager(q)
- request1 = SetUIElementValueRequest(
+ request1 = UpdateUIElementCommand(
object_ids=["obj1"], values=[1], token="token1"
)
- request2 = SetUIElementValueRequest(
+ request2 = UpdateUIElementCommand(
object_ids=["obj2"], values=[2], token="token2"
)
@@ -63,13 +63,13 @@ def test_process_request_merges_different_tokens() -> None:
def test_process_request_keeps_latest_value_per_id() -> None:
"""Test that when multiple requests update the same UI element, the latest value wins."""
- q: queue.Queue[SetUIElementValueRequest] = queue.Queue()
+ q: queue.Queue[UpdateUIElementCommand] = queue.Queue()
manager = SetUIElementRequestManager(q)
- request1 = SetUIElementValueRequest(
+ request1 = UpdateUIElementCommand(
object_ids=["obj1"], values=[1], token="token1"
)
- request2 = SetUIElementValueRequest(
+ request2 = UpdateUIElementCommand(
object_ids=["obj1"], values=[2], token="token2"
)
@@ -92,7 +92,7 @@ def test_process_request_handles_concurrent_queue_updates() -> None:
This simulates the race condition that occurs with ZeroMQ IPC where a
receiver thread continuously adds messages to the queue.
"""
- q: queue.Queue[SetUIElementValueRequest] = queue.Queue()
+ q: queue.Queue[UpdateUIElementCommand] = queue.Queue()
manager = SetUIElementRequestManager(q)
# Track how many requests were added
@@ -103,7 +103,7 @@ def test_process_request_handles_concurrent_queue_updates() -> None:
"""Simulate a ZeroMQ receiver thread adding messages to the queue."""
counter = 0
while not stop_event.is_set():
- request = SetUIElementValueRequest(
+ request = UpdateUIElementCommand(
object_ids=[f"obj{counter}"],
values=[counter],
token=f"token{counter}",
@@ -121,7 +121,7 @@ def test_process_request_handles_concurrent_queue_updates() -> None:
time.sleep(0.05)
# Process a request while the producer is still running
- initial_request = SetUIElementValueRequest(
+ initial_request = UpdateUIElementCommand(
object_ids=["obj_initial"], values=[999], token="token_initial"
)
@@ -153,13 +153,13 @@ def test_process_request_handles_concurrent_queue_updates() -> None:
async def test_process_request_with_asyncio_queue() -> None:
"""Test that the manager works with asyncio.Queue."""
- q: asyncio.Queue[SetUIElementValueRequest] = asyncio.Queue()
+ q: asyncio.Queue[UpdateUIElementCommand] = asyncio.Queue()
manager = SetUIElementRequestManager(q)
- request1 = SetUIElementValueRequest(
+ request1 = UpdateUIElementCommand(
object_ids=["obj1"], values=[1], token="token1"
)
- request2 = SetUIElementValueRequest(
+ request2 = UpdateUIElementCommand(
object_ids=["obj2"], values=[2], token="token2"
)
@@ -177,11 +177,11 @@ async def test_process_request_with_asyncio_queue() -> None:
def test_process_request_returns_none_for_empty_batch() -> None:
"""Test that None is returned when all requests are duplicates."""
- q: queue.Queue[SetUIElementValueRequest] = queue.Queue()
+ q: queue.Queue[UpdateUIElementCommand] = queue.Queue()
manager = SetUIElementRequestManager(q)
# Create a request and process it
- request = SetUIElementValueRequest(
+ request = UpdateUIElementCommand(
object_ids=["obj1"], values=[1], token="token1"
)
result1 = manager.process_request(request)
diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.py
index 39d2cfafd2..0a5a7608b3 100644
--- a/tests/_save/test_cache.py
+++ b/tests/_save/test_cache.py
@@ -12,7 +12,7 @@ import pytest
import marimo
from marimo._ast.app import App
from marimo._plugins.ui._impl.input import dropdown
-from marimo._runtime.requests import ExecutionRequest
+from marimo._runtime.commands import ExecuteCellCommand
from marimo._runtime.runtime import Kernel
from marimo._save.cache import Cache
from marimo._save.stubs.module_stub import ModuleStub
@@ -524,7 +524,7 @@ class TestAppCache:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -550,7 +550,7 @@ class TestAppCache:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -577,7 +577,7 @@ class TestAppCache:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -606,7 +606,7 @@ class TestAppCache:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -632,7 +632,7 @@ class TestAppCache:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -660,7 +660,7 @@ class TestAppCache:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -686,7 +686,7 @@ class TestAppCache:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -714,7 +714,7 @@ class TestAppCache:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -740,7 +740,7 @@ class TestAppCache:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
@@ -763,7 +763,7 @@ class TestAppCache:
k = any_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="0",
code=textwrap.dedent(
"""
diff --git a/tests/_save/test_external_decorators.py b/tests/_save/test_external_decorators.py
index 6fe6264698..54f9ecf08d 100644
--- a/tests/_save/test_external_decorators.py
+++ b/tests/_save/test_external_decorators.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import sys
import textwrap
-from marimo._runtime.requests import ExecutionRequest
+from marimo._runtime.commands import ExecuteCellCommand
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -121,7 +121,7 @@ class TestDecoratorImports:
k = lazy_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="setup",
code=textwrap.dedent(
"""
@@ -295,7 +295,7 @@ class TestAsExternalApp:
k = lazy_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="setup",
code=textwrap.dedent(
"""
@@ -352,7 +352,7 @@ class TestAsExternalApp:
k = lazy_kernel
await k.run(
[
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="setup",
code=textwrap.dedent(
"""
diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.py
index ca22bd1530..5217854547 100644
--- a/tests/_save/test_hash.py
+++ b/tests/_save/test_hash.py
@@ -9,7 +9,7 @@ import pytest
from marimo._ast.app import App
from marimo._dependencies.dependencies import DependencyManager
-from marimo._runtime.requests import ExecuteStaleRequest
+from marimo._runtime.commands import ExecuteStaleCellsCommand
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -1438,7 +1438,7 @@ class TestSideEffects:
(tmp_path / "test.txt").touch()
await asyncio.sleep(0.25)
assert len(control_requests) == 1
- assert isinstance(control_requests[0], ExecuteStaleRequest)
+ assert isinstance(control_requests[0], ExecuteStaleCellsCommand)
assert k.graph.cells[r.cell_id].stale
await k.run_stale_cells()
@@ -1503,7 +1503,7 @@ class TestSideEffects:
(tmp_path / "test_dir" / "test.txt").write_text("test")
await asyncio.sleep(0.25)
assert len(control_requests) == 1
- assert isinstance(control_requests[0], ExecuteStaleRequest)
+ assert isinstance(control_requests[0], ExecuteStaleCellsCommand)
assert k.graph.cells[r.cell_id].stale
await k.run_stale_cells()
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index d68088d702..4bcf92b8ba 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -488,7 +488,7 @@ async def test_run_until_completion_with_console_output(mock_echo: MagicMock):
mock_echo.assert_any_call("hello stderr", file=sys.stderr, nl=False)
n_tries = 0
- limit = 5
+ limit = 10
while n_tries <= limit:
try:
_assert_contents()
diff --git a/tests/_server/session/test_serialize_session.py b/tests/_server/session/test_serialize_session.py
index a5372a60bd..c820de4a2d 100644
--- a/tests/_server/session/test_serialize_session.py
+++ b/tests/_server/session/test_serialize_session.py
@@ -14,7 +14,7 @@ from marimo._ast.cell_manager import CellManager
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.errors import MarimoExceptionRaisedError, UnknownError
from marimo._messaging.notification import CellNotification
-from marimo._runtime.requests import ExecuteMultipleRequest
+from marimo._runtime.commands import ExecuteCellsCommand
from marimo._schemas.session import NotebookSessionV1
from marimo._server.session.serialize import (
SessionCacheKey,
@@ -948,7 +948,7 @@ class TestSessionCacheManager:
timestamp=0,
)
view.add_control_request(
- ExecuteMultipleRequest(cell_ids=["cell1"], codes=["a"])
+ ExecuteCellsCommand(cell_ids=["cell1"], codes=["a"])
)
with tempfile.TemporaryDirectory() as tmpdir:
@@ -978,7 +978,7 @@ class TestSessionCacheManager:
"""Test reading session view from cache file"""
view = session_view
view.add_control_request(
- ExecuteMultipleRequest(cell_ids=["1", "2"], codes=["a", "b"])
+ ExecuteCellsCommand(cell_ids=["1", "2"], codes=["a", "b"])
)
with tempfile.TemporaryDirectory() as tmpdir:
@@ -1033,9 +1033,7 @@ class TestSessionCacheManager:
)
view.add_control_request(
- ExecuteMultipleRequest(
- cell_ids=["cell1", "cell2"], codes=["a", "b"]
- )
+ ExecuteCellsCommand(cell_ids=["cell1", "cell2"], codes=["a", "b"])
)
with tempfile.TemporaryDirectory() as tmpdir:
diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.py
index a5142bacd5..5611acd938 100644
--- a/tests/_server/session/test_session_view.py
+++ b/tests/_server/session/test_session_view.py
@@ -32,11 +32,11 @@ from marimo._messaging.notification import (
VariableValuesNotification,
serialize_kernel_message,
)
-from marimo._runtime.requests import (
- CreationRequest,
- ExecuteMultipleRequest,
- ExecutionRequest,
- SetUIElementValueRequest,
+from marimo._runtime.commands import (
+ CreateNotebookCommand,
+ ExecuteCellCommand,
+ ExecuteCellsCommand,
+ UpdateUIElementCommand,
)
from marimo._server.session.session_view import SessionView
from marimo._sql.engines.duckdb import INTERNAL_DUCKDB_ENGINE
@@ -153,7 +153,7 @@ def test_session_view_variable_values(session_view: SessionView) -> None:
def test_ui_values(session_view: SessionView) -> None:
session_view.add_control_request(
- SetUIElementValueRequest.from_ids_and_values([("test_ui", 123)])
+ UpdateUIElementCommand.from_ids_and_values([("test_ui", 123)])
)
assert "test_ui" in session_view.ui_values
assert session_view.ui_values["test_ui"] == 123
@@ -161,7 +161,7 @@ def test_ui_values(session_view: SessionView) -> None:
# Can add multiple values
# and can overwrite values
session_view.add_control_request(
- SetUIElementValueRequest.from_ids_and_values(
+ UpdateUIElementCommand.from_ids_and_values(
[("test_ui2", 456), ("test_ui", 789)]
)
)
@@ -172,9 +172,9 @@ def test_ui_values(session_view: SessionView) -> None:
# Can add from CreationRequest
session_view.add_control_request(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(),
- set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[("test_ui3", 101112)]
),
auto_run=True,
@@ -226,7 +226,7 @@ def test_model_message_values(session_view: SessionView) -> None:
def test_last_run_code(session_view: SessionView) -> None:
session_view.add_control_request(
- ExecuteMultipleRequest(
+ ExecuteCellsCommand(
cell_ids=[cell_id],
codes=["print('hello')"],
)
@@ -235,7 +235,7 @@ def test_last_run_code(session_view: SessionView) -> None:
# Can overwrite values and add multiple
session_view.add_control_request(
- ExecuteMultipleRequest(
+ ExecuteCellsCommand(
cell_ids=[cell_id, "cell_2"],
codes=["print('hello world')", "print('hello world')"],
)
@@ -245,11 +245,11 @@ def test_last_run_code(session_view: SessionView) -> None:
# Can add from CreationRequest
session_view.add_control_request(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(
- ExecutionRequest(cell_id=cell_id, code="print('hello')"),
+ ExecuteCellCommand(cell_id=cell_id, code="print('hello')"),
),
- set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
[]
),
auto_run=True,
diff --git a/tests/_server/sessions/test_file_change_handler.py b/tests/_server/sessions/test_file_change_handler.py
index ace40991e6..0e5835c45b 100644
--- a/tests/_server/sessions/test_file_change_handler.py
+++ b/tests/_server/sessions/test_file_change_handler.py
@@ -16,7 +16,7 @@ from marimo._messaging.notification import (
UpdateCellCodesNotification,
UpdateCellIdsNotification,
)
-from marimo._runtime.requests import DeleteCellRequest, SyncGraphRequest
+from marimo._runtime.commands import DeleteCellCommand, SyncGraphCommand
from marimo._server.models.models import SaveNotebookRequest
from marimo._server.notebook import AppFileManager
from marimo._server.sessions.file_change_handler import (
@@ -148,7 +148,7 @@ def test_edit_mode_reload_strategy_autorun(
sync_calls = [
call
for call in mock_session.put_control_request.call_args_list
- if isinstance(call[0][0], SyncGraphRequest)
+ if isinstance(call[0][0], SyncGraphCommand)
]
assert len(sync_calls) == 1
@@ -183,7 +183,7 @@ def test_edit_mode_reload_strategy_with_deleted_cells(
delete_calls = [
call
for call in mock_session.put_control_request.call_args_list
- if isinstance(call[0][0], DeleteCellRequest)
+ if isinstance(call[0][0], DeleteCellCommand)
]
assert len(delete_calls) == 1
assert delete_calls[0][0][0].cell_id == CellId_t("cell2")
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index 5b82983906..b60b30c8a4 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -29,12 +29,12 @@ from marimo._messaging.notification import (
)
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage
-from marimo._runtime.requests import (
+from marimo._runtime.commands import (
AppMetadata,
- CreationRequest,
- ExecutionRequest,
- SetUIElementValueRequest,
- SyncGraphRequest,
+ CreateNotebookCommand,
+ ExecuteCellCommand,
+ SyncGraphCommand,
+ UpdateUIElementCommand,
)
from marimo._server.consumer import SessionConsumer
from marimo._server.file_router import AppFileRouter
@@ -229,9 +229,9 @@ def test_kernel_manager_interrupt(tmp_path: Path) -> None:
Path(file).write_text("-1")
queue_manager.control_queue.put(
- CreationRequest(
+ CreateNotebookCommand(
execution_requests=(
- ExecutionRequest(
+ ExecuteCellCommand(
cell_id="1",
code=inspect.cleandoc(
f"""
@@ -245,7 +245,7 @@ def test_kernel_manager_interrupt(tmp_path: Path) -> None:
),
),
),
- set_ui_element_value_request=SetUIElementValueRequest(
+ set_ui_element_value_request=UpdateUIElementCommand(
object_ids=[], values=[]
),
auto_run=True,
@@ -792,7 +792,7 @@ async def test_watch_mode_with_watcher_on_save_autorun(tmp_path: Path) -> None:
# Verify that cells were queued for execution
assert session.session_view.add_control_request.called
last_call = session.session_view.add_control_request.call_args[0][0]
- assert isinstance(last_call, SyncGraphRequest)
+ assert isinstance(last_call, SyncGraphCommand)
finally:
# Cleanup
diff --git a/tests/_utils/test_parse_dataclass.py b/tests/_utils/test_parse_dataclass.py
index a50aab3ce0..bc7dda1201 100644
--- a/tests/_utils/test_parse_dataclass.py
+++ b/tests/_utils/test_parse_dataclass.py
@@ -22,7 +22,7 @@ import pytest
from marimo._config.config import ExperimentalConfigType
from marimo._messaging.msgspec_encoder import asdict
-from marimo._runtime.requests import SetCellConfigRequest
+from marimo._runtime.commands import UpdateCellConfigCommand
from marimo._types.ids import CellId_t
from marimo._utils.parse_dataclass import parse_raw
@@ -173,13 +173,13 @@ class TestParseRaw:
assert parsed == nested
def test_set_cell_config(self) -> None:
- config = SetCellConfigRequest(
+ config = UpdateCellConfigCommand(
{
CellId_t("0"): {"disabled": True},
CellId_t("1"): {"disabled": False},
}
)
- parsed = parse_raw(serialize(config), SetCellConfigRequest)
+ parsed = parse_raw(serialize(config), UpdateCellConfigCommand)
assert parsed == config
def test_unions(self) -> None:
diff --git a/tests/conftest.py b/tests/conftest.py
index 10217f82c9..90c76b203d 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -33,11 +33,11 @@ from marimo._messaging.streams import (
from marimo._messaging.types import KernelMessage
from marimo._output.formatters.formatters import register_formatters
from marimo._runtime import patches
+from marimo._runtime.commands import AppMetadata, ExecuteCellCommand
from marimo._runtime.context import teardown_context
from marimo._runtime.context.kernel_context import initialize_kernel_context
from marimo._runtime.input_override import input_override
from marimo._runtime.marimo_pdb import MarimoPdb
-from marimo._runtime.requests import AppMetadata, ExecutionRequest
from marimo._runtime.runtime import Kernel
from marimo._save.stubs.module_stub import ModuleStub
from marimo._server.model import SessionMode
@@ -596,17 +596,17 @@ def temp_marimo_file_with_multiple_definitions() -> Generator[str, None, None]:
_cleanup_tmp_dir(tmp_dir)
-# Factory to create ExecutionRequests and abstract away cell ID
+# Factory to create ExecuteCellCommands and abstract away cell ID
class ExecReqProvider:
def __init__(self) -> None:
self.cell_manager = CellManager()
- def get(self, code: str) -> ExecutionRequest:
+ def get(self, code: str) -> ExecuteCellCommand:
key = self.cell_manager.create_cell_id()
- return ExecutionRequest(cell_id=key, code=textwrap.dedent(code))
+ return ExecuteCellCommand(cell_id=key, code=textwrap.dedent(code))
- def get_with_id(self, cell_id: CellId_t, code: str) -> ExecutionRequest:
- return ExecutionRequest(cell_id=cell_id, code=textwrap.dedent(code))
+ def get_with_id(self, cell_id: CellId_t, code: str) -> ExecuteCellCommand:
+ return ExecuteCellCommand(cell_id=cell_id, code=textwrap.dedent(code))
# fixture that provides an ExecReqProvider