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 Op to Notification (#7590)

Myles Scolnick10633697a72e
diff --git a/development_docs/adding_backend_and_mcp_tools.md b/development_docs/adding_backend_and_mcp_tools.md
index 5dfa2aea55..5aa556f623 100644
--- a/development_docs/adding_backend_and_mcp_tools.md
+++ b/development_docs/adding_backend_and_mcp_tools.md
@@ -1,3 +1,4 @@
+
# Adding Backend and MCP Tools to marimo
This guide explains how to create tools that are accessible via both the backend (chat panel) and MCP (Model Context Protocol) server endpoints.
@@ -23,6 +24,7 @@ Create dataclasses for your tool's arguments and output. Place these at the top
**Template:**
+---
```python
from dataclasses import dataclass, field
from marimo._ai._tools.types import SuccessResult
@@ -44,6 +46,7 @@ class YourToolOutput(SuccessResult):
data: dict = field(default_factory=dict)
count: int = 0
```
+---
**Important Type Patterns:**
@@ -59,6 +62,7 @@ Implement your tool class in the same file:
**Template:**
+---
```python
# Copyright 2025 Marimo. All rights reserved.
from __future__ import annotations
@@ -108,7 +112,7 @@ class YourTool(ToolBase[YourToolArgs, YourToolOutput]):
"When [describe primary use case]",
],
prerequisites=[
- "You must [describe args that need additional explanation]",
+ "You must [describe args that need additional explanation]",
],
avoid_if=[
"When [describe when not to use]",
@@ -143,6 +147,7 @@ class YourTool(ToolBase[YourToolArgs, YourToolOutput]):
# Implementation details
return {}
```
+---
### 4. Understanding ToolContext
@@ -152,15 +157,17 @@ class YourTool(ToolBase[YourToolArgs, YourToolOutput]):
Access via `self.context` in your `handle()` method:
+---
```python
def handle(self, args: YourToolArgs) -> YourToolOutput:
# Access ToolContext
context = self.context
-
+
# Use context methods
session = context.get_session(args.session_id)
errors = context.get_notebook_errors(args.session_id)
```
+---
#### When to add to ToolContext vs a helper method
@@ -176,22 +183,24 @@ def handle(self, args: YourToolArgs) -> YourToolOutput:
**Example:**
+---
```python
class YourTool(ToolBase[YourToolArgs, YourToolOutput]):
def handle(self, args: YourToolArgs) -> YourToolOutput:
# Use ToolContext for common operations
session = self.context.get_session(args.session_id)
errors = self.context.get_notebook_errors(args.session_id)
-
+
# Use helper methods for tool-specific logic
filtered_data = self._filter_by_criteria(errors, args.criteria)
-
+
return YourToolOutput(data=filtered_data)
-
+
def _filter_by_criteria(self, errors: list, criteria: str) -> list:
"""Tool-specific logic as a helper method."""
return [e for e in errors if criteria in e.message]
```
+---
#### Available ToolContext Methods
@@ -228,7 +237,7 @@ For the current and complete list of available methods, see `marimo/_ai/_tools/b
#### When to Use Try/Except
-**Only use try/except when you need to catch a specific error and provide tailored guidance to the AI agent.**
+**Only use try/except when you need to catch a specific error and provide tailored guidance to the AI agent.**
- ✅ **Use try/except**: For expected errors where you want to guide the agent (e.g., "Use get_lightweight_cell_map to find valid cell IDs")
- ❌ **Don't use try/except**: For unexpected errors—they're automatically wrapped in `ToolExecutionError` and surfaced to the agent
@@ -237,6 +246,7 @@ For the current and complete list of available methods, see `marimo/_ai/_tools/b
Use `ToolExecutionError` for expected failures:
+---
```python
from marimo._ai._tools.utils.exceptions import ToolExecutionError
@@ -249,6 +259,7 @@ raise ToolExecutionError(
meta={"session_id": session_id}, # Additional context
)
```
+---
**Common Error Codes:**
@@ -260,11 +271,12 @@ raise ToolExecutionError(
**Error Handling Best Practices:**
+---
```python
def handle(self, args: YourToolArgs) -> YourToolOutput:
# ToolContext methods automatically raise ToolExecutionError if session not found
session = self.context.get_session(args.session_id)
-
+
# Validate inputs - raise ToolExecutionError directly for validation errors
if args.count < 0:
raise ToolExecutionError(
@@ -273,7 +285,7 @@ def handle(self, args: YourToolArgs) -> YourToolOutput:
is_retryable=False,
suggested_fix="Provide a count >= 0",
)
-
+
# Only use try/except for specific expected errors where you want to guide the agent
try:
result = self._operation_that_might_fail()
@@ -285,15 +297,17 @@ def handle(self, args: YourToolArgs) -> YourToolOutput:
is_retryable=False,
suggested_fix="Use get_lightweight_cell_map to find valid cell IDs",
)
-
+
# Don't wrap everything in try/except - unexpected errors are handled automatically
return YourToolOutput(data=result)
```
+---
### 7. Register the Tool
Add your tool to the registry in `marimo/_ai/_tools/tools_registry.py`:
+---
```python
from marimo._ai._tools.tools.your_tool import YourTool
@@ -304,6 +318,7 @@ SUPPORTED_BACKEND_AND_MCP_TOOLS: list[type[ToolBase[Any, Any]]] = [
YourTool, # Add your tool here
]
```
+---
**That's it!** Your tool is now automatically registered in both backend and MCP contexts.
@@ -311,6 +326,7 @@ SUPPORTED_BACKEND_AND_MCP_TOOLS: list[type[ToolBase[Any, Any]]] = [
Add your tool's Args and Output classes to the `TOOL_IO_CLASSES` list in `tests/_utils/test_msgspec_basestruct.py`. This ensures type compatibility between our serialization system and pydantic (used by the python mcp sdk).
+---
```python
from marimo._ai._tools.tools.your_tool import (
YourToolArgs,
@@ -323,6 +339,7 @@ TOOL_IO_CLASSES = [
YourToolOutput,
]
```
+---
### 9. Create Tests
@@ -330,6 +347,7 @@ TOOL_IO_CLASSES = [
Create `tests/_ai/tools/tools/test_your_tool.py`:
+---
```python
from __future__ import annotations
@@ -363,13 +381,13 @@ def test_your_tool_basic_case(mock_context: Mock) -> None:
# Setup mock
mock_session = Mock()
mock_context.get_session.return_value = mock_session
-
+
tool = YourTool(ToolContext())
tool.context = mock_context
-
+
# Execute tool
result = tool.handle(YourToolArgs(session_id=SessionId("test")))
-
+
# Assertions
assert result.status == "success"
assert result.data is not None
@@ -382,14 +400,14 @@ def test_your_tool_error_handling(mock_context: Mock) -> None:
"Session not found",
code="SESSION_NOT_FOUND",
)
-
+
tool = YourTool(ToolContext())
tool.context = mock_context
-
+
# Should raise ToolExecutionError
with pytest.raises(ToolExecutionError) as exc_info:
tool.handle(YourToolArgs(session_id=SessionId("invalid")))
-
+
assert exc_info.value.code == "SESSION_NOT_FOUND"
# if necessary
@@ -398,11 +416,13 @@ def test_your_tool_with_edge_cases(mock_context: Mock) -> None:
# Test your tool with edge cases
pass
```
+---
### 10. Run Tests
Run tests:
+---
```bash
# Run all tool tests
hatch run +py=3.12 test:test tests/_ai/tools
@@ -413,11 +433,13 @@ hatch run +py=3.12 test:test tests/_ai/tools/tools/test_your_tool.py
# Run with verbose output
hatch run +py=3.12 test:test tests/_ai/tools/tools/test_your_tool.py -v
```
+---
### 11. Update Documentation
Add your tool to the user-facing documentation in `docs/guides/editor_features/tools.md`. Add a row to the appropriate category table:
+---
```markdown
## Available tools
@@ -427,6 +449,7 @@ Add your tool to the user-facing documentation in `docs/guides/editor_features/t
|------|-------------|
| **your_tool_name** | Brief description of what the tool does. Takes `param1` and `param2` parameters. Returns description of output. |
```
+---
Choose the appropriate category:
- **Inspection**: Tools for exploring notebook structure and runtime
@@ -456,6 +479,7 @@ Choose the appropriate category:
Design helpful outputs:
+---
```python
return YourToolOutput(
data=result,
@@ -470,6 +494,7 @@ return YourToolOutput(
meta={"query_time": 0.5},
)
```
+---
### Helper Methods
@@ -483,38 +508,45 @@ return YourToolOutput(
### ❌ Don't: Duplicate ToolContext Logic
+---
```python
# Bad: Reimplementing context logic
def handle(self, args: Args) -> Output:
session = self.context.get_session(args.session_id)
- cell_ops = session.session_view.cell_operations
+ cell_notifications = session.session_view.cell_notifications
errors = []
- for cell_id, op in cell_ops.items():
+ for cell_id, op in cell_notifications.items():
if op.output and op.output.channel == CellChannel.MARIMO_ERROR:
errors.append(...) # Duplicating error extraction
```
+---
### ✅ Do: Use ToolContext Methods
+---
```python
# Good: Using context methods
def handle(self, args: Args) -> Output:
errors = self.context.get_notebook_errors(
- args.session_id,
+ args.session_id,
include_stderr=True
)
```
+---
### ❌ Don't: Raise Generic Exceptions
+---
```python
# Bad: Using generic exceptions
if not found:
raise ValueError("Not found")
```
+---
### ✅ Do: Raise ToolExecutionError
+---
```python
# Good: Structured error with metadata
if not found:
@@ -525,17 +557,21 @@ if not found:
suggested_fix="Use get_lightweight_cell_map to find valid cell IDs",
)
```
+---
### ❌ Don't: Return Unstructured Data
+---
```python
# Bad: Returning raw data
def handle(self, args: Args) -> Output:
return {"data": [...], "count": 5} # type: ignore
```
+---
### ✅ Do: Use Typed Dataclass Output
+---
```python
# Good: Structured output with SuccessResult
def handle(self, args: Args) -> Output:
@@ -545,9 +581,11 @@ def handle(self, args: Args) -> Output:
next_steps=["Review the results"],
)
```
+---
### ❌ Don't: Use TypedDict or Other Type Annotations
+---
```python
# Bad: Using TypedDict for tool input/output
from typing import TypedDict
@@ -556,9 +594,11 @@ class YourToolArgs(TypedDict):
session_id: str
count: int
```
+---
### ✅ Do: Use Dataclasses
+---
```python
# Good: Using dataclasses as required
from dataclasses import dataclass
@@ -568,6 +608,7 @@ class YourToolArgs:
session_id: SessionId
count: int = 0
```
+---
**Why?** The tool system requires dataclasses for proper serialization, validation, and compatibility with both backend and MCP contexts.
@@ -577,21 +618,24 @@ class YourToolArgs:
For operations that need async/await:
+---
```python
class AsyncTool(ToolBase[Args, Output]):
"""Tool with async operations."""
-
+
async def handle(self, args: Args) -> Output: # type: ignore[override]
"""Note: Add type: ignore[override] for async handle."""
session = self.context.get_session(args.session_id)
result = await self._async_work(session)
return Output(result=result)
```
+---
### Tools with Side Effects
Generally it's better to avoid side effects in your tool. If it can't be avoided make sure to document side effects in guidelines:
+---
```python
guidelines = ToolGuidelines(
side_effects=[
@@ -600,11 +644,13 @@ guidelines = ToolGuidelines(
],
)
```
+---
### Complex Return Types
Use nested dataclasses for complex outputs:
+---
```python
@dataclass
class CellInfo:
@@ -617,6 +663,7 @@ class ComplexOutput(SuccessResult):
cells: list[CellInfo] = field(default_factory=list)
summary: dict[str, Any] = field(default_factory=dict)
```
+---
## Review Checklist
diff --git a/frontend/src/core/cells/__tests__/runs.test.ts b/frontend/src/core/cells/__tests__/runs.test.ts
index e11479b37a..3ec5d3580b 100644
--- a/frontend/src/core/cells/__tests__/runs.test.ts
+++ b/frontend/src/core/cells/__tests__/runs.test.ts
@@ -26,7 +26,7 @@ describe("RunsState Reducer", () => {
const timestamp = Date.now();
const code = "print('Hello World')";
- const cellOperation: CellMessage = {
+ const cellNotification: CellMessage = {
run_id: runId,
cell_id: cellId,
timestamp,
@@ -35,9 +35,9 @@ describe("RunsState Reducer", () => {
function addQueuedCell(): RunsState {
return reducer(state, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: cellOperation,
+ cellNotification: cellNotification,
code: "print('Hello World')",
},
});
@@ -94,9 +94,9 @@ describe("RunsState Reducer", () => {
let intermediateState = addQueuedCell();
intermediateState = reducer(intermediateState, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId2,
cell_id: "cell2",
timestamp,
@@ -120,9 +120,9 @@ describe("RunsState Reducer", () => {
const runStartTimestamp = timestamp + 1000;
const updatedState = reducer(state, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: cellId,
timestamp: timestamp + 1000,
@@ -141,9 +141,9 @@ describe("RunsState Reducer", () => {
);
const successState = reducer(updatedState, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: cellId,
timestamp: runStartTimestamp + 5000,
@@ -168,9 +168,9 @@ describe("RunsState Reducer", () => {
it("should limit the number of runs to MAX_RUNS", () => {
for (let i = 1; i <= MAX_RUNS + 1; i++) {
state = reducer(state, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: `run${i}`,
cell_id: `cell${i}`,
timestamp: timestamp,
@@ -194,9 +194,9 @@ describe("RunsState Reducer", () => {
const truncatedCode = longCode.slice(0, MAX_CODE_LENGTH);
const nextState = reducer(state, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: cellId,
timestamp,
@@ -216,9 +216,9 @@ describe("RunsState Reducer", () => {
const errorTimestamp = timestamp + 2000;
const errorState = reducer(state, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: cellId,
timestamp: errorTimestamp,
@@ -244,9 +244,9 @@ describe("RunsState Reducer", () => {
const errorTimestamp = timestamp + 2000;
const errorState = reducer(state, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: cellId,
timestamp: errorTimestamp,
@@ -269,9 +269,9 @@ describe("RunsState Reducer", () => {
it("should maintain status as error when there was a previous error", () => {
const erroredState = reducer(state, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: cellId,
timestamp,
@@ -284,9 +284,9 @@ describe("RunsState Reducer", () => {
});
const finalState = reducer(erroredState, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: cellId,
timestamp: timestamp + 2000,
@@ -308,9 +308,9 @@ describe("RunsState Reducer", () => {
let intermediateState = addQueuedCell();
intermediateState = reducer(intermediateState, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId2,
cell_id: "cell2",
timestamp: timestamp + 1000,
@@ -321,9 +321,9 @@ describe("RunsState Reducer", () => {
});
const finalState = reducer(intermediateState, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId3,
cell_id: "cell3",
timestamp: timestamp + 2000,
@@ -341,9 +341,9 @@ describe("RunsState Reducer", () => {
const run1 = state1.runMap.get(runId);
const state2 = reducer(state1, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: "cell2",
timestamp: timestamp + 1000,
@@ -363,9 +363,9 @@ describe("RunsState Reducer", () => {
const run1 = state1.runMap.get(runId);
const state2 = reducer(state1, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: cellId,
timestamp: timestamp + 1000,
@@ -382,9 +382,9 @@ describe("RunsState Reducer", () => {
it("should skip markdown for first run", () => {
const markdownState = reducer(state, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: cellId,
timestamp,
@@ -401,9 +401,9 @@ describe("RunsState Reducer", () => {
it("should not skip markdown if first run was not markdown", () => {
// Add non-markdown run first
let nextState = reducer(state, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: cellId,
timestamp,
@@ -415,9 +415,9 @@ describe("RunsState Reducer", () => {
// Add markdown run second
nextState = reducer(nextState, {
- type: "addCellOperation",
+ type: "addCellNotification",
payload: {
- cellOperation: {
+ cellNotification: {
run_id: runId,
cell_id: "cell2",
timestamp: timestamp + 1000,
diff --git a/frontend/src/core/cells/runs.ts b/frontend/src/core/cells/runs.ts
index 12d428a4f3..681c761a63 100644
--- a/frontend/src/core/cells/runs.ts
+++ b/frontend/src/core/cells/runs.ts
@@ -40,13 +40,13 @@ const {
valueAtom: runsAtom,
useActions: useRunsActions,
} = createReducerAndAtoms(initialState, {
- addCellOperation: (
+ addCellNotification: (
state: RunsState,
- opts: { cellOperation: CellMessage; code: string },
+ opts: { cellNotification: CellMessage; code: string },
): RunsState => {
- const { cellOperation, code } = opts;
- const timestamp = cellOperation.timestamp ?? 0;
- const runId = cellOperation.run_id as RunId | undefined;
+ const { cellNotification, code } = opts;
+ const timestamp = cellNotification.timestamp ?? 0;
+ const runId = cellNotification.run_id as RunId | undefined;
if (!runId) {
return state;
}
@@ -61,15 +61,15 @@ const {
// We determine if the cell operation errored by looking at the output
const erroredOutput =
- cellOperation.output &&
- (cellOperation.output.channel === "marimo-error" ||
- cellOperation.output.channel === "stderr");
+ cellNotification.output &&
+ (cellNotification.output.channel === "marimo-error" ||
+ cellNotification.output.channel === "stderr");
let status: CellRun["status"] = erroredOutput
? "error"
- : cellOperation.status === "queued"
+ : cellNotification.status === "queued"
? "queued"
- : cellOperation.status === "running"
+ : cellNotification.status === "running"
? "running"
: "success";
@@ -79,9 +79,9 @@ const {
runId,
cellRuns: new Map([
[
- cellOperation.cell_id as CellId,
+ cellNotification.cell_id as CellId,
{
- cellId: cellOperation.cell_id as CellId,
+ cellId: cellNotification.cell_id as CellId,
code: code.slice(0, MAX_CODE_LENGTH),
elapsedTime: 0,
status: status,
@@ -111,13 +111,15 @@ const {
// Update existing run
const nextCellRuns = new Map(existingRun.cellRuns);
- const existingCellRun = nextCellRuns.get(cellOperation.cell_id as CellId);
+ const existingCellRun = nextCellRuns.get(
+ cellNotification.cell_id as CellId,
+ );
// Early return if nothing changed
if (
existingCellRun &&
!erroredOutput &&
- cellOperation.status === "queued"
+ cellNotification.status === "queued"
) {
return state;
}
@@ -129,7 +131,7 @@ const {
status = hasErroredPreviously || erroredOutput ? "error" : status;
const startTime =
- cellOperation.status === "running"
+ cellNotification.status === "running"
? timestamp
: existingCellRun.startTime;
@@ -138,15 +140,15 @@ const {
? timestamp - existingCellRun.startTime
: undefined;
- nextCellRuns.set(cellOperation.cell_id as CellId, {
+ nextCellRuns.set(cellNotification.cell_id as CellId, {
...existingCellRun,
startTime,
elapsedTime,
status,
});
} else {
- nextCellRuns.set(cellOperation.cell_id as CellId, {
- cellId: cellOperation.cell_id as CellId,
+ nextCellRuns.set(cellNotification.cell_id as CellId, {
+ cellId: cellNotification.cell_id as CellId,
code: code.slice(0, MAX_CODE_LENGTH),
elapsedTime: 0,
status: status,
diff --git a/frontend/src/core/datasets/state.ts b/frontend/src/core/datasets/state.ts
index 15db04cd88..1a85027867 100644
--- a/frontend/src/core/datasets/state.ts
+++ b/frontend/src/core/datasets/state.ts
@@ -4,7 +4,7 @@ import { atom, useAtomValue } from "jotai";
import { createReducerAndAtoms } from "@/utils/createReducer";
import type {
DataColumnPreview,
- OperationMessageData,
+ NotificationMessageData,
} from "../kernel/messages";
import { getRequestClient } from "../network/requests";
import type { VariableName } from "../variables/types";
@@ -25,7 +25,7 @@ const {
valueAtom: datasetsAtom,
useActions,
} = createReducerAndAtoms(initialState, {
- addDatasets: (state, datasets: OperationMessageData<"datasets">) => {
+ addDatasets: (state, datasets: NotificationMessageData<"datasets">) => {
const { previewDatasetColumn } = getRequestClient();
// Quietly in the background make requests to get the previews for
// opened columns, in the new tables
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index cd57919d6a..1b93fd38bd 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -6,7 +6,7 @@ import { Deferred } from "@/utils/Deferred";
import { throwNotImplemented } from "@/utils/functions";
import type { JsonString } from "@/utils/json/base64";
import { Logger } from "@/utils/Logger";
-import type { OperationMessage } from "../kernel/messages";
+import type { NotificationPayload } from "../kernel/messages";
import { getMarimoVersion } from "../meta/globals";
import type { EditRequests, RunRequests } from "../network/types";
import { store } from "../state/jotai";
@@ -30,7 +30,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
private rpc: ReturnType<typeof getWorkerRPC<WorkerSchema>>;
private messageConsumer:
- | ((message: JsonString<OperationMessage>) => void)
+ | ((message: JsonString<NotificationPayload>) => void)
| undefined;
public initialized = new Deferred<void>();
@@ -94,7 +94,9 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
await this.rpc.proxy.request.startSession(opts);
}
- consumeMessages(consumer: (message: JsonString<OperationMessage>) => void) {
+ consumeMessages(
+ consumer: (message: JsonString<NotificationPayload>) => void,
+ ) {
this.messageConsumer = consumer;
this.rpc.proxy.send.consumerReady({});
}
diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.ts
index 0b67c61e31..4bd5fb1901 100644
--- a/frontend/src/core/islands/main.ts
+++ b/frontend/src/core/islands/main.ts
@@ -30,7 +30,7 @@ import { MarimoValueInputEvent } from "../dom/events";
import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";
import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";
import {
- handleCellOperation,
+ handleCellNotificationeration,
handleKernelReady,
handleRemoveUIElements,
} from "../kernel/handlers";
@@ -161,7 +161,7 @@ export async function initialize() {
);
return;
case "cell-op":
- handleCellOperation(msg.data, actions.handleCellMessage);
+ handleCellNotificationeration(msg.data, actions.handleCellMessage);
return;
case "alert":
// TODO: support toast with islands
@@ -189,7 +189,7 @@ export async function initialize() {
return;
case "cache-cleared":
return;
- case "cache-info-fetched":
+ case "cache-info":
return;
default:
logNever(msg.data);
diff --git a/frontend/src/core/islands/worker/controller.ts b/frontend/src/core/islands/worker/controller.ts
index 3463a57fcc..7549a064ba 100644
--- a/frontend/src/core/islands/worker/controller.ts
+++ b/frontend/src/core/islands/worker/controller.ts
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type { PyodideInterface } from "pyodide";
import { defaultUserConfig } from "@/core/config/config-schema";
-import type { OperationMessage } from "@/core/kernel/messages";
+import type { NotificationPayload } from "@/core/kernel/messages";
import { DefaultWasmController } from "@/core/wasm/worker/bootstrap";
import { WasmFileSystem } from "@/core/wasm/worker/fs";
import type { SerializedBridge } from "@/core/wasm/worker/types";
@@ -37,7 +37,7 @@ export class ReadonlyWasmController extends DefaultWasmController {
override async startSession(opts: {
code: string;
filename: string | null;
- onMessage: (message: JsonString<OperationMessage>) => void;
+ onMessage: (message: JsonString<NotificationPayload>) => void;
}): Promise<SerializedBridge> {
const bridge = super.startSession({
queryParameters: {},
diff --git a/frontend/src/core/islands/worker/worker.tsx b/frontend/src/core/islands/worker/worker.tsx
index 3501131921..6731430af5 100644
--- a/frontend/src/core/islands/worker/worker.tsx
+++ b/frontend/src/core/islands/worker/worker.tsx
@@ -7,7 +7,7 @@ import {
createWorkerParentTransport,
type RPCSchema,
} from "rpc-anywhere";
-import type { OperationMessage } from "@/core/kernel/messages";
+import type { NotificationPayload } from "@/core/kernel/messages";
import type { ParentSchema } from "@/core/wasm/rpc";
import { TRANSPORT_ID } from "@/core/wasm/worker/constants";
import { getPyodideVersion } from "@/core/wasm/worker/getPyodideVersion";
@@ -45,7 +45,7 @@ async function loadPyodideAndPackages() {
const pyodideReadyPromise = loadPyodideAndPackages();
const messageBuffer = new MessageBuffer(
- (message: JsonString<OperationMessage>) => {
+ (message: JsonString<NotificationPayload>) => {
rpc.send.kernelMessage({ message });
},
);
@@ -147,7 +147,7 @@ export type WorkerSchema = RPCSchema<
// Emitted when the worker is ready
ready: {};
// Emitted when the kernel sends a message
- kernelMessage: { message: JsonString<OperationMessage> };
+ kernelMessage: { message: JsonString<NotificationPayload> };
// Emitted when the Pyodide is initialized
initialized: {};
// Emitted when the Pyodide fails to initialize
diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.ts
index c53757d43f..c7291df958 100644
--- a/frontend/src/core/kernel/handlers.ts
+++ b/frontend/src/core/kernel/handlers.ts
@@ -16,11 +16,11 @@ import { VirtualFileTracker } from "../static/virtual-file-tracker";
import type {
Capabilities,
CellMessage,
- OperationMessageData,
+ NotificationMessageData,
} from "./messages";
export function handleKernelReady(
- data: OperationMessageData<"kernel-ready">,
+ data: NotificationMessageData<"kernel-ready">,
opts: {
autoInstantiate: boolean;
setCells: (cells: CellData[], layout: LayoutState) => void;
@@ -133,7 +133,7 @@ export function handleKernelReady(
}
export function handleRemoveUIElements(
- data: OperationMessageData<"remove-ui-elements">,
+ data: NotificationMessageData<"remove-ui-elements">,
) {
// This removes the element from the registry to (1) clean-up
// memory and (2) make sure that the old value doesn't get re-used
@@ -143,8 +143,8 @@ export function handleRemoveUIElements(
VirtualFileTracker.INSTANCE.removeForCellId(cellId);
}
-export function handleCellOperation(
- data: OperationMessageData<"cell-op">,
+export function handleCellNotificationeration(
+ data: NotificationMessageData<"cell-op">,
handleCellMessage: (message: CellMessage) => void,
) {
/* Register a state transition for a cell.
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index 9a7affbc8f..1fd78b2309 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -13,7 +13,7 @@ export const DATA_TYPES = [
"time",
"unknown",
] as const;
-export type Banner = OperationMessageData<"banner">;
+export type Banner = NotificationMessageData<"banner">;
export type AiInlineCompletionRequest = schemas["AiInlineCompletionRequest"];
export type DataTableColumn = schemas["DataTableColumn"];
export type DataTable = schemas["DataTable"];
@@ -27,32 +27,35 @@ export type MarimoError = Extract<
{ type: string }[]
>[number];
export type OutputMessage = schemas["CellOutput"];
-export type CompletionOption = schemas["CompletionResult"]["options"][0];
-export type CompletionResultMessage = OperationMessageData<"completion-result">;
+export type CompletionOption =
+ schemas["CompletionResultNotification"]["options"][0];
+export type CompletionResultMessage =
+ NotificationMessageData<"completion-result">;
export type HumanReadableStatus = schemas["HumanReadableStatus"];
export type FunctionCallResultMessage =
- OperationMessageData<"function-call-result">;
+ NotificationMessageData<"function-call-result">;
export type PackageInstallationStatus =
- schemas["InstallingPackageAlert"]["packages"];
-export type DataColumnPreview = OperationMessageData<"data-column-preview">;
-export type SQLTablePreview = OperationMessageData<"sql-table-preview">;
+ schemas["InstallingPackageAlertNotification"]["packages"];
+export type DataColumnPreview = NotificationMessageData<"data-column-preview">;
+export type SQLTablePreview = NotificationMessageData<"sql-table-preview">;
export type SQLTableListPreview =
- OperationMessageData<"sql-table-list-preview">;
-export type ValidateSQLResult = OperationMessageData<"validate-sql-result">;
-export type SecretKeysResult = OperationMessageData<"secret-keys-result">;
-export type StartupLogs = OperationMessageData<"startup-logs">;
-export type CellMessage = OperationMessageData<"cell-op">;
-export type Capabilities = OperationMessageData<"kernel-ready">["capabilities"];
-export type CacheInfoFetched = OperationMessageData<"cache-info-fetched">;
+ NotificationMessageData<"sql-table-list-preview">;
+export type ValidateSQLResult = NotificationMessageData<"validate-sql-result">;
+export type SecretKeysResult = NotificationMessageData<"secret-keys-result">;
+export type StartupLogs = NotificationMessageData<"startup-logs">;
+export type CellMessage = NotificationMessageData<"cell-op">;
+export type Capabilities =
+ NotificationMessageData<"kernel-ready">["capabilities"];
+export type CacheInfoFetched = NotificationMessageData<"cache-info">;
-export type MessageOperationUnion = schemas["KnownUnions"]["operation"];
+export type NotificationMessage = schemas["KnownUnions"]["notification"];
-export type OperationMessageType = MessageOperationUnion["op"];
-export interface OperationMessage {
- data: MessageOperationUnion;
+export type NotificationMessageType = NotificationMessage["op"];
+export interface NotificationPayload {
+ data: NotificationMessage;
}
-export type OperationMessageData<T extends OperationMessageType> = Omit<
- Extract<MessageOperationUnion, { op: T }>,
+export type NotificationMessageData<T extends NotificationMessageType> = Omit<
+ Extract<NotificationMessage, { op: T }>,
"op"
>;
diff --git a/frontend/src/core/kernel/queryParamHandlers.ts b/frontend/src/core/kernel/queryParamHandlers.ts
index 1078ddd3f3..3ee07016ed 100644
--- a/frontend/src/core/kernel/queryParamHandlers.ts
+++ b/frontend/src/core/kernel/queryParamHandlers.ts
@@ -1,15 +1,15 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import type { OperationMessageData } from "./messages";
+import type { NotificationMessageData } from "./messages";
export const queryParamHandlers = {
- append: (data: OperationMessageData<"query-params-append">) => {
+ append: (data: NotificationMessageData<"query-params-append">) => {
const url = new URL(window.location.href);
url.searchParams.append(data.key, data.value);
window.history.pushState({}, "", `${url.pathname}${url.search}`);
return;
},
- set: (data: OperationMessageData<"query-params-set">) => {
+ set: (data: NotificationMessageData<"query-params-set">) => {
const url = new URL(window.location.href);
if (Array.isArray(data.value)) {
url.searchParams.delete(data.key);
@@ -20,7 +20,7 @@ export const queryParamHandlers = {
window.history.pushState({}, "", `${url.pathname}${url.search}`);
return;
},
- delete: (data: OperationMessageData<"query-params-delete">) => {
+ delete: (data: NotificationMessageData<"query-params-delete">) => {
const url = new URL(window.location.href);
if (data.value == null) {
url.searchParams.delete(data.key);
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 925c37b0ce..75aca16447 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -14,7 +14,7 @@ export type CellConfig = schemas["CellConfig"];
* idle: not running.
* disabled-transitively: disabled because an ancestor was disabled.
*/
-export type RuntimeState = schemas["CellOp"]["status"];
+export type RuntimeState = schemas["CellNotification"]["status"];
export type CodeCompletionRequest = schemas["CodeCompletionRequest"];
export type DeleteCellRequest = schemas["DeleteCellRequest"];
export type ExecuteMultipleRequest = schemas["ExecuteMultipleRequest"];
diff --git a/frontend/src/core/wasm/worker/bootstrap.ts b/frontend/src/core/wasm/worker/bootstrap.ts
index 4e7ad82686..f2d68eedfe 100644
--- a/frontend/src/core/wasm/worker/bootstrap.ts
+++ b/frontend/src/core/wasm/worker/bootstrap.ts
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { loadPyodide, type PyodideInterface } from "pyodide";
import type { UserConfig } from "@/core/config/config-schema";
-import type { OperationMessage } from "@/core/kernel/messages";
+import type { NotificationPayload } from "@/core/kernel/messages";
import type { JsonString } from "@/utils/json/base64";
import { invariant } from "../../../utils/invariant";
import { Logger } from "../../../utils/Logger";
@@ -99,7 +99,7 @@ export class DefaultWasmController implements WasmController {
queryParameters: Record<string, string | string[]>;
code: string;
filename: string | null;
- onMessage: (message: JsonString<OperationMessage>) => void;
+ onMessage: (message: JsonString<NotificationPayload>) => void;
userConfig: UserConfig;
}): Promise<SerializedBridge> {
const { code, filename, onMessage, queryParameters, userConfig } = opts;
diff --git a/frontend/src/core/wasm/worker/types.ts b/frontend/src/core/wasm/worker/types.ts
index 01605d5c7b..337cbd1032 100644
--- a/frontend/src/core/wasm/worker/types.ts
+++ b/frontend/src/core/wasm/worker/types.ts
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type { PyodideInterface } from "pyodide";
import type { UserConfig } from "@/core/config/config-schema";
-import type { OperationMessage } from "@/core/kernel/messages";
+import type { NotificationPayload } from "@/core/kernel/messages";
import type { JsonString } from "@/utils/json/base64";
import type {
CodeCompletionRequest,
@@ -57,7 +57,7 @@ export interface WasmController {
code: string;
filename: string | null;
userConfig: UserConfig;
- onMessage: (message: JsonString<OperationMessage>) => void;
+ onMessage: (message: JsonString<NotificationPayload>) => void;
}): Promise<SerializedBridge>;
}
diff --git a/frontend/src/core/wasm/worker/worker.ts b/frontend/src/core/wasm/worker/worker.ts
index 45e606d8dd..a7f4136f9a 100644
--- a/frontend/src/core/wasm/worker/worker.ts
+++ b/frontend/src/core/wasm/worker/worker.ts
@@ -8,7 +8,7 @@ import {
type RPCSchema,
} from "rpc-anywhere";
import type { UserConfig } from "@/core/config/config-schema";
-import type { OperationMessage } from "@/core/kernel/messages";
+import type { NotificationPayload } from "@/core/kernel/messages";
import type {
ListPackagesResponse,
PackageOperationResponse,
@@ -64,7 +64,7 @@ async function loadPyodideAndPackages() {
}
const messageBuffer = new MessageBuffer(
- (message: JsonString<OperationMessage>) => {
+ (message: JsonString<NotificationPayload>) => {
rpc.send.kernelMessage({ message });
},
);
@@ -330,7 +330,7 @@ export type WorkerSchema = RPCSchema<
// Emitted when the worker is ready
ready: {};
// Emitted when the kernel sends a message
- kernelMessage: { message: JsonString<OperationMessage> };
+ kernelMessage: { message: JsonString<NotificationPayload> };
// Emitted when the Pyodide is initialized
initialized: {};
// Emitted when the Pyodide is initializing, with new messages
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index 86679dd7c1..1337ccb73d 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -6,7 +6,7 @@ import { useErrorBoundary } from "react-error-boundary";
import { toast } from "@/components/ui/use-toast";
import { getNotebook, useCellActions } from "@/core/cells/cells";
import { AUTOCOMPLETER } from "@/core/codemirror/completion/Autocompleter";
-import type { OperationMessage } from "@/core/kernel/messages";
+import type { NotificationPayload } from "@/core/kernel/messages";
import { useConnectionTransport } from "@/core/websocket/useWebSocket";
import { renderHTML } from "@/plugins/core/RenderHTML";
import {
@@ -43,7 +43,7 @@ import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";
import { useBannersActions } from "../errors/state";
import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";
import {
- handleCellOperation,
+ handleCellNotificationeration,
handleKernelReady,
handleRemoveUIElements,
} from "../kernel/handlers";
@@ -75,7 +75,7 @@ export function useMarimoKernelConnection(opts: {
const { showBoundary } = useErrorBoundary();
const { handleCellMessage, setCellCodes, setCellIds } = useCellActions();
- const { addCellOperation } = useRunsActions();
+ const { addCellNotification } = useRunsActions();
const setAppConfig = useSetAppConfig();
const { setVariables, setMetadata } = useVariablesActions();
const { addColumnPreview } = useDatasetsActions();
@@ -91,7 +91,7 @@ export function useMarimoKernelConnection(opts: {
const runtimeManager = useRuntimeManager();
const setCacheInfo = useSetAtom(cacheInfoAtom);
- const handleMessage = (e: MessageEvent<JsonString<OperationMessage>>) => {
+ const handleMessage = (e: MessageEvent<JsonString<NotificationPayload>>) => {
const msg = jsonParseWithSpecialChar(e.data);
switch (msg.data.op) {
case "reload":
@@ -154,12 +154,15 @@ export function useMarimoKernelConnection(opts: {
);
return;
case "cell-op": {
- handleCellOperation(msg.data, handleCellMessage);
+ handleCellNotificationeration(msg.data, handleCellMessage);
const cellData = getNotebook().cellData[msg.data.cell_id as CellId];
if (!cellData) {
return;
}
- addCellOperation({ cellOperation: msg.data, code: cellData.code });
+ addCellNotification({
+ cellNotification: msg.data,
+ code: cellData.code,
+ });
return;
}
@@ -251,7 +254,7 @@ export function useMarimoKernelConnection(opts: {
case "secret-keys-result":
SECRETS_REGISTRY.resolve(msg.data.request_id as RequestId, msg.data);
return;
- case "cache-info-fetched":
+ case "cache-info":
setCacheInfo(msg.data);
return;
case "cache-cleared":
diff --git a/frontend/src/utils/json/base64.ts b/frontend/src/utils/json/base64.ts
index 65c29c809e..ca7c9c6a9e 100644
--- a/frontend/src/utils/json/base64.ts
+++ b/frontend/src/utils/json/base64.ts
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import type { OperationMessageData } from "@/core/kernel/messages";
+import type { NotificationMessageData } from "@/core/kernel/messages";
import type { TypedString } from "../typed";
export type JsonString<T = unknown> = TypedString<"Json"> & {
@@ -64,10 +64,10 @@ export function binaryToByteString(binary: Uint8Array): ByteString {
}
export function safeExtractSetUIElementMessageBuffers(
- op: OperationMessageData<"send-ui-element-message">,
+ notification: NotificationMessageData<"send-ui-element-message">,
): readonly DataView[] {
// @ts-expect-error - TypeScript doesn't know that these strings are actually base64 strings
- const strs: Base64String[] = op.buffers ?? [];
+ const strs: Base64String[] = notification.buffers ?? [];
return strs.map((str) => {
const bytes = byteStringToBinary(typedAtob(str));
return new DataView(bytes.buffer);
diff --git a/marimo/_ai/_tools/base.py b/marimo/_ai/_tools/base.py
index 975fff0fa6..847d5944af 100644
--- a/marimo/_ai/_tools/base.py
+++ b/marimo/_ai/_tools/base.py
@@ -28,7 +28,7 @@ from marimo._ai._tools.utils.exceptions import ToolExecutionError
from marimo._ai._tools.utils.output_cleaning import clean_output
from marimo._config.config import CopilotMode
from marimo._messaging.cell_output import CellChannel
-from marimo._messaging.ops import CellOp
+from marimo._messaging.notification import CellNotification
from marimo._server.ai.tools.types import (
FunctionArgs,
ToolDefinition,
@@ -91,17 +91,19 @@ class ToolContext:
)
return session
- def get_cell_ops(self, session_id: SessionId, cell_id: CellId_t) -> CellOp:
+ def get_cell_notification(
+ self, session_id: SessionId, cell_id: CellId_t
+ ) -> CellNotification:
session_view = self.get_session(session_id).session_view
- if cell_id not in session_view.cell_operations:
+ if cell_id not in session_view.cell_notifications:
raise ToolExecutionError(
- f"Cell operation not found for cell {cell_id}",
- code="CELL_OPERATION_NOT_FOUND",
+ f"Cell notification not found for cell {cell_id}",
+ code="CELL_NOTIFICATION_NOT_FOUND",
is_retryable=False,
suggested_fix="Try again with a valid cell ID.",
meta={"cell_id": cell_id},
)
- return session_view.cell_operations[cell_id]
+ return session_view.cell_notifications[cell_id]
def get_active_sessions_internal(self) -> list[MarimoNotebookInfo]:
"""
@@ -149,14 +151,14 @@ class ToolContext:
notebook_errors: list[MarimoCellErrors] = []
stderr: list[str] = []
- for cell_id, cell_op in session_view.cell_operations.items():
+ for cell_id, cell_notif in session_view.cell_notifications.items():
errors = self.get_cell_errors(
session_id,
cell_id,
- maybe_cell_op=cell_op,
+ maybe_cell_notif=cell_notif,
)
if include_stderr:
- stderr = self.get_cell_console_outputs(cell_op).stderr
+ stderr = self.get_cell_console_outputs(cell_notif).stderr
if errors:
cell_errors_map[cell_id] = MarimoCellErrors(
cell_id=cell_id,
@@ -177,21 +179,23 @@ class ToolContext:
self,
session_id: SessionId,
cell_id: CellId_t,
- maybe_cell_op: Optional[CellOp] = None,
+ maybe_cell_notif: Optional[CellNotification] = None,
) -> list[MarimoErrorDetail]:
"""
Get all errors for a given cell.
"""
errors: list[MarimoErrorDetail] = []
- cell_op = maybe_cell_op or self.get_cell_ops(session_id, cell_id)
+ cell_notif = maybe_cell_notif or self.get_cell_notification(
+ session_id, cell_id
+ )
if (
- not cell_op.output
- or cell_op.output.channel != CellChannel.MARIMO_ERROR
+ not cell_notif.output
+ or cell_notif.output.channel != CellChannel.MARIMO_ERROR
):
return errors
- items = cell_op.output.data
+ items = cell_notif.output.data
if not isinstance(items, list):
# no errors
@@ -228,21 +232,21 @@ class ToolContext:
return errors
def get_cell_console_outputs(
- self, cell_op: CellOp
+ self, cell_notif: CellNotification
) -> MarimoCellConsoleOutputs:
"""
- Get the console outputs for a given cell operation.
+ Get the console outputs for a given cell notification.
"""
stdout_messages: list[str] = []
stderr_messages: list[str] = []
- if cell_op.console is None:
+ if cell_notif.console is None:
return MarimoCellConsoleOutputs(stdout=[], stderr=[])
console_outputs = (
- cell_op.console
- if isinstance(cell_op.console, list)
- else [cell_op.console]
+ cell_notif.console
+ if isinstance(cell_notif.console, list)
+ else [cell_notif.console]
)
for output in console_outputs:
if output is None:
diff --git a/marimo/_ai/_tools/tools/cells.py b/marimo/_ai/_tools/tools/cells.py
index d12097eb87..e9ca71b1d2 100644
--- a/marimo/_ai/_tools/tools/cells.py
+++ b/marimo/_ai/_tools/tools/cells.py
@@ -15,7 +15,10 @@ from marimo._ai._tools.types import (
from marimo._ai._tools.utils.exceptions import ToolExecutionError
from marimo._ast.models import CellData
from marimo._messaging.errors import Error
-from marimo._messaging.ops import CellOp, VariableValue
+from marimo._messaging.notification import (
+ CellNotification,
+ VariableValue,
+)
from marimo._types.ids import CellId_t, SessionId
if TYPE_CHECKING:
@@ -304,11 +307,11 @@ class GetCellRuntimeData(
"""Get cell runtime metadata including status and execution info."""
# Get basic runtime state from session view
session_view = session.session_view
- cell_op = session_view.cell_operations.get(cell_id)
+ cell_notif = session_view.cell_notifications.get(cell_id)
runtime_state = None
- if cell_op and cell_op.status is not None:
- runtime_state = cell_op.status
+ if cell_notif and cell_notif.status is not None:
+ runtime_state = cell_notif.status
# Get execution time if available
execution_time = session_view.last_execution_time.get(cell_id)
@@ -368,9 +371,9 @@ class GetCellOutputs(ToolBase[GetCellOutputArgs, GetCellOutputOutput]):
session = context.get_session(args.session_id)
session_view = session.session_view
cell_id = args.cell_id
- cell_op = session_view.cell_operations.get(cell_id)
+ cell_notif = session_view.cell_notifications.get(cell_id)
- if cell_op is None:
+ if cell_notif is None:
raise ToolExecutionError(
f"Cell {cell_id} not found in session {args.session_id}",
code="CELL_NOT_FOUND",
@@ -378,8 +381,8 @@ class GetCellOutputs(ToolBase[GetCellOutputArgs, GetCellOutputOutput]):
suggested_fix="Use get_lightweight_cell_map to find valid cell IDs",
)
- visual_output, visual_mimetype = self._get_visual_output(cell_op)
- console_outputs = context.get_cell_console_outputs(cell_op)
+ visual_output, visual_mimetype = self._get_visual_output(cell_notif)
+ console_outputs = context.get_cell_console_outputs(cell_notif)
return GetCellOutputOutput(
visual_output=CellVisualOutput(
@@ -394,14 +397,14 @@ class GetCellOutputs(ToolBase[GetCellOutputArgs, GetCellOutputOutput]):
)
def _get_visual_output(
- self, cell_op: CellOp
+ self, cell_notif: CellNotification
) -> tuple[Optional[str], Optional[str]]:
visual_output = None
visual_mimetype = None
- if cell_op.output:
- data = cell_op.output.data
+ if cell_notif.output:
+ data = cell_notif.output.data
visual_output = self._get_str_output_data(data)
- visual_mimetype = cell_op.output.mimetype
+ visual_mimetype = cell_notif.output.mimetype
return visual_output, visual_mimetype
def _get_str_output_data(
diff --git a/marimo/_ai/_tools/tools/tables_and_variables.py b/marimo/_ai/_tools/tools/tables_and_variables.py
index 9f2023e24b..704c8b8745 100644
--- a/marimo/_ai/_tools/tools/tables_and_variables.py
+++ b/marimo/_ai/_tools/tools/tables_and_variables.py
@@ -7,7 +7,7 @@ from typing import Optional
from marimo._ai._tools.base import ToolBase
from marimo._ai._tools.types import SuccessResult, ToolGuidelines
from marimo._data.models import DataTableColumn
-from marimo._messaging.ops import VariableValue
+from marimo._messaging.notification import VariableValue
from marimo._server.sessions import Session
from marimo._types.ids import SessionId
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index d789fc3aa1..3a108a9808 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -69,7 +69,7 @@ if TYPE_CHECKING:
from collections.abc import Sequence
from types import FrameType, TracebackType
- from marimo._messaging.ops import HumanReadableStatus
+ from marimo._messaging.notification import HumanReadableStatus
from marimo._plugins.core.web_component import JSONType
from marimo._runtime.context.types import ExecutionContext
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index c75bc19a70..9fb1d8bc59 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -15,7 +15,7 @@ import msgspec.json
from marimo._cli.print import orange
from marimo._data.models import DataType
from marimo._messaging.errors import Error as MarimoError
-from marimo._messaging.ops import MessageOperation
+from marimo._messaging.notification import NotificationMessage
from marimo._server.session.serialize import (
serialize_notebook,
serialize_session_view,
@@ -32,7 +32,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
import marimo._config.config as config
import marimo._data.models as data
import marimo._messaging.errors as errors
- import marimo._messaging.ops as ops
+ import marimo._messaging.notification as notification
import marimo._runtime.requests as requests
import marimo._secrets.models as secrets_models
import marimo._server.models.completion as completion
@@ -102,41 +102,41 @@ def _generate_server_api_schema() -> dict[str, Any]:
secrets_models.SecretKeysWithProvider,
secrets.CreateSecretRequest,
# Operations
- ops.CellOp,
- ops.HumanReadableStatus,
- ops.FunctionCallResult,
- ops.SendUIElementMessage,
- ops.RemoveUIElements,
- ops.Interrupted,
- ops.CompletedRun,
- ops.KernelReady,
- ops.CompletionResult,
- ops.Alert,
- ops.MissingPackageAlert,
- ops.InstallingPackageAlert,
- ops.Reconnected,
- ops.Banner,
- ops.Reload,
- ops.VariableDeclaration,
- ops.VariableValue,
- ops.Variables,
- ops.VariableValues,
- ops.Datasets,
- ops.DataColumnPreview,
- ops.SQLTablePreview,
- ops.SQLTableListPreview,
- ops.DataSourceConnections,
- ops.SecretKeysResult,
- ops.CacheCleared,
- ops.CacheInfoFetched,
- ops.QueryParamsSet,
- ops.QueryParamsAppend,
- ops.QueryParamsDelete,
- ops.QueryParamsClear,
- ops.UpdateCellCodes,
- ops.UpdateCellIdsRequest,
- ops.FocusCell,
- ops.MessageOperation,
+ notification.CellNotification,
+ notification.HumanReadableStatus,
+ notification.FunctionCallResultNotification,
+ notification.UIElementMessageNotification,
+ notification.RemoveUIElementsNotification,
+ notification.InterruptedNotification,
+ notification.CompletedRunNotification,
+ notification.KernelReadyNotification,
+ notification.CompletionResultNotification,
+ notification.AlertNotification,
+ notification.MissingPackageAlertNotification,
+ notification.InstallingPackageAlertNotification,
+ notification.ReconnectedNotification,
+ notification.BannerNotification,
+ notification.ReloadNotification,
+ notification.VariableDeclarationNotification,
+ notification.VariableValue,
+ notification.VariablesNotification,
+ notification.VariableValuesNotification,
+ notification.DatasetsNotification,
+ notification.DataColumnPreviewNotification,
+ notification.SQLTablePreviewNotification,
+ notification.SQLTableListPreviewNotification,
+ notification.DataSourceConnectionsNotification,
+ notification.SecretKeysResultNotification,
+ notification.CacheClearedNotification,
+ notification.CacheInfoNotification,
+ notification.QueryParamsSetNotification,
+ notification.QueryParamsAppendNotification,
+ notification.QueryParamsDeleteNotification,
+ notification.QueryParamsClearNotification,
+ notification.UpdateCellCodesNotification,
+ notification.UpdateCellIdsNotification,
+ notification.FocusCellNotification,
+ notification.NotificationMessage,
# ai
ChatMessage,
ToolDefinition,
@@ -215,6 +215,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
models.MCPRefreshResponse,
requests.CodeCompletionRequest,
requests.DeleteCellRequest,
+ requests.UpdateCellIdsRequest,
requests.HTTPRequest,
requests.ExecuteMultipleRequest,
requests.ExecuteScratchpadRequest,
@@ -266,12 +267,12 @@ def _generate_server_api_schema() -> dict[str, Any]:
data.NonNestedLiteral: "NonNestedLiteral",
RuntimeStateType: "RuntimeState",
CellChannel: "CellChannel",
- ops.MessageOperation: "MessageOperation",
+ notification.NotificationMessage: "NotificationMessage",
}
# Hack to get the unions to be included in the schema
class KnownUnions(msgspec.Struct):
- operation: MessageOperation
+ notification: NotificationMessage
error: MarimoError
data_type: DataType
diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.py
index c77c3407a1..6ca47318cb 100644
--- a/marimo/_data/preview_column.py
+++ b/marimo/_data/preview_column.py
@@ -13,7 +13,10 @@ from marimo._data.sql_summaries import (
get_sql_stats,
)
from marimo._dependencies.dependencies import DependencyManager
-from marimo._messaging.ops import ColumnPreview, DataColumnPreview
+from marimo._messaging.notification import (
+ ColumnPreview,
+ DataColumnPreviewNotification,
+)
from marimo._plugins.ui._impl.tables.table_manager import (
FieldType,
TableManager,
@@ -136,7 +139,7 @@ def get_column_preview_dataset(
def get_column_preview_for_dataframe(
item: object,
request: PreviewDatasetColumnRequest,
-) -> DataColumnPreview | None:
+) -> DataColumnPreviewNotification | None:
"""
Finds the table manager for the item and gets the column preview.
"""
@@ -148,7 +151,7 @@ def get_column_preview_for_dataframe(
return None
column_preview = get_column_preview_dataset(table, table_name, column_name)
- return DataColumnPreview(
+ return DataColumnPreviewNotification(
table_name=table_name,
column_name=column_name,
chart_spec=column_preview.chart_spec,
@@ -163,7 +166,7 @@ def get_column_preview_for_duckdb(
*,
fully_qualified_table_name: str,
column_name: str,
-) -> Optional[DataColumnPreview]:
+) -> Optional[DataColumnPreviewNotification]:
DependencyManager.duckdb.require(why="previewing DuckDB columns")
column_type = get_column_type(fully_qualified_table_name, column_name)
@@ -202,7 +205,7 @@ def get_column_preview_for_duckdb(
except Exception as e:
LOGGER.warning(f"Failed to generate Altair chart: {str(e)}")
- return DataColumnPreview(
+ return DataColumnPreviewNotification(
table_name=fully_qualified_table_name,
column_name=column_name,
chart_spec=chart_spec,
diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.py
index 6e40090e26..25bb1d4524 100644
--- a/marimo/_messaging/console_output_worker.py
+++ b/marimo/_messaging/console_output_worker.py
@@ -37,11 +37,11 @@ def _write_console_output(
data: str,
mimetype: ConsoleMimeType,
) -> None:
- from marimo._messaging.notification_utils import broadcast_op
- from marimo._messaging.ops import CellOp
+ from marimo._messaging.notification import CellNotification
+ from marimo._messaging.notification_utils import broadcast_notification
- broadcast_op(
- CellOp(
+ broadcast_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput(
channel=stream_type,
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/notification.py
similarity index 76%
rename from marimo/_messaging/ops.py
rename to marimo/_messaging/notification.py
index 0e1f2111c4..98119317e3 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/notification.py
@@ -47,14 +47,14 @@ from marimo._utils.platform import is_pyodide, is_windows
LOGGER = loggers.marimo_logger()
-class Op(msgspec.Struct, tag_field="op"):
+class Notification(msgspec.Struct, tag_field="op"):
name: ClassVar[str]
-class CellOp(Op, tag="cell-op"):
+class CellNotification(Notification, tag="cell-op"):
"""Op to transition a cell.
- A CellOp's data has some optional fields:
+ A CellNotification's data has some optional fields:
output - a CellOutput
console - a CellOutput (console msg to append), or a list of
@@ -109,7 +109,7 @@ class HumanReadableStatus(msgspec.Struct):
message: Union[str, None] = None
-class FunctionCallResult(Op, tag="function-call-result"):
+class FunctionCallResultNotification(Notification, tag="function-call-result"):
"""Result of calling a function."""
name: ClassVar[str] = "function-call-result"
@@ -128,7 +128,7 @@ class FunctionCallResult(Op, tag="function-call-result"):
e,
)
return serialize_kernel_message(
- FunctionCallResult(
+ FunctionCallResultNotification(
function_call_id=self.function_call_id,
return_value=None,
status=HumanReadableStatus(
@@ -140,14 +140,16 @@ class FunctionCallResult(Op, tag="function-call-result"):
)
-class RemoveUIElements(Op, tag="remove-ui-elements"):
+class RemoveUIElementsNotification(Notification, tag="remove-ui-elements"):
"""Invalidate UI elements for a given cell."""
name: ClassVar[str] = "remove-ui-elements"
cell_id: CellId_t
-class SendUIElementMessage(Op, tag="send-ui-element-message"):
+class UIElementMessageNotification(
+ Notification, tag="send-ui-element-message"
+):
"""Send a message to a UI element."""
name: ClassVar[str] = "send-ui-element-message"
@@ -157,19 +159,19 @@ class SendUIElementMessage(Op, tag="send-ui-element-message"):
buffers: Optional[list[bytes]] = None
-class Interrupted(Op, tag="interrupted"):
+class InterruptedNotification(Notification, tag="interrupted"):
"""Written when the kernel is interrupted by the user."""
name: ClassVar[str] = "interrupted"
-class CompletedRun(Op, tag="completed-run"):
+class CompletedRunNotification(Notification, tag="completed-run"):
"""Written on run completion (of submitted cells and their descendants."""
name: ClassVar[str] = "completed-run"
-class KernelCapabilities(msgspec.Struct):
+class KernelCapabilitiesNotification(msgspec.Struct):
terminal: bool = False
pylsp: bool = False
ty: bool = False
@@ -183,7 +185,7 @@ class KernelCapabilities(msgspec.Struct):
self.ty = DependencyManager.ty.has()
-class KernelReady(Op, tag="kernel-ready"):
+class KernelReadyNotification(Notification, tag="kernel-ready"):
"""Kernel is ready for execution."""
name: ClassVar[str] = "kernel-ready"
@@ -205,10 +207,10 @@ class KernelReady(Op, tag="kernel-ready"):
# Whether the kernel is kiosk mode
kiosk: bool
# Kernel capabilities
- capabilities: KernelCapabilities
+ capabilities: KernelCapabilitiesNotification
-class CompletionResult(Op, tag="completion-result"):
+class CompletionResultNotification(Notification, tag="completion-result"):
"""Code completion result."""
name: ClassVar[str] = "completion-result"
@@ -217,7 +219,7 @@ class CompletionResult(Op, tag="completion-result"):
options: list[CompletionOption]
-class Alert(Op, tag="alert"):
+class AlertNotification(Notification, tag="alert"):
name: ClassVar[str] = "alert"
title: str
# description may be HTML
@@ -225,7 +227,9 @@ class Alert(Op, tag="alert"):
variant: Optional[Literal["danger"]] = None
-class MissingPackageAlert(Op, tag="missing-package-alert"):
+class MissingPackageAlertNotification(
+ Notification, tag="missing-package-alert"
+):
name: ClassVar[str] = "missing-package-alert"
packages: list[str]
isolated: bool
@@ -237,7 +241,9 @@ PackageStatusType = dict[
]
-class InstallingPackageAlert(Op, tag="installing-package-alert"):
+class InstallingPackageAlertNotification(
+ Notification, tag="installing-package-alert"
+):
name: ClassVar[str] = "installing-package-alert"
packages: PackageStatusType
# Optional fields for streaming logs per package
@@ -245,17 +251,17 @@ class InstallingPackageAlert(Op, tag="installing-package-alert"):
log_status: Optional[Literal["append", "start", "done"]] = None
-class Reconnected(Op, tag="reconnected"):
+class ReconnectedNotification(Notification, tag="reconnected"):
name: ClassVar[str] = "reconnected"
-class StartupLogs(Op, tag="startup-logs"):
+class StartupLogsNotification(Notification, tag="startup-logs"):
name: ClassVar[str] = "startup-logs"
content: str
status: Literal["append", "start", "done"]
-class Banner(Op, tag="banner"):
+class BannerNotification(Notification, tag="banner"):
name: ClassVar[str] = "banner"
title: str
# description may be HTML
@@ -264,11 +270,11 @@ class Banner(Op, tag="banner"):
action: Optional[Literal["restart"]] = None
-class Reload(Op, tag="reload"):
+class ReloadNotification(Notification, tag="reload"):
name: ClassVar[str] = "reload"
-class VariableDeclaration(msgspec.Struct):
+class VariableDeclarationNotification(msgspec.Struct):
name: str
declared_by: list[CellId_t]
used_by: list[CellId_t]
@@ -336,21 +342,21 @@ class VariableValue(BaseStruct):
return VariableValue._stringify_static(resolved)
-class Variables(Op, tag="variables"):
+class VariablesNotification(Notification, tag="variables"):
"""List of variable declarations."""
name: ClassVar[str] = "variables"
- variables: list[VariableDeclaration]
+ variables: list[VariableDeclarationNotification]
-class VariableValues(Op, tag="variable-values"):
+class VariableValuesNotification(Notification, tag="variable-values"):
"""List of variables and their types/values."""
name: ClassVar[str] = "variable-values"
variables: list[VariableValue]
-class Datasets(Op, tag="datasets"):
+class DatasetsNotification(Notification, tag="datasets"):
"""List of datasets."""
name: ClassVar[str] = "datasets"
@@ -366,7 +372,7 @@ class SQLMetadata(msgspec.Struct, tag="sql-metadata"):
schema: str
-class SQLTablePreview(Op, tag="sql-table-preview"):
+class SQLTablePreviewNotification(Notification, tag="sql-table-preview"):
"""Preview of a table in a SQL database."""
name: ClassVar[str] = "sql-table-preview"
@@ -376,7 +382,9 @@ class SQLTablePreview(Op, tag="sql-table-preview"):
error: Optional[str] = None
-class SQLTableListPreview(Op, tag="sql-table-list-preview"):
+class SQLTableListPreviewNotification(
+ Notification, tag="sql-table-list-preview"
+):
"""Preview of a list of tables in a schema."""
name: ClassVar[str] = "sql-table-list-preview"
@@ -394,8 +402,8 @@ class ColumnPreview(msgspec.Struct):
stats: Optional[ColumnStats] = None
-class DataColumnPreview(
- Op, ColumnPreview, kw_only=True, tag="data-column-preview"
+class DataColumnPreviewNotification(
+ Notification, ColumnPreview, kw_only=True, tag="data-column-preview"
):
"""Preview of a column in a dataset."""
@@ -404,12 +412,14 @@ class DataColumnPreview(
column_name: str
-class DataSourceConnections(Op, tag="data-source-connections"):
+class DataSourceConnectionsNotification(
+ Notification, tag="data-source-connections"
+):
name: ClassVar[str] = "data-source-connections"
connections: list[DataSourceConnection]
-class ValidateSQLResult(Op, tag="validate-sql-result"):
+class ValidateSQLResultNotification(Notification, tag="validate-sql-result"):
name: ClassVar[str] = "validate-sql-result"
request_id: RequestId
parse_result: Optional[SqlParseResult] = None
@@ -417,7 +427,7 @@ class ValidateSQLResult(Op, tag="validate-sql-result"):
error: Optional[str] = None
-class QueryParamsSet(Op, tag="query-params-set"):
+class QueryParamsSetNotification(Notification, tag="query-params-set"):
"""Set query parameters."""
name: ClassVar[str] = "query-params-set"
@@ -425,13 +435,13 @@ class QueryParamsSet(Op, tag="query-params-set"):
value: Union[str, list[str]]
-class QueryParamsAppend(Op, tag="query-params-append"):
+class QueryParamsAppendNotification(Notification, tag="query-params-append"):
name: ClassVar[str] = "query-params-append"
key: str
value: str
-class QueryParamsDelete(Op, tag="query-params-delete"):
+class QueryParamsDeleteNotification(Notification, tag="query-params-delete"):
name: ClassVar[str] = "query-params-delete"
key: str
# If value is None, delete all values for the key
@@ -439,17 +449,17 @@ class QueryParamsDelete(Op, tag="query-params-delete"):
value: Optional[str]
-class QueryParamsClear(Op, tag="query-params-clear"):
+class QueryParamsClearNotification(Notification, tag="query-params-clear"):
# Clear all query parameters
name: ClassVar[str] = "query-params-clear"
-class FocusCell(Op, tag="focus-cell"):
+class FocusCellNotification(Notification, tag="focus-cell"):
name: ClassVar[str] = "focus-cell"
cell_id: CellId_t
-class UpdateCellCodes(Op, tag="update-cell-codes"):
+class UpdateCellCodesNotification(Notification, tag="update-cell-codes"):
name: ClassVar[str] = "update-cell-codes"
cell_ids: list[CellId_t]
codes: list[str]
@@ -458,7 +468,7 @@ class UpdateCellCodes(Op, tag="update-cell-codes"):
code_is_stale: bool
-class SecretKeysResult(Op, tag="secret-keys-result"):
+class SecretKeysResultNotification(Notification, tag="secret-keys-result"):
"""Result of listing secret keys."""
request_id: RequestId
@@ -466,17 +476,17 @@ class SecretKeysResult(Op, tag="secret-keys-result"):
secrets: list[SecretKeysWithProvider]
-class CacheCleared(Op, tag="cache-cleared"):
+class CacheClearedNotification(Notification, tag="cache-cleared"):
"""Result of clearing cache."""
name: ClassVar[str] = "cache-cleared"
bytes_freed: int
-class CacheInfoFetched(Op, tag="cache-info-fetched"):
+class CacheInfoNotification(Notification, tag="cache-info"):
"""Cache statistics information."""
- name: ClassVar[str] = "cache-info-fetched"
+ name: ClassVar[str] = "cache-info"
hits: int
misses: int
time: float
@@ -484,7 +494,7 @@ class CacheInfoFetched(Op, tag="cache-info-fetched"):
disk_total: int
-class UpdateCellIdsRequest(Op, tag="update-cell-ids"):
+class UpdateCellIdsNotification(Notification, tag="update-cell-ids"):
"""
Update the cell ID ordering of the cells in the notebook.
@@ -496,48 +506,48 @@ class UpdateCellIdsRequest(Op, tag="update-cell-ids"):
cell_ids: list[CellId_t]
-MessageOperation = Union[
- # Cell operations
- CellOp,
- FunctionCallResult,
- SendUIElementMessage,
- RemoveUIElements,
+NotificationMessage = Union[
+ # Cell notifications
+ CellNotification,
+ FunctionCallResultNotification,
+ UIElementMessageNotification,
+ RemoveUIElementsNotification,
# Notebook operations
- Reload,
- Reconnected,
- Interrupted,
- CompletedRun,
- KernelReady,
+ ReloadNotification,
+ ReconnectedNotification,
+ InterruptedNotification,
+ CompletedRunNotification,
+ KernelReadyNotification,
# Editor operations
- CompletionResult,
+ CompletionResultNotification,
# Alerts
- Alert,
- Banner,
- MissingPackageAlert,
- InstallingPackageAlert,
- StartupLogs,
+ AlertNotification,
+ BannerNotification,
+ MissingPackageAlertNotification,
+ InstallingPackageAlertNotification,
+ StartupLogsNotification,
# Variables
- Variables,
- VariableValues,
+ VariablesNotification,
+ VariableValuesNotification,
# Query params
- QueryParamsSet,
- QueryParamsAppend,
- QueryParamsDelete,
- QueryParamsClear,
+ QueryParamsSetNotification,
+ QueryParamsAppendNotification,
+ QueryParamsDeleteNotification,
+ QueryParamsClearNotification,
# Datasets
- Datasets,
- DataColumnPreview,
- SQLTablePreview,
- SQLTableListPreview,
- DataSourceConnections,
- ValidateSQLResult,
+ DatasetsNotification,
+ DataColumnPreviewNotification,
+ SQLTablePreviewNotification,
+ SQLTableListPreviewNotification,
+ DataSourceConnectionsNotification,
+ ValidateSQLResultNotification,
# Secrets
- SecretKeysResult,
+ SecretKeysResultNotification,
# Cache
- CacheCleared,
- CacheInfoFetched,
+ CacheClearedNotification,
+ CacheInfoNotification,
# Kiosk specific
- FocusCell,
- UpdateCellCodes,
- UpdateCellIdsRequest,
+ FocusCellNotification,
+ UpdateCellCodesNotification,
+ UpdateCellIdsNotification,
]
diff --git a/marimo/_messaging/notification_utils.py b/marimo/_messaging/notification_utils.py
index fca1973a80..ffc16a684f 100644
--- a/marimo/_messaging/notification_utils.py
+++ b/marimo/_messaging/notification_utils.py
@@ -11,34 +11,36 @@ from typing import TYPE_CHECKING, Optional
from uuid import uuid4
from marimo import _loggers as loggers
-
-if TYPE_CHECKING:
- from collections.abc import Sequence
-
- import msgspec
-
-from marimo._ast.cell import RuntimeStateType
-from marimo._ast.toplevel import TopLevelHints, TopLevelStatus
-from marimo._messaging.cell_output import CellChannel, CellOutput
+from marimo._messaging.cell_output import CellOutput
from marimo._messaging.errors import (
- Error,
MarimoInternalError,
is_sensitive_error,
)
-from marimo._messaging.mimetypes import KnownMimeType
from marimo._messaging.serde import serialize_kernel_message
from marimo._messaging.streams import output_max_bytes
-from marimo._messaging.types import Stream
from marimo._runtime.context import get_context
from marimo._runtime.context.types import ContextNotInitializedError
from marimo._runtime.context.utils import get_mode
-from marimo._types.ids import CellId_t
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from marimo._ast.cell import RuntimeStateType
+ from marimo._ast.toplevel import TopLevelHints, TopLevelStatus
+ from marimo._messaging.cell_output import CellChannel
+ from marimo._messaging.errors import Error
+ from marimo._messaging.mimetypes import KnownMimeType
+ from marimo._messaging.notification import NotificationMessage
+ from marimo._messaging.types import Stream
+ from marimo._types.ids import CellId_t
LOGGER = loggers.marimo_logger()
-def broadcast_op(op: msgspec.Struct, stream: Optional[Stream] = None) -> None:
- """Broadcast an operation to the stream."""
+def broadcast_notification(
+ notification: NotificationMessage, stream: Optional[Stream] = None
+) -> None:
+ """Broadcast a notification to the stream."""
if stream is None:
try:
ctx = get_context()
@@ -49,11 +51,11 @@ def broadcast_op(op: msgspec.Struct, stream: Optional[Stream] = None) -> None:
stream = ctx.stream
try:
- stream.write(serialize_kernel_message(op))
+ stream.write(serialize_kernel_message(notification))
except Exception as e:
LOGGER.exception(
- "Error serializing op %s: %s",
- op.__class__.__name__,
+ "Error serializing notification %s: %s",
+ notification.__class__.__name__,
e,
)
return
@@ -114,7 +116,7 @@ class CellNotificationUtils:
stream: Stream | None = None,
) -> None:
# Import here to avoid circular dependency
- from marimo._messaging.ops import CellOp
+ from marimo._messaging.notification import CellNotification
mimetype, data = CellNotificationUtils.maybe_truncate_output(
mimetype, data
@@ -123,8 +125,8 @@ class CellNotificationUtils:
cell_id if cell_id is not None else get_context().stream.cell_id
)
assert cell_id is not None
- broadcast_op(
- CellOp(
+ broadcast_notification(
+ CellNotification(
cell_id=cell_id,
output=CellOutput(
channel=channel,
@@ -143,14 +145,14 @@ class CellNotificationUtils:
stream: Stream | None = None,
) -> None:
# Import here to avoid circular dependency
- from marimo._messaging.ops import CellOp
+ from marimo._messaging.notification import CellNotification
cell_id = (
cell_id if cell_id is not None else get_context().stream.cell_id
)
assert cell_id is not None
- broadcast_op(
- CellOp(
+ broadcast_notification(
+ CellNotification(
cell_id=cell_id,
output=CellOutput.empty(),
status=status,
@@ -168,7 +170,7 @@ class CellNotificationUtils:
stream: Stream | None = None,
) -> None:
# Import here to avoid circular dependency
- from marimo._messaging.ops import CellOp
+ from marimo._messaging.notification import CellNotification
mimetype, data = CellNotificationUtils.maybe_truncate_output(
mimetype, data
@@ -177,8 +179,8 @@ class CellNotificationUtils:
cell_id if cell_id is not None else get_context().stream.cell_id
)
assert cell_id is not None
- broadcast_op(
- CellOp(
+ broadcast_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput(
channel=channel,
@@ -197,14 +199,16 @@ class CellNotificationUtils:
stream: Stream | None = None,
) -> None:
# Import here to avoid circular dependency
- from marimo._messaging.ops import CellOp
+ from marimo._messaging.notification import CellNotification
if status != "running":
- broadcast_op(CellOp(cell_id=cell_id, status=status), stream)
+ broadcast_notification(
+ CellNotification(cell_id=cell_id, status=status), stream
+ )
else:
# Console gets cleared on "running"
- broadcast_op(
- CellOp(cell_id=cell_id, console=[], status=status),
+ broadcast_notification(
+ CellNotification(cell_id=cell_id, console=[], status=status),
stream=stream,
)
@@ -215,7 +219,7 @@ class CellNotificationUtils:
cell_id: CellId_t,
) -> None:
# Import here to avoid circular dependency
- from marimo._messaging.ops import CellOp
+ from marimo._messaging.notification import CellNotification
console: Optional[list[CellOutput]] = [] if clear_console else None
@@ -238,8 +242,8 @@ class CellNotificationUtils:
else:
safe_errors = list(data)
- broadcast_op(
- CellOp(
+ broadcast_notification(
+ CellNotification(
cell_id=cell_id,
output=CellOutput.errors(safe_errors),
console=console,
@@ -252,9 +256,11 @@ class CellNotificationUtils:
cell_id: CellId_t, stale: bool, stream: Stream | None = None
) -> None:
# Import here to avoid circular dependency
- from marimo._messaging.ops import CellOp
+ from marimo._messaging.notification import CellNotification
- broadcast_op(CellOp(cell_id=cell_id, stale_inputs=stale), stream)
+ broadcast_notification(
+ CellNotification(cell_id=cell_id, stale_inputs=stale), stream
+ )
@staticmethod
def broadcast_serialization(
@@ -263,9 +269,10 @@ class CellNotificationUtils:
stream: Stream | None = None,
) -> None:
# Import here to avoid circular dependency
- from marimo._messaging.ops import CellOp
+ from marimo._messaging.notification import CellNotification
status: Optional[TopLevelHints] = serialization.hint
- broadcast_op(
- CellOp(cell_id=cell_id, serialization=str(status)), stream
+ broadcast_notification(
+ CellNotification(cell_id=cell_id, serialization=str(status)),
+ stream,
)
diff --git a/marimo/_messaging/print_override.py b/marimo/_messaging/print_override.py
index fe2a8f28b0..3ebf54c346 100644
--- a/marimo/_messaging/print_override.py
+++ b/marimo/_messaging/print_override.py
@@ -6,8 +6,8 @@ import threading
from typing import Any
from marimo._messaging.cell_output import CellOutput
-from marimo._messaging.notification_utils import broadcast_op
-from marimo._messaging.ops import CellOp
+from marimo._messaging.notification import CellNotification
+from marimo._messaging.notification_utils import broadcast_notification
from marimo._runtime.context.types import (
ContextNotInitializedError,
get_context,
@@ -51,8 +51,8 @@ def print_override(*args: Any, **kwargs: Any) -> None:
end = kwargs.get("end", "\n")
msg = sep.join([str(arg) for arg in args]) + end
- broadcast_op(
- CellOp(
+ broadcast_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout(msg),
),
diff --git a/marimo/_messaging/serde.py b/marimo/_messaging/serde.py
index 1fa672f549..ce8f135a49 100644
--- a/marimo/_messaging/serde.py
+++ b/marimo/_messaging/serde.py
@@ -11,33 +11,33 @@ from marimo._messaging.msgspec_encoder import encode_json_bytes
from marimo._messaging.types import KernelMessage
if TYPE_CHECKING:
- from marimo._messaging.ops import MessageOperation
+ from marimo._messaging.notification import NotificationMessage
-def serialize_kernel_message(message: msgspec.Struct) -> KernelMessage:
+def serialize_kernel_message(message: NotificationMessage) -> KernelMessage:
"""
- Serialize a MessageOperation to a KernelMessage.
+ Serialize a NotificationMessage to a KernelMessage.
"""
return KernelMessage(encode_json_bytes(message))
-def deserialize_kernel_message(message: KernelMessage) -> MessageOperation:
+def deserialize_kernel_message(message: KernelMessage) -> NotificationMessage:
"""
- Deserialize a KernelMessage to a MessageOperation.
+ Deserialize a KernelMessage to a NotificationMessage.
"""
# Import here to avoid circular dependency
- from marimo._messaging.ops import MessageOperation
+ from marimo._messaging.notification import NotificationMessage
- return msgspec.json.decode(message, strict=True, type=MessageOperation) # type: ignore[no-any-return]
+ return msgspec.json.decode(message, strict=True, type=NotificationMessage) # type: ignore[no-any-return]
-class _OpName(msgspec.Struct):
+class _NotificationName(msgspec.Struct):
op: str
-def deserialize_kernel_operation_name(message: KernelMessage) -> str:
+def deserialize_kernel_notification_name(message: KernelMessage) -> str:
"""
- Deserialize a KernelMessage to a MessageOperation name.
+ Deserialize a KernelMessage to a NotificationMessage name.
"""
- # We use the _OpName type to deserialize the message because it is slimmer than MessageOperation
- return msgspec.json.decode(message, strict=True, type=_OpName).op
+ # We use the _NotificationName type to deserialize the message because it is slimmer than NotificationMessage
+ return msgspec.json.decode(message, strict=True, type=_NotificationName).op
diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.py
index 5ea65bc72b..dde09c18a3 100644
--- a/marimo/_messaging/streams.py
+++ b/marimo/_messaging/streams.py
@@ -123,14 +123,14 @@ class ThreadSafeStream(Stream):
self.pipe.send(data)
except OSError as e:
from marimo._messaging.serde import (
- deserialize_kernel_operation_name,
+ deserialize_kernel_notification_name,
)
# Most likely a BrokenPipeError, caused by the
# server process shutting down
LOGGER.debug(
"Error when writing (op: %s) to pipe: %s",
- deserialize_kernel_operation_name(data),
+ deserialize_kernel_notification_name(data),
e,
)
diff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.py
index bc91a89afa..6aa0bb843c 100644
--- a/marimo/_messaging/types.py
+++ b/marimo/_messaging/types.py
@@ -8,7 +8,7 @@ from typing import NewType, Optional
from marimo._messaging.mimetypes import ConsoleMimeType
from marimo._types.ids import CellId_t
-# A KernelMessage is a bytes object that contains a serialized MessageOperation.
+# A KernelMessage is a bytes object that contains a serialized NotificationMessage.
KernelMessage = NewType("KernelMessage", bytes)
diff --git a/marimo/_plugins/stateless/status/_progress.py b/marimo/_plugins/stateless/status/_progress.py
index 27f4e981db..84cc5c9930 100644
--- a/marimo/_plugins/stateless/status/_progress.py
+++ b/marimo/_plugins/stateless/status/_progress.py
@@ -16,8 +16,8 @@ from typing import (
import marimo._runtime.output._output as output
from marimo._messaging.mimetypes import KnownMimeType
-from marimo._messaging.notification_utils import broadcast_op
-from marimo._messaging.ops import Alert
+from marimo._messaging.notification import AlertNotification
+from marimo._messaging.notification_utils import broadcast_notification
from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import build_stateless_plugin
@@ -501,6 +501,6 @@ def toast(
kind (Literal["danger"], optional): Optional kind, use "danger" for error toasts.
Defaults to None.
"""
- broadcast_op(
- Alert(title=title, description=description, variant=kind),
+ broadcast_notification(
+ AlertNotification(title=title, description=description, variant=kind),
)
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index 4acbc22569..f4e388d9cb 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -433,11 +433,13 @@ class UIElement(Html, Generic[S, T]):
from the backend.
"""
- from marimo._messaging.notification_utils import broadcast_op
- from marimo._messaging.ops import SendUIElementMessage
+ from marimo._messaging.notification import (
+ UIElementMessageNotification,
+ )
+ from marimo._messaging.notification_utils import broadcast_notification
- broadcast_op(
- SendUIElementMessage(
+ broadcast_notification(
+ UIElementMessageNotification(
ui_element=self._id,
model_id=None,
message=message,
diff --git a/marimo/_plugins/ui/_impl/comm.py b/marimo/_plugins/ui/_impl/comm.py
index 8cdfcbf9be..7b48052620 100644
--- a/marimo/_plugins/ui/_impl/comm.py
+++ b/marimo/_plugins/ui/_impl/comm.py
@@ -218,14 +218,16 @@ class MarimoComm:
)
def flush(self) -> None:
- from marimo._messaging.notification_utils import broadcast_op
- from marimo._messaging.ops import SendUIElementMessage
+ from marimo._messaging.notification import (
+ UIElementMessageNotification,
+ )
+ from marimo._messaging.notification_utils import broadcast_notification
while self._publish_message_buffer:
item = self._publish_message_buffer.pop(0)
- broadcast_op(
- SendUIElementMessage(
+ broadcast_notification(
+ UIElementMessageNotification(
# ui_element_id can be None. In this case, we are creating a model
# not tied to a specific UI element
ui_element=self.ui_element_id,
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index b24b234efd..d2f9028926 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -21,7 +21,7 @@ from marimo import _loggers
from marimo._data.models import BinValue, ColumnStats, ValueCount
from marimo._data.preview_column import get_column_preview_dataset
from marimo._dependencies.dependencies import DependencyManager
-from marimo._messaging.ops import ColumnPreview
+from marimo._messaging.notification import ColumnPreview
from marimo._output.mime import MIME
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType
diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.py
index 522a3eecc9..206da9df32 100644
--- a/marimo/_pyodide/bootstrap.py
+++ b/marimo/_pyodide/bootstrap.py
@@ -5,9 +5,9 @@ import json
from typing import TYPE_CHECKING, Callable
from marimo._config.config import merge_config
-from marimo._messaging.ops import (
- KernelCapabilities,
- KernelReady,
+from marimo._messaging.notification import (
+ KernelCapabilitiesNotification,
+ KernelReadyNotification,
)
from marimo._messaging.serde import (
deserialize_kernel_message,
@@ -83,10 +83,10 @@ def create_session(
This function is called by the WebAssembly frontend.
"""
- def write_kernel_message(op: KernelMessage) -> None:
- data_json_str = op.decode("utf-8")
- op_name = deserialize_kernel_message(op).name
- text = f'{{"op": "{op_name}", "data": {data_json_str}}}'
+ def write_kernel_message(notification: KernelMessage) -> None:
+ data_json_str = notification.decode("utf-8")
+ name = deserialize_kernel_message(notification).name
+ text = f'{{"op": "{name}", "data": {data_json_str}}}'
message_callback(text)
# Lazy import to decrease startup time
@@ -112,7 +112,7 @@ def create_session(
# should be after this message is sent
write_kernel_message(
serialize_kernel_message(
- KernelReady(
+ KernelReadyNotification(
codes=tuple(app.cell_manager.codes()),
names=tuple(app.cell_manager.names()),
configs=tuple(app.cell_manager.configs()),
@@ -124,7 +124,7 @@ def create_session(
last_execution_time={},
app_config=app.config,
kiosk=False,
- capabilities=KernelCapabilities(),
+ capabilities=KernelCapabilitiesNotification(),
)
),
)
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index a4539f57a0..5b10761f94 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -134,7 +134,7 @@ class PyodideSession:
self.consumers: list[Callable[[KernelMessage], None]] = [
lambda msg: self.session_consumer(msg),
- lambda msg: self.session_view.add_raw_operation(msg),
+ lambda msg: self.session_view.add_raw_notification(msg),
]
def _on_message(self, msg: KernelMessage) -> None:
diff --git a/marimo/_pyodide/streams.py b/marimo/_pyodide/streams.py
index 17aa72ac7f..d135e8f21b 100644
--- a/marimo/_pyodide/streams.py
+++ b/marimo/_pyodide/streams.py
@@ -8,8 +8,8 @@ from typing import TYPE_CHECKING, Callable, Optional
from marimo import _loggers
from marimo._messaging.cell_output import CellOutput
from marimo._messaging.mimetypes import ConsoleMimeType
-from marimo._messaging.notification_utils import broadcast_op
-from marimo._messaging.ops import CellOp
+from marimo._messaging.notification import CellNotification
+from marimo._messaging.notification_utils import broadcast_notification
from marimo._messaging.streams import std_stream_max_bytes
from marimo._messaging.types import (
KernelMessage,
@@ -74,8 +74,8 @@ class PyodideStdout(Stdout):
"Warning: marimo truncated a very large console output.\n"
)
data = data[: int(max_bytes)] + " ... "
- broadcast_op(
- CellOp(
+ broadcast_notification(
+ CellNotification(
cell_id=self.stream.cell_id,
console=CellOutput.stdout(data, mimetype),
),
@@ -122,8 +122,8 @@ class PyodideStderr(Stderr):
+ " ... "
)
- broadcast_op(
- CellOp(
+ broadcast_notification(
+ CellNotification(
cell_id=self.stream.cell_id,
console=CellOutput.stderr(data, mimetype),
),
@@ -164,8 +164,8 @@ class PyodideStdin(Stdin):
+ " ... "
)
- broadcast_op(
- CellOp(
+ broadcast_notification(
+ CellNotification(
cell_id=self.stream.cell_id,
console=CellOutput.stdin(prompt),
),
diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.py
index bde24641f6..2ca4daaea7 100644
--- a/marimo/_runtime/app/kernel_runner.py
+++ b/marimo/_runtime/app/kernel_runner.py
@@ -21,7 +21,7 @@ from marimo._types.ids import CellId_t
if TYPE_CHECKING:
from marimo._ast.app import InternalApp
- from marimo._messaging.ops import HumanReadableStatus
+ from marimo._messaging.notification import HumanReadableStatus
from marimo._plugins.core.web_component import JSONType
diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.py
index 203293d0a3..e00bb3cd94 100644
--- a/marimo/_runtime/complete.py
+++ b/marimo/_runtime/complete.py
@@ -16,8 +16,8 @@ import jedi.api # type: ignore # noqa: F401
from marimo import _loggers as loggers
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.completion_option import CompletionOption
-from marimo._messaging.notification_utils import broadcast_op
-from marimo._messaging.ops import CompletionResult
+from marimo._messaging.notification import CompletionResultNotification
+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
@@ -299,8 +299,8 @@ def _write_completion_result(
prefix_length: int,
options: list[CompletionOption],
) -> None:
- broadcast_op(
- CompletionResult(
+ broadcast_notification(
+ CompletionResultNotification(
completion_id=completion_id,
prefix_length=prefix_length,
options=options,
diff --git a/marimo/_runtime/handlers.py b/marimo/_runtime/handlers.py
index 2997348f03..aad3193cdb 100644
--- a/marimo/_runtime/handlers.py
+++ b/marimo/_runtime/handlers.py
@@ -6,8 +6,8 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable
from marimo import _loggers
-from marimo._messaging.notification_utils import broadcast_op
-from marimo._messaging.ops import Interrupted
+from marimo._messaging.notification import InterruptedNotification
+from marimo._messaging.notification_utils import broadcast_notification
from marimo._runtime.context import get_context
from marimo._runtime.context.kernel_context import KernelRuntimeContext
from marimo._runtime.control_flow import MarimoInterrupt
@@ -31,7 +31,7 @@ def construct_interrupt_handler(
# it won't be interrupted, which isn't right ... but the
# probability of that happening is low.
if context.execution_context is not None:
- broadcast_op(Interrupted())
+ broadcast_notification(InterruptedNotification())
# DuckDB connections are sometimes left in an inconsistent
# state when interrupted by a SIGINT. Manually interrupting
# duckdb through its own API seems to be safer.
diff --git a/marimo/_runtime/packages/package_manager.py b/marimo/_runtime/packages/package_manager.py
index f5c7e36e23..a61d5d2e11 100644
--- a/marimo/_runtime/packages/package_manager.py
+++ b/marimo/_runtime/packages/package_manager.py
@@ -10,8 +10,8 @@ import msgspec
from marimo import _loggers
from marimo._dependencies.dependencies import DependencyManager
-from marimo._messaging.notification_utils import broadcast_op
-from marimo._messaging.ops import Alert
+from marimo._messaging.notification import AlertNotification
+from marimo._messaging.notification_utils import broadcast_notification
from marimo._runtime.packages.utils import append_version
if TYPE_CHECKING:
@@ -221,8 +221,8 @@ class PackageManager(abc.ABC):
def alert_not_installed(self) -> None:
"""Alert the user that the package manager is not installed."""
- broadcast_op(
- Alert(
+ broadcast_notification(
+ AlertNotification(
title="Package manager not installed",
description=(f"{self.name} is not available on your machine."),
variant="danger",
diff --git a/marimo/_runtime/params.py b/marimo/_runtime/params.py
index 4df7353090..ad22aac09c 100644
--- a/marimo/_runtime/params.py
+++ b/marimo/_runtime/params.py
@@ -10,13 +10,13 @@ from typing import (
)
from marimo._messaging.mimetypes import KnownMimeType
-from marimo._messaging.notification_utils import broadcast_op
-from marimo._messaging.ops import (
- QueryParamsAppend,
- QueryParamsClear,
- QueryParamsDelete,
- QueryParamsSet,
+from marimo._messaging.notification import (
+ QueryParamsAppendNotification,
+ QueryParamsClearNotification,
+ QueryParamsDeleteNotification,
+ QueryParamsSetNotification,
)
+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 (
@@ -105,12 +105,16 @@ class QueryParams(State[SerializedQueryParams]):
return
# We always overwrite the value
self._params[key] = value
- broadcast_op(QueryParamsSet(key, value), self._stream)
+ broadcast_notification(
+ QueryParamsSetNotification(key, value), self._stream
+ )
self._set_value(self._params)
def __delitem__(self, key: str) -> None:
del self._params[key]
- broadcast_op(QueryParamsDelete(key, None), self._stream)
+ broadcast_notification(
+ QueryParamsDeleteNotification(key, None), self._stream
+ )
self._set_value(self._params)
def set(self, key: str, value: Union[str, list[str]]) -> None:
@@ -126,7 +130,9 @@ class QueryParams(State[SerializedQueryParams]):
"""
if key not in self._params:
self._params[key] = value
- broadcast_op(QueryParamsAppend(key, value), self._stream)
+ broadcast_notification(
+ QueryParamsAppendNotification(key, value), self._stream
+ )
self._set_value(self._params)
return
@@ -136,7 +142,9 @@ class QueryParams(State[SerializedQueryParams]):
else:
self._params[key] = [current_value, value]
- broadcast_op(QueryParamsAppend(key, value), self._stream)
+ broadcast_notification(
+ QueryParamsAppendNotification(key, value), self._stream
+ )
self._set_value(self._params)
def remove(self, key: str, value: Optional[str] = None) -> None:
@@ -151,7 +159,9 @@ class QueryParams(State[SerializedQueryParams]):
# If value is None, remove the key
if value is None:
del self._params[key]
- broadcast_op(QueryParamsDelete(key, value), self._stream)
+ broadcast_notification(
+ QueryParamsDeleteNotification(key, value), self._stream
+ )
self._set_value(self._params)
return
@@ -161,7 +171,9 @@ class QueryParams(State[SerializedQueryParams]):
elif current_value == value:
del self._params[key]
- broadcast_op(QueryParamsDelete(key, value), self._stream)
+ broadcast_notification(
+ QueryParamsDeleteNotification(key, value), self._stream
+ )
self._set_value(self._params)
def _mime_(self) -> tuple[KnownMimeType, str]:
@@ -172,7 +184,7 @@ class QueryParams(State[SerializedQueryParams]):
def clear(self) -> None:
"""Clear all query params."""
self._params.clear()
- broadcast_op(QueryParamsClear(), self._stream)
+ broadcast_notification(QueryParamsClearNotification(), self._stream)
self._set_value(self._params)
def to_dict(self) -> dict[str, Union[str, list[str]]]:
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.py
index 20ae1436e2..66c393d180 100644
--- a/marimo/_runtime/requests.py
+++ b/marimo/_runtime/requests.py
@@ -304,6 +304,10 @@ class DeleteCellRequest(msgspec.Struct, rename="camel"):
cell_id: CellId_t
+class UpdateCellIdsRequest(msgspec.Struct, rename="camel"):
+ cell_ids: list[CellId_t]
+
+
class StopRequest(msgspec.Struct, rename="camel"):
pass
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index 2b2e691ff3..388f9c6bf9 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -19,15 +19,15 @@ from marimo._messaging.errors import (
MarimoSQLError,
MarimoStrictExecutionError,
)
+from marimo._messaging.notification import (
+ DatasetsNotification,
+ DataSourceConnectionsNotification,
+ VariableValue,
+ VariableValuesNotification,
+)
from marimo._messaging.notification_utils import (
CellNotificationUtils,
- broadcast_op,
-)
-from marimo._messaging.ops import (
- Datasets,
- DataSourceConnections,
- VariableValue,
- VariableValues,
+ broadcast_notification,
)
from marimo._messaging.tracebacks import write_traceback
from marimo._output import formatting
@@ -132,7 +132,7 @@ def _broadcast_variables(
for variable in cell.defs
]
if values:
- broadcast_op(VariableValues(variables=values))
+ broadcast_notification(VariableValuesNotification(variables=values))
@kernel_tracer.start_as_current_span("broadcast_datasets")
@@ -155,7 +155,7 @@ def _broadcast_datasets(
)
if tables:
LOGGER.debug("Broadcasting data tables")
- broadcast_op(Datasets(tables=tables))
+ broadcast_notification(DatasetsNotification(tables=tables))
@kernel_tracer.start_as_current_span("broadcast_data_source_connection")
@@ -181,8 +181,8 @@ def _broadcast_data_source_connection(
return
LOGGER.debug("Broadcasting data source connections")
- broadcast_op(
- DataSourceConnections(
+ broadcast_notification(
+ DataSourceConnectionsNotification(
connections=[
engine_to_data_source_connection(variable, engine)
for variable, engine in engines
@@ -217,8 +217,8 @@ def _broadcast_duckdb_datasource(
return
LOGGER.debug("Broadcasting internal duckdb datasource")
- broadcast_op(
- DataSourceConnections(
+ broadcast_notification(
+ DataSourceConnectionsNotification(
connections=[
engine_to_data_source_connection(
INTERNAL_DUCKDB_ENGINE, DuckDBEngine()
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 27be9d188b..07403b43b2 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -53,31 +53,31 @@ from marimo._messaging.errors import (
MarimoSyntaxError,
UnknownError,
)
-from marimo._messaging.notification_utils import (
- CellNotificationUtils,
- broadcast_op,
-)
-from marimo._messaging.ops import (
- CacheCleared,
- CacheInfoFetched,
- CompletedRun,
- DataColumnPreview,
- DataSourceConnections,
- FunctionCallResult,
+from marimo._messaging.notification import (
+ CacheClearedNotification,
+ CacheInfoNotification,
+ CompletedRunNotification,
+ DataColumnPreviewNotification,
+ DataSourceConnectionsNotification,
+ FunctionCallResultNotification,
HumanReadableStatus,
- InstallingPackageAlert,
- MissingPackageAlert,
+ InstallingPackageAlertNotification,
+ MissingPackageAlertNotification,
PackageStatusType,
- RemoveUIElements,
- SecretKeysResult,
+ RemoveUIElementsNotification,
+ SecretKeysResultNotification,
SQLMetadata,
- SQLTableListPreview,
- SQLTablePreview,
- ValidateSQLResult,
- VariableDeclaration,
- Variables,
+ SQLTableListPreviewNotification,
+ SQLTablePreviewNotification,
+ ValidateSQLResultNotification,
+ VariableDeclarationNotification,
+ VariablesNotification,
VariableValue,
- VariableValues,
+ VariableValuesNotification,
+)
+from marimo._messaging.notification_utils import (
+ CellNotificationUtils,
+ broadcast_notification,
)
from marimo._messaging.print_override import print_override
from marimo._messaging.streams import (
@@ -1104,7 +1104,7 @@ class Kernel:
get_context().cell_lifecycle_registry.dispose(
descendent, deletion=deletion
)
- broadcast_op(RemoveUIElements(cell_id=cell_id))
+ broadcast_notification(RemoveUIElementsNotification(cell_id=cell_id))
def _deactivate_cell(self, cell_id: CellId_t) -> set[CellId_t]:
"""Deactivate: remove from graph, invalidate state, but keep metadata
@@ -1328,10 +1328,10 @@ class Kernel:
# Always broadcast Variables message after graph mutation to ensure
# frontend has the latest dependency information
- broadcast_op(
- Variables(
+ broadcast_notification(
+ VariablesNotification(
variables=[
- VariableDeclaration(
+ VariableDeclarationNotification(
name=variable,
declared_by=list(declared_by),
used_by=list(
@@ -1942,8 +1942,9 @@ class Kernel:
continue
if variable_values:
- broadcast_op(
- VariableValues(variables=variable_values), self.stream
+ broadcast_notification(
+ VariableValuesNotification(variables=variable_values),
+ self.stream,
)
if self.reactive_execution_mode == "autorun":
@@ -2223,14 +2224,14 @@ class Kernel:
async def handle_instantiate(request: CreationRequest) -> None:
with http_request_context(request.request):
await self.instantiate(request)
- broadcast_op(CompletedRun())
+ broadcast_notification(CompletedRunNotification())
async def handle_execute_multiple(
request: ExecuteMultipleRequest,
) -> None:
with http_request_context(request.request):
await self.run(request.execution_requests)
- broadcast_op(CompletedRun())
+ broadcast_notification(CompletedRunNotification())
async def handle_sync_graph(
request: SyncGraphRequest,
@@ -2239,26 +2240,26 @@ class Kernel:
await self.sync_graph(
request.cells, request.run_ids, request.delete_ids
)
- broadcast_op(CompletedRun())
+ broadcast_notification(CompletedRunNotification())
async def handle_execute_scratchpad(
request: ExecuteScratchpadRequest,
) -> None:
with http_request_context(request.request):
await self.run_scratchpad(request.code)
- broadcast_op(CompletedRun())
+ broadcast_notification(CompletedRunNotification())
async def handle_execute_stale(request: ExecuteStaleRequest) -> None:
with http_request_context(request.request):
await self.run_stale_cells()
- broadcast_op(CompletedRun())
+ broadcast_notification(CompletedRunNotification())
async def handle_set_ui_element_value(
request: SetUIElementValueRequest,
) -> None:
with http_request_context(request.request):
await self.set_ui_element_value(request)
- broadcast_op(CompletedRun())
+ broadcast_notification(CompletedRunNotification())
async def handle_pdb_request(request: PdbRequest) -> None:
await self.pdb_request(request.cell_id)
@@ -2278,8 +2279,8 @@ class Kernel:
async def handle_function_call(request: FunctionCallRequest) -> None:
status, ret, _ = await self.function_call_request(request)
LOGGER.debug("Function returned with status %s", status)
- broadcast_op(
- FunctionCallResult(
+ broadcast_notification(
+ FunctionCallResultNotification(
function_call_id=request.function_call_id,
return_value=ret,
status=status,
@@ -2295,7 +2296,7 @@ class Kernel:
request: InstallMissingPackagesRequest,
) -> None:
await self.packages_callbacks.install_missing_packages(request)
- broadcast_op(CompletedRun())
+ broadcast_notification(CompletedRunNotification())
async def handle_stop(request: StopRequest) -> None:
del request
@@ -2446,8 +2447,8 @@ class DatasetCallbacks:
dataset, request
)
elif source_type == "connection":
- broadcast_op(
- DataColumnPreview(
+ broadcast_notification(
+ DataColumnPreviewNotification(
error="Column preview for connection data sources is not supported",
column_name=column_name,
table_name=table_name,
@@ -2455,8 +2456,8 @@ class DatasetCallbacks:
)
return
elif source_type == "catalog":
- broadcast_op(
- DataColumnPreview(
+ broadcast_notification(
+ DataColumnPreviewNotification(
error="Column preview for catalog data sources is not supported",
column_name=column_name,
table_name=table_name,
@@ -2467,15 +2468,15 @@ class DatasetCallbacks:
assert_never(source_type)
if column_preview is None:
- broadcast_op(
- DataColumnPreview(
+ broadcast_notification(
+ DataColumnPreviewNotification(
error=f"Column {column_name} not found",
column_name=column_name,
table_name=table_name,
),
)
else:
- broadcast_op(column_preview)
+ broadcast_notification(column_preview)
except Exception as e:
LOGGER.warning(
"Failed to get preview for column %s in table %s",
@@ -2483,8 +2484,8 @@ class DatasetCallbacks:
table_name,
exc_info=e,
)
- broadcast_op(
- DataColumnPreview(
+ broadcast_notification(
+ DataColumnPreviewNotification(
error=str(e),
column_name=column_name,
table_name=table_name,
@@ -2515,8 +2516,8 @@ class DatasetCallbacks:
engine, error = self.get_engine_catalog(variable_name)
if error is not None or engine is None:
- broadcast_op(
- SQLTablePreview(
+ broadcast_notification(
+ SQLTablePreviewNotification(
request_id=request.request_id,
table=None,
error=error,
@@ -2532,8 +2533,8 @@ class DatasetCallbacks:
database_name=database_name,
)
- broadcast_op(
- SQLTablePreview(
+ broadcast_notification(
+ SQLTablePreviewNotification(
request_id=request.request_id,
table=table,
metadata=sql_metadata,
@@ -2545,8 +2546,8 @@ class DatasetCallbacks:
table_name,
schema_name,
)
- broadcast_op(
- SQLTablePreview(
+ broadcast_notification(
+ SQLTablePreviewNotification(
request_id=request.request_id,
table=None,
error="Failed to get table details: " + str(e),
@@ -2577,8 +2578,8 @@ class DatasetCallbacks:
engine, error = self.get_engine_catalog(variable_name)
if error is not None or engine is None:
- broadcast_op(
- SQLTableListPreview(
+ broadcast_notification(
+ SQLTableListPreviewNotification(
request_id=request.request_id,
tables=[],
error=error,
@@ -2593,8 +2594,8 @@ class DatasetCallbacks:
database=database_name,
include_table_details=False,
)
- broadcast_op(
- SQLTableListPreview(
+ broadcast_notification(
+ SQLTableListPreviewNotification(
request_id=request.request_id,
tables=table_list,
metadata=sql_metadata,
@@ -2604,8 +2605,8 @@ class DatasetCallbacks:
LOGGER.exception(
"Failed to get table list for schema %s", schema_name
)
- broadcast_op(
- SQLTableListPreview(
+ broadcast_notification(
+ SQLTableListPreviewNotification(
request_id=request.request_id,
tables=[],
error="Failed to get table list: " + str(e),
@@ -2631,8 +2632,8 @@ class DatasetCallbacks:
LOGGER.debug(
"Broadcasting datasource connection for %s engine", variable_name
)
- broadcast_op(
- DataSourceConnections(
+ broadcast_notification(
+ DataSourceConnectionsNotification(
connections=[data_source_connection],
),
)
@@ -2653,8 +2654,8 @@ class SqlCallbacks:
if request.only_parse:
if request.dialect is None:
- broadcast_op(
- ValidateSQLResult(
+ broadcast_notification(
+ ValidateSQLResultNotification(
request_id=request_id,
error="Dialect is required when only parsing",
),
@@ -2663,8 +2664,8 @@ class SqlCallbacks:
# Just parse the query (no DB connection required)
parse_result, error = parse_sql(request.query, request.dialect)
- broadcast_op(
- ValidateSQLResult(
+ broadcast_notification(
+ ValidateSQLResultNotification(
request_id=request_id,
parse_result=parse_result,
error=error,
@@ -2678,8 +2679,8 @@ class SqlCallbacks:
# For failed connections, we should not raise an error
if request.engine is None:
- broadcast_op(
- ValidateSQLResult(
+ broadcast_notification(
+ ValidateSQLResultNotification(
request_id=request_id,
error="Engine is required for validating catalog",
),
@@ -2695,8 +2696,8 @@ class SqlCallbacks:
engine, error = self._kernel.get_sql_connection(variable_name)
if error is not None or engine is None:
- broadcast_op(
- ValidateSQLResult(
+ broadcast_notification(
+ ValidateSQLResultNotification(
request_id=request_id,
error="Failed to get engine " + variable_name,
),
@@ -2710,8 +2711,8 @@ class SqlCallbacks:
LOGGER.debug("Parse error: %s", parse_error)
if not isinstance(engine, QueryEngine):
- broadcast_op(
- ValidateSQLResult(
+ broadcast_notification(
+ ValidateSQLResultNotification(
request_id=request_id,
error=f"Engine {variable_name} does not support catalog validation.",
parse_result=parse_result,
@@ -2724,8 +2725,8 @@ class SqlCallbacks:
success=True if error_message is None else False,
error_message=error_message,
)
- broadcast_op(
- ValidateSQLResult(
+ broadcast_notification(
+ ValidateSQLResultNotification(
request_id=request_id,
validate_result=validate_result,
parse_result=parse_result,
@@ -2741,8 +2742,8 @@ class SqlCallbacks:
await self._validate_sql_query(request)
except Exception as e:
LOGGER.exception("Failed to validate SQL query")
- broadcast_op(
- ValidateSQLResult(
+ broadcast_notification(
+ ValidateSQLResultNotification(
request_id=request.request_id,
error="Failed to validate SQL query: " + str(e),
),
@@ -2757,8 +2758,10 @@ class SecretsCallbacks:
secrets = get_secret_keys(
self._kernel.user_config, self._kernel._original_environ
)
- broadcast_op(
- SecretKeysResult(request_id=request.request_id, secrets=secrets),
+ broadcast_notification(
+ SecretKeysResultNotification(
+ request_id=request.request_id, secrets=secrets
+ ),
)
async def refresh_secrets(self, request: RefreshSecretsRequest) -> None:
@@ -2798,8 +2801,8 @@ class PackagesCallbacks:
)
)
# Deleting a cell can make the set of missing packages smaller
- broadcast_op(
- MissingPackageAlert(
+ broadcast_notification(
+ MissingPackageAlertNotification(
packages=packages,
isolated=is_python_isolated(),
),
@@ -2877,8 +2880,8 @@ class PackagesCallbacks:
)
)
else:
- broadcast_op(
- MissingPackageAlert(
+ broadcast_notification(
+ MissingPackageAlertNotification(
packages=packages,
isolated=is_python_isolated(),
),
@@ -2927,12 +2930,14 @@ class PackagesCallbacks:
package_statuses: PackageStatusType = {
pkg: "queued" for pkg in missing_packages
}
- broadcast_op(InstallingPackageAlert(packages=package_statuses))
+ broadcast_notification(
+ InstallingPackageAlertNotification(packages=package_statuses)
+ )
def create_log_callback(pkg: str) -> LogCallback:
def log_callback(log_line: str) -> None:
- broadcast_op(
- InstallingPackageAlert(
+ broadcast_notification(
+ InstallingPackageAlertNotification(
packages=package_statuses,
logs={pkg: log_line},
log_status="append",
@@ -2947,11 +2952,13 @@ class PackagesCallbacks:
# Skip the installation.
continue
package_statuses[pkg] = "installing"
- broadcast_op(InstallingPackageAlert(packages=package_statuses))
+ broadcast_notification(
+ InstallingPackageAlertNotification(packages=package_statuses)
+ )
# Send initial "start" log
- broadcast_op(
- InstallingPackageAlert(
+ broadcast_notification(
+ InstallingPackageAlertNotification(
packages=package_statuses,
logs={pkg: f"Installing {pkg}...\n"},
log_status="start",
@@ -2964,8 +2971,8 @@ class PackagesCallbacks:
):
package_statuses[pkg] = "installed"
# Send final "done" log
- broadcast_op(
- InstallingPackageAlert(
+ broadcast_notification(
+ InstallingPackageAlertNotification(
packages=package_statuses,
logs={pkg: f"Successfully installed {pkg}\n"},
log_status="done",
@@ -2976,8 +2983,8 @@ class PackagesCallbacks:
mod = self.package_manager.package_to_module(pkg)
self._kernel.module_registry.excluded_modules.add(mod)
# Send final "done" log with error
- broadcast_op(
- InstallingPackageAlert(
+ broadcast_notification(
+ InstallingPackageAlertNotification(
packages=package_statuses,
logs={pkg: f"Failed to install {pkg}\n"},
log_status="done",
@@ -3067,7 +3074,7 @@ class CacheCallbacks:
if isinstance(obj.loader, BasePersistenceLoader):
obj.loader.clear()
- broadcast_op(CacheCleared(bytes_freed=saved))
+ broadcast_notification(CacheClearedNotification(bytes_freed=saved))
async def get_cache_info(self, request: GetCacheInfoRequest) -> None:
del request
@@ -3087,8 +3094,8 @@ class CacheCallbacks:
total_misses += misses
total_time += time
# d2f, dt = obj.loader.disk_usage()
- broadcast_op(
- CacheInfoFetched(
+ broadcast_notification(
+ CacheInfoNotification(
hits=total_hits,
misses=total_misses,
time=total_time,
diff --git a/marimo/_schemas/README.md b/marimo/_schemas/README.md
index 9c0420ab6a..f2bb15933e 100644
--- a/marimo/_schemas/README.md
+++ b/marimo/_schemas/README.md
@@ -6,7 +6,7 @@ This directory contains the schemas for the notebook, session, and kernel messag
- **notebook.py**: Schema for the notebook file format
- **session.py**: Schema for the notebook session (outputs, console, etc.)
-- **notifications** (from `marimo/_messaging/ops.py`): Schema for kernel notifications sent to the client
+- **notifications** (from `marimo/_messaging/notification.py`): Schema for kernel notifications sent to the client
## How to update the schemas
diff --git a/marimo/_schemas/generated/notifications.yaml b/marimo/_schemas/generated/notifications.yaml
index 4a0fc62360..b95eef3e6c 100644
--- a/marimo/_schemas/generated/notifications.yaml
+++ b/marimo/_schemas/generated/notifications.yaml
@@ -1,7 +1,7 @@
# This file is generated by scripts/generate_schemas.py
components:
schemas:
- Alert:
+ AlertNotification:
properties:
description:
type: string
@@ -20,9 +20,9 @@ components:
- op
- title
- description
- title: Alert
+ title: AlertNotification
type: object
- Banner:
+ BannerNotification:
properties:
action:
anyOf:
@@ -47,9 +47,9 @@ components:
- op
- title
- description
- title: Banner
+ title: BannerNotification
type: object
- CacheCleared:
+ CacheClearedNotification:
description: Result of clearing cache.
properties:
bytes_freed:
@@ -60,9 +60,9 @@ components:
required:
- op
- bytes_freed
- title: CacheCleared
+ title: CacheClearedNotification
type: object
- CacheInfoFetched:
+ CacheInfoNotification:
description: Cache statistics information.
properties:
disk_to_free:
@@ -75,7 +75,7 @@ components:
type: integer
op:
enum:
- - cache-info-fetched
+ - cache-info
time:
type: number
required:
@@ -85,7 +85,7 @@ components:
- time
- disk_to_free
- disk_total
- title: CacheInfoFetched
+ title: CacheInfoNotification
type: object
CellChannel:
description: The channel of a cell's output.
@@ -117,15 +117,15 @@ components:
required: []
title: CellConfig
type: object
- CellOp:
- description: "Op to transition a cell.\n\nA CellOp's data has some optional\
- \ fields:\n\noutput - a CellOutput\nconsole - a CellOutput (console\
- \ msg to append), or a list of\n CellOutputs\nstatus \
- \ - execution status\nstale_inputs - whether the cell has stale inputs (variables,\
- \ modules, ...)\nrun_id - the run associated with this cell.\nserialization\
- \ - the serialization status of the cell\n\nOmitting a field means that its\
- \ value should be unchanged!\n\nAnd one required field:\n\ncell_id - the cell\
- \ id"
+ 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"
properties:
cell_id:
type: string
@@ -174,7 +174,7 @@ components:
required:
- op
- cell_id
- title: CellOp
+ title: CellNotification
type: object
CellOutput:
properties:
@@ -323,7 +323,7 @@ components:
required: []
title: ColumnStats
type: object
- CompletedRun:
+ CompletedRunNotification:
description: Written on run completion (of submitted cells and their descendants.
properties:
op:
@@ -331,7 +331,7 @@ components:
- completed-run
required:
- op
- title: CompletedRun
+ title: CompletedRunNotification
type: object
CompletionOption:
properties:
@@ -349,7 +349,7 @@ components:
- completion_info
title: CompletionOption
type: object
- CompletionResult:
+ CompletionResultNotification:
description: Code completion result.
properties:
completion_id:
@@ -368,7 +368,7 @@ components:
- completion_id
- prefix_length
- options
- title: CompletionResult
+ title: CompletionResultNotification
type: object
CycleError:
properties:
@@ -393,7 +393,7 @@ components:
- edges_with_vars
title: CycleError
type: object
- DataColumnPreview:
+ DataColumnPreviewNotification:
description: Preview of a column in a dataset.
properties:
chart_code:
@@ -434,7 +434,7 @@ components:
- op
- table_name
- column_name
- title: DataColumnPreview
+ title: DataColumnPreviewNotification
type: object
DataSourceConnection:
description: "Represents a data source connection.\n\nAttributes:\n source\
@@ -477,7 +477,7 @@ components:
- databases
title: DataSourceConnection
type: object
- DataSourceConnections:
+ DataSourceConnectionsNotification:
properties:
connections:
items:
@@ -489,7 +489,7 @@ components:
required:
- op
- connections
- title: DataSourceConnections
+ title: DataSourceConnectionsNotification
type: object
DataTable:
description: "Represents a data table.\n\nAttributes:\n source_type (DataTableSource):\
@@ -619,7 +619,7 @@ components:
- schemas
title: Database
type: object
- Datasets:
+ DatasetsNotification:
description: List of datasets.
properties:
clear_channel:
@@ -641,9 +641,9 @@ components:
required:
- op
- tables
- title: Datasets
+ title: DatasetsNotification
type: object
- FocusCell:
+ FocusCellNotification:
properties:
cell_id:
type: string
@@ -653,9 +653,9 @@ components:
required:
- op
- cell_id
- title: FocusCell
+ title: FocusCellNotification
type: object
- FunctionCallResult:
+ FunctionCallResultNotification:
description: Result of calling a function.
properties:
function_call_id:
@@ -671,7 +671,7 @@ components:
- function_call_id
- return_value
- status
- title: FunctionCallResult
+ title: FunctionCallResultNotification
type: object
HumanReadableStatus:
description: Human-readable status.
@@ -711,7 +711,7 @@ components:
- msg
title: ImportStarError
type: object
- InstallingPackageAlert:
+ InstallingPackageAlertNotification:
properties:
log_status:
anyOf:
@@ -742,9 +742,9 @@ components:
required:
- op
- packages
- title: InstallingPackageAlert
+ title: InstallingPackageAlertNotification
type: object
- Interrupted:
+ InterruptedNotification:
description: Written when the kernel is interrupted by the user.
properties:
op:
@@ -752,9 +752,9 @@ components:
- interrupted
required:
- op
- title: Interrupted
+ title: InterruptedNotification
type: object
- KernelCapabilities:
+ KernelCapabilitiesNotification:
properties:
basedpyright:
default: false
@@ -769,15 +769,15 @@ components:
default: false
type: boolean
required: []
- title: KernelCapabilities
+ title: KernelCapabilitiesNotification
type: object
- KernelReady:
+ KernelReadyNotification:
description: Kernel is ready for execution.
properties:
app_config:
$ref: '#/components/schemas/_AppConfig'
capabilities:
- $ref: '#/components/schemas/KernelCapabilities'
+ $ref: '#/components/schemas/KernelCapabilitiesNotification'
cell_ids:
items:
type: string
@@ -835,7 +835,7 @@ components:
- app_config
- kiosk
- capabilities
- title: KernelReady
+ title: KernelReadyNotification
type: object
LayoutConfig:
properties:
@@ -1009,7 +1009,7 @@ components:
- msg
title: MarimoSyntaxError
type: object
- MissingPackageAlert:
+ MissingPackageAlertNotification:
properties:
isolated:
type: boolean
@@ -1024,7 +1024,7 @@ components:
- op
- packages
- isolated
- title: MissingPackageAlert
+ title: MissingPackageAlertNotification
type: object
MultipleDefinitionError:
properties:
@@ -1043,7 +1043,7 @@ components:
- cells
title: MultipleDefinitionError
type: object
- QueryParamsAppend:
+ QueryParamsAppendNotification:
properties:
key:
type: string
@@ -1056,18 +1056,18 @@ components:
- op
- key
- value
- title: QueryParamsAppend
+ title: QueryParamsAppendNotification
type: object
- QueryParamsClear:
+ QueryParamsClearNotification:
properties:
op:
enum:
- query-params-clear
required:
- op
- title: QueryParamsClear
+ title: QueryParamsClearNotification
type: object
- QueryParamsDelete:
+ QueryParamsDeleteNotification:
properties:
key:
type: string
@@ -1082,9 +1082,9 @@ components:
- op
- key
- value
- title: QueryParamsDelete
+ title: QueryParamsDeleteNotification
type: object
- QueryParamsSet:
+ QueryParamsSetNotification:
description: Set query parameters.
properties:
key:
@@ -1102,27 +1102,27 @@ components:
- op
- key
- value
- title: QueryParamsSet
+ title: QueryParamsSetNotification
type: object
- Reconnected:
+ ReconnectedNotification:
properties:
op:
enum:
- reconnected
required:
- op
- title: Reconnected
+ title: ReconnectedNotification
type: object
- Reload:
+ ReloadNotification:
properties:
op:
enum:
- reload
required:
- op
- title: Reload
+ title: ReloadNotification
type: object
- RemoveUIElements:
+ RemoveUIElementsNotification:
description: Invalidate UI elements for a given cell.
properties:
cell_id:
@@ -1133,7 +1133,7 @@ components:
required:
- op
- cell_id
- title: RemoveUIElements
+ title: RemoveUIElementsNotification
type: object
SQLMetadata:
description: Metadata for a SQL database.
@@ -1154,7 +1154,7 @@ components:
- schema
title: SQLMetadata
type: object
- SQLTableListPreview:
+ SQLTableListPreviewNotification:
description: Preview of a list of tables in a schema.
properties:
error:
@@ -1178,9 +1178,9 @@ components:
- op
- request_id
- metadata
- title: SQLTableListPreview
+ title: SQLTableListPreviewNotification
type: object
- SQLTablePreview:
+ SQLTablePreviewNotification:
description: Preview of a table in a SQL database.
properties:
error:
@@ -1204,7 +1204,7 @@ components:
- request_id
- metadata
- table
- title: SQLTablePreview
+ title: SQLTablePreviewNotification
type: object
Schema:
properties:
@@ -1219,7 +1219,7 @@ components:
- tables
title: Schema
type: object
- SecretKeysResult:
+ SecretKeysResultNotification:
description: Result of listing secret keys.
properties:
op:
@@ -1235,7 +1235,7 @@ components:
- op
- request_id
- secrets
- title: SecretKeysResult
+ title: SecretKeysResultNotification
type: object
SecretKeysWithProvider:
properties:
@@ -1255,7 +1255,7 @@ components:
- keys
title: SecretKeysWithProvider
type: object
- SendUIElementMessage:
+ UIElementMessageNotification:
description: Send a message to a UI element.
properties:
buffers:
@@ -1284,7 +1284,7 @@ components:
- ui_element
- model_id
- message
- title: SendUIElementMessage
+ title: UIElementMessageNotification
type: object
SetupRootError:
properties:
@@ -1363,7 +1363,7 @@ components:
- errors
title: SqlParseResult
type: object
- StartupLogs:
+ StartupLogsNotification:
properties:
content:
type: string
@@ -1379,7 +1379,7 @@ components:
- op
- content
- status
- title: StartupLogs
+ title: StartupLogsNotification
type: object
UnknownError:
properties:
@@ -1398,7 +1398,7 @@ components:
- msg
title: UnknownError
type: object
- UpdateCellCodes:
+ UpdateCellCodesNotification:
properties:
cell_ids:
items:
@@ -1418,9 +1418,9 @@ components:
- cell_ids
- codes
- code_is_stale
- title: UpdateCellCodes
+ title: UpdateCellCodesNotification
type: object
- UpdateCellIdsRequest:
+ UpdateCellIdsNotification:
description: 'Update the cell ID ordering of the cells in the notebook.
@@ -1438,9 +1438,9 @@ components:
required:
- op
- cell_ids
- title: UpdateCellIdsRequest
+ title: UpdateCellIdsNotification
type: object
- ValidateSQLResult:
+ ValidateSQLResultNotification:
properties:
error:
anyOf:
@@ -1465,9 +1465,9 @@ components:
required:
- op
- request_id
- title: ValidateSQLResult
+ title: ValidateSQLResultNotification
type: object
- VariableDeclaration:
+ VariableDeclarationNotification:
properties:
declared_by:
items:
@@ -1483,7 +1483,7 @@ components:
- name
- declared_by
- used_by
- title: VariableDeclaration
+ title: VariableDeclarationNotification
type: object
VariableValue:
properties:
@@ -1503,7 +1503,7 @@ components:
- datatype
title: VariableValue
type: object
- VariableValues:
+ VariableValuesNotification:
description: List of variables and their types/values.
properties:
op:
@@ -1516,9 +1516,9 @@ components:
required:
- op
- variables
- title: VariableValues
+ title: VariableValuesNotification
type: object
- Variables:
+ VariablesNotification:
description: List of variable declarations.
properties:
op:
@@ -1526,20 +1526,16 @@ components:
- variables
variables:
items:
- $ref: '#/components/schemas/VariableDeclaration'
+ $ref: '#/components/schemas/VariableDeclarationNotification'
type: array
required:
- op
- variables
- title: Variables
+ title: VariablesNotification
type: object
_AppConfig:
- description: 'Program-specific configuration.
-
-
- Configuration for frontends or runtimes that is specific to
-
- a single marimo program.'
+ description: "Program-specific configuration.\n\n Configuration for frontends\
+ \ or runtimes that is specific to\n a single marimo program."
properties:
app_title:
anyOf:
diff --git a/marimo/_server/api/endpoints/config.py b/marimo/_server/api/endpoints/config.py
index e28814b680..2af377c719 100644
--- a/marimo/_server/api/endpoints/config.py
+++ b/marimo/_server/api/endpoints/config.py
@@ -11,7 +11,7 @@ from marimo import _loggers
from marimo._config.config import PartialMarimoConfig
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.msgspec_encoder import asdict
-from marimo._messaging.ops import MissingPackageAlert
+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
@@ -85,7 +85,7 @@ async def save_user_config(
if session_id is not None and session is not None:
send_message_to_consumer(
session=session,
- operation=MissingPackageAlert(
+ operation=MissingPackageAlertNotification(
packages=["mcp"],
isolated=is_python_isolated(),
),
diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.py
index cb4d03ddea..6e53d078c3 100644
--- a/marimo/_server/api/endpoints/editing.py
+++ b/marimo/_server/api/endpoints/editing.py
@@ -5,12 +5,13 @@ from typing import TYPE_CHECKING
from starlette.authentication import requires
-from marimo._messaging.ops import UpdateCellIdsRequest
+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
@@ -97,7 +98,8 @@ async def sync_cell_ids(request: Request) -> BaseResponse:
body = await parse_request(request, cls=UpdateCellIdsRequest)
session_id = app_state.require_current_session_id()
app_state.require_current_session().notify(
- body, from_consumer_id=ConsumerId(session_id)
+ UpdateCellIdsNotification(cell_ids=body.cell_ids),
+ from_consumer_id=ConsumerId(session_id),
)
return SuccessResponse()
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index 8132b23780..5b0e5ee667 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -9,7 +9,7 @@ from starlette.authentication import requires
from starlette.responses import JSONResponse
from marimo import _loggers
-from marimo._messaging.ops import Alert
+from marimo._messaging.notification import AlertNotification
from marimo._runtime.requests import (
ExecuteScratchpadRequest,
FunctionCallRequest,
@@ -371,7 +371,7 @@ async def takeover_endpoint(
if existing_session is not None:
# Send a disconnect message to the client
existing_session.notify(
- Alert(
+ AlertNotification(
title="Session taken over",
description="Another user has taken over this session.",
variant="danger",
diff --git a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py b/marimo/_server/api/endpoints/ws/ws_kernel_ready.py
index 316b00b86e..f9926b3c23 100644
--- a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py
+++ b/marimo/_server/api/endpoints/ws/ws_kernel_ready.py
@@ -8,7 +8,10 @@ from typing import TYPE_CHECKING
from marimo import _loggers
from marimo._ast.cell import CellConfig
from marimo._dependencies.dependencies import DependencyManager
-from marimo._messaging.ops import KernelCapabilities, KernelReady
+from marimo._messaging.notification import (
+ KernelCapabilitiesNotification,
+ KernelReadyNotification,
+)
from marimo._plugins.core.web_component import JSONType
from marimo._server.model import SessionMode
from marimo._types.ids import CellId_t
@@ -35,7 +38,7 @@ def build_kernel_ready(
file_key: MarimoFileKey,
mode: SessionMode,
doc_manager: LoroDocManager,
-) -> KernelReady:
+) -> KernelReadyNotification:
"""Build a KernelReady message.
Args:
@@ -60,7 +63,7 @@ def build_kernel_ready(
if _should_init_rtc(rtc_enabled, mode):
_try_init_rtc_doc(cell_ids, codes, file_key, doc_manager)
- return KernelReady(
+ return KernelReadyNotification(
codes=codes,
names=names,
configs=configs,
@@ -72,7 +75,7 @@ def build_kernel_ready(
last_execution_time=last_execution_time,
app_config=session.app_file_manager.app.config,
kiosk=kiosk,
- capabilities=KernelCapabilities(),
+ capabilities=KernelCapabilitiesNotification(),
)
diff --git a/marimo/_server/api/endpoints/ws/ws_message_loop.py b/marimo/_server/api/endpoints/ws/ws_message_loop.py
index a461d45579..744d992d47 100644
--- a/marimo/_server/api/endpoints/ws/ws_message_loop.py
+++ b/marimo/_server/api/endpoints/ws/ws_message_loop.py
@@ -7,11 +7,11 @@ from typing import TYPE_CHECKING, Any, Callable
from starlette.websockets import WebSocketDisconnect, WebSocketState
from marimo import _loggers
-from marimo._messaging.ops import (
- CompletionResult,
- FocusCell,
+from marimo._messaging.notification import (
+ CompletionResultNotification,
+ FocusCellNotification,
)
-from marimo._messaging.serde import deserialize_kernel_operation_name
+from marimo._messaging.serde import deserialize_kernel_notification_name
from marimo._messaging.types import KernelMessage
if TYPE_CHECKING:
@@ -21,12 +21,12 @@ LOGGER = _loggers.marimo_logger()
# Operations that are only sent in kiosk mode
KIOSK_ONLY_OPERATIONS = {
- FocusCell.name,
+ FocusCellNotification.name,
}
# Operations that are excluded from kiosk mode
KIOSK_EXCLUDED_OPERATIONS = {
- CompletionResult.name,
+ CompletionResultNotification.name,
}
@@ -72,7 +72,7 @@ class WebSocketMessageLoop:
"""Listen for messages from kernel and send to frontend."""
while True:
data = await self.message_queue.get()
- op: str = deserialize_kernel_operation_name(data)
+ op: str = deserialize_kernel_notification_name(data)
if self._should_filter_operation(op):
continue
diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.py
index 2f1295f036..5bd1730593 100644
--- a/marimo/_server/api/endpoints/ws_endpoint.py
+++ b/marimo/_server/api/endpoints/ws_endpoint.py
@@ -12,11 +12,11 @@ from marimo._cli.upgrade import check_for_updates
from marimo._config.cli_state import MarimoCLIState
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._dependencies.dependencies import DependencyManager
-from marimo._messaging.ops import (
- Alert,
- Banner,
- MessageOperation,
- Reconnected,
+from marimo._messaging.notification import (
+ AlertNotification,
+ BannerNotification,
+ NotificationMessage,
+ ReconnectedNotification,
)
from marimo._messaging.serde import serialize_kernel_message
from marimo._messaging.types import KernelMessage
@@ -169,7 +169,7 @@ class WebSocketHandler(SessionConsumer):
def notify(self, notification: KernelMessage) -> None:
self.message_queue.put_nowait(notification)
- def _serialize_and_notify(self, notification: MessageOperation) -> None:
+ def _serialize_and_notify(self, notification: NotificationMessage) -> None:
self.notify(serialize_kernel_message(notification))
def _write_kernel_ready_from_session_view(
@@ -234,12 +234,12 @@ class WebSocketHandler(SessionConsumer):
session.connect_consumer(self, main=True)
# Write reconnected message
- self._serialize_and_notify(Reconnected())
+ self._serialize_and_notify(ReconnectedNotification())
# If not replaying, just send a toast
if not replay:
self._serialize_and_notify(
- Alert(
+ AlertNotification(
title="Reconnected",
description="You have reconnected to an existing session.",
)
@@ -248,7 +248,7 @@ class WebSocketHandler(SessionConsumer):
self._write_kernel_ready_from_session_view(session, self.params.kiosk)
self._serialize_and_notify(
- Banner(
+ BannerNotification(
title="Reconnected",
description="You have reconnected to an existing session.",
action="restart",
@@ -279,14 +279,14 @@ class WebSocketHandler(SessionConsumer):
def _replay_previous_session(self, session: Session) -> None:
"""Replay the previous session view."""
- operations = session.session_view.operations
- if len(operations) == 0:
- LOGGER.debug("No operations to replay")
+ notifications = session.session_view.notifications
+ if len(notifications) == 0:
+ LOGGER.debug("No notifications to replay")
return
- LOGGER.debug(f"Replaying {len(operations)} operations")
- for op in operations:
- LOGGER.debug("Replaying operation %s", op)
- self._serialize_and_notify(op)
+ LOGGER.debug(f"Replaying {len(notifications)} notifications")
+ for notif in notifications:
+ LOGGER.debug("Replaying notification %s", notif)
+ self._serialize_and_notify(notif)
def _on_disconnect(
self,
@@ -469,7 +469,7 @@ class WebSocketHandler(SessionConsumer):
description += notices_text
self._serialize_and_notify(
- Alert(title=title, description=description)
+ AlertNotification(title=title, description=description)
)
check_for_updates(on_update)
diff --git a/marimo/_server/errors.py b/marimo/_server/errors.py
index 38e1728541..e41cc07109 100644
--- a/marimo/_server/errors.py
+++ b/marimo/_server/errors.py
@@ -8,7 +8,7 @@ from starlette.exceptions import HTTPException
from starlette.responses import JSONResponse
from marimo import _loggers
-from marimo._messaging.ops import MissingPackageAlert
+from marimo._messaging.notification import MissingPackageAlertNotification
from marimo._runtime.packages.utils import is_python_isolated
from marimo._server.api.deps import AppState
from marimo._server.api.status import (
@@ -64,7 +64,7 @@ async def handle_error(request: Request, response: Any) -> Any:
):
send_message_to_consumer(
session=session,
- operation=MissingPackageAlert(
+ operation=MissingPackageAlertNotification(
packages=[response.name],
isolated=is_python_isolated(),
),
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index e41789b18f..38a7b802df 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -15,9 +15,9 @@ from marimo._config.manager import (
)
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.errors import Error, is_unexpected_error
-from marimo._messaging.ops import (
- CellOp,
- CompletedRun,
+from marimo._messaging.notification import (
+ CellNotification,
+ CompletedRunNotification,
)
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage
@@ -255,7 +255,7 @@ async def run_app_until_completion(
def notify(self, notification: KernelMessage) -> None:
data = deserialize_kernel_message(notification)
# Print errors to stderr
- if isinstance(data, CellOp):
+ if isinstance(data, CellNotification):
output = data.output
console_output = data.console
if output and output.channel == CellChannel.MARIMO_ERROR:
@@ -285,7 +285,7 @@ async def run_app_until_completion(
except Exception:
LOGGER.warning("Error printing console output")
- if isinstance(data, CompletedRun):
+ if isinstance(data, CompletedRunNotification):
instantiated_event.set()
def on_attach(
diff --git a/marimo/_server/lsp.py b/marimo/_server/lsp.py
index d272441c82..fe0fcffb9a 100644
--- a/marimo/_server/lsp.py
+++ b/marimo/_server/lsp.py
@@ -12,7 +12,7 @@ from marimo._config.config import MarimoConfig
from marimo._config.manager import MarimoConfigReader
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._dependencies.dependencies import DependencyManager
-from marimo._messaging.ops import Alert
+from marimo._messaging.notification import AlertNotification
from marimo._server.utils import find_free_port
from marimo._tracer import server_tracer
from marimo._utils.paths import marimo_package_path
@@ -26,7 +26,7 @@ class LspServer(ABC):
id: str
@abstractmethod
- async def start(self) -> Optional[Alert]:
+ async def start(self) -> Optional[AlertNotification]:
pass
@abstractmethod
@@ -47,7 +47,7 @@ class BaseLspServer(LspServer):
self.log_file = _loggers.get_log_directory() / f"{self.id}.log"
@server_tracer.start_as_current_span("lsp_server.start")
- async def start(self) -> Optional[Alert]:
+ async def start(self) -> Optional[AlertNotification]:
if self.process is not None:
LOGGER.debug("LSP server already started")
return None
@@ -104,7 +104,7 @@ class BaseLspServer(LspServer):
LOGGER.error(f"Command: {' '.join(cmd)}")
LOGGER.error(f"Error output: {stderr_output}")
- return Alert(
+ return AlertNotification(
title=f"{self.id} LSP server failed to start",
description=f"The {self.id} server crashed on startup. Check {self.log_file} for details. Error: {stderr_output[:200]}",
variant="danger",
@@ -206,7 +206,7 @@ class BaseLspServer(LspServer):
def get_command(self) -> list[str]:
raise NotImplementedError()
- def missing_binary_alert(self) -> Alert:
+ def missing_binary_alert(self) -> AlertNotification:
raise NotImplementedError()
@@ -286,8 +286,8 @@ class CopilotLspServer(BaseLspServer):
str(self.log_file),
]
- def missing_binary_alert(self) -> Alert:
- return Alert(
+ def missing_binary_alert(self) -> AlertNotification:
+ return AlertNotification(
title="GitHub Copilot: Connection Error",
description="<span><a class='hyperlink' href='https://docs.marimo.io/getting_started/index.html#github-copilot'>Install Node.js</a> to use copilot.</span>",
variant="danger",
@@ -306,7 +306,7 @@ class PyLspServer(BaseLspServer):
id = "pylsp"
- async def start(self) -> Optional[Alert]:
+ async def start(self) -> Optional[AlertNotification]:
# pylsp is not required, so we don't want to alert or fail if it is not installed
if not DependencyManager.pylsp.has():
LOGGER.info(
@@ -354,8 +354,8 @@ class PyLspServer(BaseLspServer):
str(self.log_file),
]
- def missing_binary_alert(self) -> Alert:
- return Alert(
+ def missing_binary_alert(self) -> AlertNotification:
+ return AlertNotification(
title="Python LSP: Connection Error",
description=f"<span><a class='hyperlink' href='https://github.com/python-lsp/python-lsp-server'>Install python-lsp-server</a> for Python language support. If already installed, check {self.log_file} or disable pylsp in Settings > Editor > Language Servers.</span>",
variant="danger",
@@ -369,7 +369,7 @@ class BasedpyrightServer(BaseLspServer):
super().__init__(port)
self.log_file = _loggers.get_log_directory() / "basedpyright-lsp.log"
- async def start(self) -> Optional[Alert]:
+ async def start(self) -> Optional[AlertNotification]:
# basedpyright is not required, so we don't want to alert or fail if it is not installed
if not DependencyManager.basedpyright.has():
LOGGER.debug("basedpyright is not installed. Skipping LSP server.")
@@ -399,8 +399,8 @@ class BasedpyrightServer(BaseLspServer):
str(self.log_file),
]
- def missing_binary_alert(self) -> Alert:
- return Alert(
+ def missing_binary_alert(self) -> AlertNotification:
+ return AlertNotification(
title="basedpyright: Connection Error",
description="<span><a class='hyperlink' href='https://docs.basedpyright.com'>Install basedpyright</a> for type checking support.</span>",
variant="danger",
@@ -414,7 +414,7 @@ class TyServer(BaseLspServer):
super().__init__(port)
self.log_file = _loggers.get_log_directory() / "ty-lsp.log"
- async def start(self) -> Optional[Alert]:
+ async def start(self) -> Optional[AlertNotification]:
# ty is not required, so we don't want to alert or fail if it is not installed
if not DependencyManager.ty.has():
LOGGER.debug("ty is not installed. Skipping LSP server.")
@@ -449,8 +449,8 @@ class TyServer(BaseLspServer):
str(self.log_file),
]
- def missing_binary_alert(self) -> Alert:
- return Alert(
+ def missing_binary_alert(self) -> AlertNotification:
+ return AlertNotification(
title="Ty: Connection Error",
description="<span><a class='hyperlink' href='https://github.com/astral-sh/ty'>Install ty</a> for type checking support.</span>",
variant="danger",
@@ -509,10 +509,10 @@ class CompositeLspServer(LspServer):
.get("enabled", False),
)
- async def start(self) -> Optional[Alert]:
+ async def start(self) -> Optional[AlertNotification]:
# .get_config() should not be cached, as it may be updated by the user
config = self.config_reader.get_config()
- tasks: list[asyncio.Task[Optional[Alert]]] = []
+ tasks: list[asyncio.Task[Optional[AlertNotification]]] = []
for server_name, server in self.servers.items():
if not self._is_enabled(config, server_name):
diff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.py
index 7b11579e60..eb5dc2b88c 100644
--- a/marimo/_server/session/serialize.py
+++ b/marimo/_server/session/serialize.py
@@ -18,7 +18,7 @@ from marimo._messaging.errors import (
)
from marimo._messaging.mimetypes import KnownMimeType
from marimo._messaging.msgspec_encoder import asdict
-from marimo._messaging.ops import CellOp
+from marimo._messaging.notification import CellNotification
from marimo._schemas.notebook import (
NotebookCell,
NotebookCellConfig,
@@ -99,12 +99,12 @@ def serialize_session_view(
"reconstruct the notebook state from the serialized session "
"view."
)
- cell_ids = view.cell_operations.keys()
+ cell_ids = view.cell_notifications.keys()
for cell_id in cell_ids:
- cell_op = view.cell_operations.get(cell_id)
- if cell_op is None:
- # We haven't seen any outputs or operations for this cell.
+ cell_notif = view.cell_notifications.get(cell_id)
+ if cell_notif is None:
+ # We haven't seen any outputs or notifications for this cell.
cells.append(
Cell(id=cell_id, code_hash=None, outputs=[], console=[])
)
@@ -113,11 +113,11 @@ def serialize_session_view(
console: list[ConsoleType] = []
# Convert output
- if cell_op.output:
- if cell_op.output.channel == CellChannel.MARIMO_ERROR:
+ if cell_notif.output:
+ if cell_notif.output.channel == CellChannel.MARIMO_ERROR:
for error in cast(
list[Union[MarimoError, dict[str, Any]]],
- cell_op.output.data,
+ cell_notif.output.data,
):
outputs.append(_normalize_error(error))
else:
@@ -125,13 +125,13 @@ def serialize_session_view(
DataOutput(
type="data",
data={
- cell_op.output.mimetype: cell_op.output.data,
+ cell_notif.output.mimetype: cell_notif.output.data,
},
)
)
# Convert console outputs
- for console_out in as_list(cell_op.console):
+ for console_out in as_list(cell_notif.console):
assert isinstance(console_out, CellOutput)
if console_out.channel == CellChannel.MEDIA:
console.append(
@@ -293,7 +293,7 @@ def deserialize_session(
)
continue
- view.cell_operations[cell_id] = CellOp(
+ view.cell_notifications[cell_id] = CellNotification(
cell_id=cell_id,
status="idle",
output=cell_outputs[0] if cell_outputs else None,
diff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.py
index 5390503544..72d248e9fe 100644
--- a/marimo/_server/session/session_view.py
+++ b/marimo/_server/session/session_view.py
@@ -7,22 +7,22 @@ from typing import Any, Literal, Optional
from marimo._data.models import DataSourceConnection, DataTable
from marimo._messaging.cell_output import CellChannel, CellOutput
-from marimo._messaging.ops import (
- CellOp,
- Datasets,
- DataSourceConnections,
- InstallingPackageAlert,
- Interrupted,
- MessageOperation,
- SendUIElementMessage,
- SQLTableListPreview,
- SQLTablePreview,
- StartupLogs,
- UpdateCellCodes,
- UpdateCellIdsRequest,
- Variables,
+from marimo._messaging.notification import (
+ CellNotification,
+ DatasetsNotification,
+ DataSourceConnectionsNotification,
+ InstallingPackageAlertNotification,
+ InterruptedNotification,
+ NotificationMessage,
+ SQLTableListPreviewNotification,
+ SQLTablePreviewNotification,
+ StartupLogsNotification,
+ UIElementMessageNotification,
+ UpdateCellCodesNotification,
+ UpdateCellIdsNotification,
+ VariablesNotification,
VariableValue,
- VariableValues,
+ VariableValuesNotification,
)
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage
@@ -70,7 +70,7 @@ class SessionView:
Of note, a SessionView stores:
* the last-seen notebook-order of Cell IDs
- * a mapping from cell IDs to their last seen operation of interest,
+ * a mapping from cell IDs to their last seen notification of interest,
such as an output, status, or console output
* various other state needed for replay
@@ -81,15 +81,19 @@ class SessionView:
def __init__(self) -> None:
# Last seen notebook-order of cell IDs
- self.cell_ids: Optional[UpdateCellIdsRequest] = None
- # A mapping from cell (IDs) to their last seen operation
- self.cell_operations: dict[CellId_t, CellOp] = {}
- # The most recent datasets operation.
- self.datasets = Datasets(tables=[])
- # The most recent data-connectors operation
- self.data_connectors = DataSourceConnections(connections=[])
- # The most recent Variables operation.
- self.variable_operations: Variables = Variables(variables=[])
+ self.cell_ids: Optional[UpdateCellIdsNotification] = None
+ # A mapping from cell (IDs) to their last seen notification
+ self.cell_notifications: dict[CellId_t, CellNotification] = {}
+ # The most recent datasets notification.
+ self.datasets = DatasetsNotification(tables=[])
+ # The most recent data-connectors notification
+ self.data_connectors = DataSourceConnectionsNotification(
+ connections=[]
+ )
+ # The most recent Variables notification.
+ self.variable_notifications: VariablesNotification = (
+ VariablesNotification(variables=[])
+ )
# Map of variable name to value.
self.variable_values: dict[str, VariableValue] = {}
# Map of object id to value.
@@ -99,14 +103,14 @@ class SessionView:
# Map of cell id to the last cell execution time
self.last_execution_time: dict[CellId_t, float] = {}
# Any stale code that was read from a file-watcher
- self.stale_code: Optional[UpdateCellCodes] = None
+ self.stale_code: Optional[UpdateCellCodesNotification] = None
# Model messages
self.model_messages: dict[
- WidgetModelId, list[SendUIElementMessage]
+ WidgetModelId, list[UIElementMessageNotification]
] = {}
# Startup logs for startup command - only one at a time
- self.startup_logs: Optional[StartupLogs] = None
+ self.startup_logs: Optional[StartupLogsNotification] = None
# Package installation logs - accumulated per package
self.package_logs: dict[
@@ -122,10 +126,10 @@ class SessionView:
def _add_last_run_code(self, req: ExecutionRequest) -> None:
self.last_executed_code[req.cell_id] = req.code
- def add_raw_operation(self, raw_operation: KernelMessage) -> None:
+ def add_raw_notification(self, raw_notification: KernelMessage) -> None:
self._touch()
- # Type ignore because MessageOperation is a Union, not a class
- self.add_operation(deserialize_kernel_message(raw_operation)) # type: ignore[arg-type]
+ # 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:
self._touch()
@@ -150,37 +154,40 @@ class SessionView:
"""Add a stdin request to the session view."""
# Find the first cell that is waiting for stdin.
- for cell_op in self.cell_operations.values():
- console_ops: list[CellOutput] = as_list(cell_op.console)
- for cell_output in console_ops:
+ for cell_notif in self.cell_notifications.values():
+ console_outputs: list[CellOutput] = as_list(cell_notif.console)
+ for cell_output in console_outputs:
if cell_output.channel == CellChannel.STDIN:
cell_output.channel = CellChannel.STDOUT
cell_output.data = f"{cell_output.data} {stdin}\n"
return
- def add_operation(self, operation: MessageOperation) -> None:
- """Add an operation to the session view."""
+ def add_notification(self, notification: NotificationMessage) -> None:
+ """Add a notification to the session view."""
self._touch()
self.auto_export_state.mark_all_stale()
- if isinstance(operation, CellOp):
- previous = self.cell_operations.get(operation.cell_id)
- self.cell_operations[operation.cell_id] = merge_cell_operation(
- previous, operation
+ if isinstance(notification, CellNotification):
+ previous = self.cell_notifications.get(notification.cell_id)
+ self.cell_notifications[notification.cell_id] = (
+ merge_cell_notification(previous, notification)
)
if not previous:
return
- if previous.status == "queued" and operation.status == "running":
- self.save_execution_time(operation, "start")
- if previous.status == "running" and operation.status == "idle":
- self.save_execution_time(operation, "end")
+ if (
+ previous.status == "queued"
+ and notification.status == "running"
+ ):
+ self.save_execution_time(notification, "start")
+ if previous.status == "running" and notification.status == "idle":
+ self.save_execution_time(notification, "end")
- elif isinstance(operation, Variables):
- self.variable_operations = operation
+ elif isinstance(notification, VariablesNotification):
+ self.variable_notifications = notification
# Set of variable names that are in scope.
variable_names: set[str] = set(
- [v.name for v in self.variable_operations.variables]
+ [v.name for v in self.variable_notifications.variables]
)
# Remove any variable values that are no longer in scope.
@@ -204,7 +211,9 @@ class SessionView:
next_tables[table.name] = table
else:
next_tables[table.name] = table
- self.datasets = Datasets(tables=list(next_tables.values()))
+ self.datasets = DatasetsNotification(
+ tables=list(next_tables.values())
+ )
# Remove any data source connections that are no longer in scope.
# Keep internal connections if they exist as these are not defined in variables
@@ -215,47 +224,47 @@ class SessionView:
or connection.name == INTERNAL_DUCKDB_ENGINE
):
next_connections[connection.name] = connection
- self.data_connectors = DataSourceConnections(
+ self.data_connectors = DataSourceConnectionsNotification(
connections=list(next_connections.values())
)
- elif isinstance(operation, VariableValues):
- for value in operation.variables:
+ elif isinstance(notification, VariableValuesNotification):
+ for value in notification.variables:
self.variable_values[value.name] = value
- elif isinstance(operation, Interrupted):
+ elif isinstance(notification, InterruptedNotification):
# Resolve stdin
self.add_stdin("")
- elif isinstance(operation, Datasets):
+ elif isinstance(notification, DatasetsNotification):
# Merge datasets, dedupe by table name and keep the latest.
# If clear_channel is set, clear those tables
prev_tables = self.datasets.tables
- if operation.clear_channel is not None:
+ if notification.clear_channel is not None:
prev_tables = [
t
for t in prev_tables
- if t.source_type != operation.clear_channel
+ if t.source_type != notification.clear_channel
]
tables = {t.name: t for t in prev_tables}
- for table in operation.tables:
+ for table in notification.tables:
tables[table.name] = table
- self.datasets = Datasets(tables=list(tables.values()))
+ self.datasets = DatasetsNotification(tables=list(tables.values()))
- elif isinstance(operation, DataSourceConnections):
+ elif isinstance(notification, DataSourceConnectionsNotification):
# Update data source connections, dedupe by name and keep the latest
prev_connections = self.data_connectors.connections
connections = {c.name: c for c in prev_connections}
- for c in operation.connections:
+ for c in notification.connections:
connections[c.name] = c
- self.data_connectors = DataSourceConnections(
+ self.data_connectors = DataSourceConnectionsNotification(
connections=list(connections.values())
)
- elif isinstance(operation, SQLTablePreview):
- sql_table_preview = operation
+ elif isinstance(notification, SQLTablePreviewNotification):
+ sql_table_preview = notification
sql_metadata = sql_table_preview.metadata
table_preview_connections = self.data_connectors.connections
if sql_table_preview.table is not None:
@@ -265,8 +274,8 @@ class SessionView:
sql_table_preview.table,
)
- elif isinstance(operation, SQLTableListPreview):
- sql_table_list_preview = operation
+ elif isinstance(notification, SQLTableListPreviewNotification):
+ sql_table_list_preview = notification
sql_metadata = sql_table_list_preview.metadata
table_list_connections = self.data_connectors.connections
update_table_list_in_connection(
@@ -275,43 +284,44 @@ class SessionView:
sql_table_list_preview.tables,
)
- elif isinstance(operation, UpdateCellIdsRequest):
- self.cell_ids = operation
+ elif isinstance(notification, UpdateCellIdsNotification):
+ self.cell_ids = notification
elif (
- isinstance(operation, UpdateCellCodes) and operation.code_is_stale
+ isinstance(notification, UpdateCellCodesNotification)
+ and notification.code_is_stale
):
- self.stale_code = operation
+ self.stale_code = notification
- elif isinstance(operation, SendUIElementMessage):
- if operation.model_id is None:
+ elif isinstance(notification, UIElementMessageNotification):
+ if notification.model_id is None:
return
- messages = self.model_messages.get(operation.model_id, [])
- messages.append(operation)
+ messages = self.model_messages.get(notification.model_id, [])
+ messages.append(notification)
# TODO: cleanup/merge previous 'update' messages
- self.model_messages[operation.model_id] = messages
+ self.model_messages[notification.model_id] = messages
- elif isinstance(operation, StartupLogs):
+ elif isinstance(notification, StartupLogsNotification):
prev = self.startup_logs.content if self.startup_logs else ""
- self.startup_logs = StartupLogs(
- content=prev + operation.content,
- status=operation.status,
+ self.startup_logs = StartupLogsNotification(
+ content=prev + notification.content,
+ status=notification.status,
)
- elif isinstance(operation, InstallingPackageAlert):
+ elif isinstance(notification, InstallingPackageAlertNotification):
# Handle streaming logs if present
- if operation.logs and operation.log_status:
- for package_name, new_content in operation.logs.items():
- if operation.log_status == "start":
+ if notification.logs and notification.log_status:
+ for package_name, new_content in notification.logs.items():
+ if notification.log_status == "start":
# Start new log for this package
self.package_logs[package_name] = new_content
- elif operation.log_status == "append":
+ elif notification.log_status == "append":
# Append to existing log
prev_content = self.package_logs.get(package_name, "")
self.package_logs[package_name] = (
prev_content + new_content
)
- elif operation.log_status == "done":
+ elif notification.log_status == "done":
# Append final content and mark as done
prev_content = self.package_logs.get(package_name, "")
self.package_logs[package_name] = (
@@ -326,9 +336,9 @@ class SessionView:
"""Get the outputs for the given cell ids."""
outputs: dict[CellId_t, CellOutput] = {}
for cell_id in ids:
- cell_op = self.cell_operations.get(cell_id)
- if cell_op is not None and cell_op.output is not None:
- outputs[cell_id] = cell_op.output
+ cell_notif = self.cell_notifications.get(cell_id)
+ if cell_notif is not None and cell_notif.output is not None:
+ outputs[cell_id] = cell_notif.output
return outputs
def get_cell_console_outputs(
@@ -337,21 +347,21 @@ class SessionView:
"""Get the console outputs for the given cell ids."""
outputs: dict[CellId_t, list[CellOutput]] = {}
for cell_id in ids:
- cell_op = self.cell_operations.get(cell_id)
- if cell_op is not None and cell_op.console:
- outputs[cell_id] = as_list(cell_op.console)
+ cell_notif = self.cell_notifications.get(cell_id)
+ if cell_notif is not None and cell_notif.console:
+ outputs[cell_id] = as_list(cell_notif.console)
return outputs
def save_execution_time(
- self, operation: MessageOperation, event: Literal["start", "end"]
+ self, notification: NotificationMessage, event: Literal["start", "end"]
) -> None:
"""Updates execution time for given cell."""
- if not isinstance(operation, CellOp):
+ if not isinstance(notification, CellNotification):
return
- cell_id = operation.cell_id
+ cell_id = notification.cell_id
if event == "start":
- time_elapsed = operation.timestamp
+ time_elapsed = notification.timestamp
elif event == "end":
start = self.last_execution_time.get(cell_id)
start = start if start else 0
@@ -361,35 +371,37 @@ class SessionView:
self.last_execution_time[cell_id] = time_elapsed
@property
- def operations(self) -> list[MessageOperation]:
- all_ops: list[MessageOperation] = []
+ def notifications(self) -> list[NotificationMessage]:
+ all_notifications: list[NotificationMessage] = []
if self.cell_ids:
- all_ops.append(self.cell_ids)
- if self.variable_operations.variables:
- all_ops.append(self.variable_operations)
+ all_notifications.append(self.cell_ids)
+ if self.variable_notifications.variables:
+ all_notifications.append(self.variable_notifications)
if self.variable_values:
- all_ops.append(
- VariableValues(variables=list(self.variable_values.values()))
+ all_notifications.append(
+ VariableValuesNotification(
+ variables=list(self.variable_values.values())
+ )
)
if self.datasets.tables:
- all_ops.append(self.datasets)
+ all_notifications.append(self.datasets)
if self.data_connectors.connections:
- all_ops.append(self.data_connectors)
- all_ops.extend(self.cell_operations.values())
+ all_notifications.append(self.data_connectors)
+ all_notifications.extend(self.cell_notifications.values())
if self.stale_code:
- all_ops.append(self.stale_code)
+ all_notifications.append(self.stale_code)
if self.model_messages:
for messages in self.model_messages.values():
- all_ops.extend(messages)
+ all_notifications.extend(messages)
# Only include startup logs if they are in progress (not done)
if self.startup_logs and self.startup_logs.status != "done":
- all_ops.append(self.startup_logs)
- return all_ops
+ all_notifications.append(self.startup_logs)
+ return all_notifications
def is_empty(self) -> bool:
return all(
- op.output is None and op.console is None
- for op in self.cell_operations.values()
+ notif.output is None and notif.console is None
+ for notif in self.cell_notifications.values()
)
def mark_auto_export_html(self) -> None:
@@ -443,32 +455,32 @@ def _merge_consecutive_console_outputs(
return merged
-def merge_cell_operation(
- previous: Optional[CellOp],
- next_: CellOp,
-) -> CellOp:
- """Merge two cell operations."""
+def merge_cell_notification(
+ previous: Optional[CellNotification],
+ current: CellNotification,
+) -> CellNotification:
+ """Merge two cell notifications."""
if previous is None:
- return next_
+ return current
- assert previous.cell_id == next_.cell_id
+ assert previous.cell_id == current.cell_id
- if next_.status is None:
- next_.status = previous.status
+ if current.status is None:
+ current.status = previous.status
# If we went from queued to running, clear the console.
- if next_.status == "running" and previous.status == "queued":
- next_.console = []
+ if current.status == "running" and previous.status == "queued":
+ current.console = []
else:
combined_console: list[CellOutput] = as_list(previous.console)
- combined_console.extend(as_list(next_.console))
- next_.console = _merge_consecutive_console_outputs(combined_console)
+ combined_console.extend(as_list(current.console))
+ current.console = _merge_consecutive_console_outputs(combined_console)
# If we went from running to running, use the previous timestamp.
- if next_.status == "running" and previous.status == "running":
- next_.timestamp = previous.timestamp
+ if current.status == "running" and previous.status == "running":
+ current.timestamp = previous.timestamp
- if next_.output is None:
- next_.output = previous.output
+ if current.output is None:
+ current.output = previous.output
- return next_
+ return current
diff --git a/marimo/_server/sessions/file_change_handler.py b/marimo/_server/sessions/file_change_handler.py
index 97e760c5f9..fd26c01564 100644
--- a/marimo/_server/sessions/file_change_handler.py
+++ b/marimo/_server/sessions/file_change_handler.py
@@ -12,7 +12,11 @@ from typing import TYPE_CHECKING, Optional, Protocol
from marimo import _loggers
from marimo._config.manager import MarimoConfigManager
-from marimo._messaging.ops import Reload, UpdateCellCodes, UpdateCellIdsRequest
+from marimo._messaging.notification import (
+ ReloadNotification,
+ UpdateCellCodesNotification,
+ UpdateCellIdsNotification,
+)
from marimo._runtime.requests import DeleteCellRequest, SyncGraphRequest
from marimo._server.model import SessionMode
from marimo._types.ids import CellId_t
@@ -76,7 +80,7 @@ class EditModeReloadStrategy(ReloadStrategy):
# Send the updated cell IDs to the frontend
session.notify(
- UpdateCellIdsRequest(cell_ids=cell_ids),
+ UpdateCellIdsNotification(cell_ids=cell_ids),
from_consumer_id=None,
)
@@ -113,7 +117,7 @@ class EditModeReloadStrategy(ReloadStrategy):
)
if cell_ids:
session.notify(
- UpdateCellCodes(
+ UpdateCellCodesNotification(
cell_ids=cell_ids,
codes=codes,
code_is_stale=True,
@@ -133,7 +137,7 @@ class RunModeReloadStrategy:
) -> None:
"""Handle reload in run mode by sending Reload operation."""
del changed_cell_ids
- session.notify(Reload(), from_consumer_id=None)
+ session.notify(ReloadNotification(), from_consumer_id=None)
class FileChangeCoordinator:
diff --git a/marimo/_server/sessions/session.py b/marimo/_server/sessions/session.py
index 20887465a7..7b86630a66 100644
--- a/marimo/_server/sessions/session.py
+++ b/marimo/_server/sessions/session.py
@@ -12,10 +12,10 @@ from uuid import uuid4
from marimo import _loggers
from marimo._config.manager import MarimoConfigManager, ScriptConfigManager
-from marimo._messaging.ops import (
- FocusCell,
- MessageOperation,
- UpdateCellCodes,
+from marimo._messaging.notification import (
+ FocusCellNotification,
+ NotificationMessage,
+ UpdateCellCodesNotification,
)
from marimo._messaging.serde import serialize_kernel_message
from marimo._messaging.types import KernelMessage
@@ -256,7 +256,7 @@ class SessionImpl(Session):
codes = [request.cells[cell_id] for cell_id in cell_ids]
if cell_ids:
self.notify(
- UpdateCellCodes(
+ UpdateCellCodesNotification(
cell_ids=cell_ids,
codes=codes,
# Not stale because we just ran the code
@@ -266,7 +266,7 @@ class SessionImpl(Session):
)
if len(cell_ids) == 1:
self.notify(
- FocusCell(cell_id=cell_ids[0]),
+ FocusCellNotification(cell_id=cell_ids[0]),
from_consumer_id=from_consumer_id,
)
@@ -332,7 +332,7 @@ class SessionImpl(Session):
def notify(
self,
- operation: MessageOperation | KernelMessage,
+ operation: NotificationMessage | KernelMessage,
from_consumer_id: Optional[ConsumerId],
) -> None:
"""Write an operation to the session consumer and the session view."""
@@ -341,7 +341,7 @@ class SessionImpl(Session):
else:
notification = serialize_kernel_message(operation)
self.room.broadcast(notification, except_consumer=from_consumer_id)
- self.session_view.add_raw_operation(notification)
+ self.session_view.add_raw_notification(notification)
self._event_bus.emit_notification_sent(self, notification)
def close(self) -> None:
diff --git a/marimo/_server/sessions/types.py b/marimo/_server/sessions/types.py
index c748caef4f..9ffca666da 100644
--- a/marimo/_server/sessions/types.py
+++ b/marimo/_server/sessions/types.py
@@ -16,7 +16,7 @@ if TYPE_CHECKING:
from collections.abc import Mapping
from marimo._config.manager import MarimoConfigManager
- from marimo._messaging.ops import MessageOperation
+ from marimo._messaging.notification import NotificationMessage
from marimo._messaging.types import KernelMessage
from marimo._runtime import requests
from marimo._server.consumer import SessionConsumer
@@ -178,7 +178,7 @@ class Session(Protocol):
def notify(
self,
- operation: MessageOperation | KernelMessage,
+ operation: NotificationMessage | KernelMessage,
from_consumer_id: Optional[ConsumerId],
) -> None:
"""Write an operation to the session consumer and the session view."""
diff --git a/marimo/_server/sessions/utils.py b/marimo/_server/sessions/utils.py
index 60718b513a..7823517df2 100644
--- a/marimo/_server/sessions/utils.py
+++ b/marimo/_server/sessions/utils.py
@@ -10,13 +10,13 @@ from marimo._server.model import ConnectionState
from marimo._types.ids import ConsumerId
if TYPE_CHECKING:
- from marimo._messaging.ops import MessageOperation
+ from marimo._messaging.notification import NotificationMessage
from marimo._server.sessions.session import Session
def send_message_to_consumer(
session: Session,
- operation: MessageOperation,
+ operation: NotificationMessage,
consumer_id: Optional[ConsumerId],
) -> None:
"""Send a message operation to a specific consumer in a session."""
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index 4d4bb8b197..bd6ba8671e 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -14,7 +14,7 @@ from marimo._cli.print import echo
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.ops import StartupLogs
+from marimo._messaging.notification import StartupLogsNotification
from marimo._runtime.requests import SerializedCLIArgs
from marimo._server.file_router import AppFileRouter
from marimo._server.lsp import CompositeLspServer, NoopLspServer
@@ -43,18 +43,21 @@ def _execute_startup_command(
"""Execute a server startup command in a background thread and stream logs."""
def run_command() -> None:
- buffer = StartupLogs(content="", status="start")
+ buffer = StartupLogsNotification(content="", status="start")
try:
def write_to_all_sessions(
- content: StartupLogs, buffer: StartupLogs
+ content: StartupLogsNotification,
+ buffer: StartupLogsNotification,
) -> None:
for session in session_manager.sessions.values():
# Clear buffer if it has content
if buffer.content != "":
session.notify(buffer, from_consumer_id=None)
- buffer = StartupLogs(content="", status="start")
+ buffer = StartupLogsNotification(
+ content="", status="start"
+ )
session.notify(content, from_consumer_id=None)
else:
buffer.content += content.content
@@ -62,7 +65,7 @@ def _execute_startup_command(
# Broadcast start message to all sessions
write_to_all_sessions(
- StartupLogs(content="", status="start"), buffer
+ StartupLogsNotification(content="", status="start"), buffer
)
# Execute the command
@@ -79,7 +82,8 @@ def _execute_startup_command(
if process.stdout:
for line in process.stdout:
write_to_all_sessions(
- StartupLogs(content=line, status="append"), buffer
+ StartupLogsNotification(content=line, status="append"),
+ buffer,
)
echo(line, nl=False)
@@ -91,7 +95,8 @@ def _execute_startup_command(
f"\nProcess completed with exit code: {return_code}\n"
)
write_to_all_sessions(
- StartupLogs(content=final_message, status="done"), buffer
+ StartupLogsNotification(content=final_message, status="done"),
+ buffer,
)
echo(final_message)
@@ -99,7 +104,8 @@ def _execute_startup_command(
# Broadcast error message
error_message = f"\nError executing startup command: {str(e)}\n"
write_to_all_sessions(
- StartupLogs(content=error_message, status="done"), buffer
+ StartupLogsNotification(content=error_message, status="done"),
+ buffer,
)
echo(error_message)
diff --git a/marimo/_sql/connection_utils.py b/marimo/_sql/connection_utils.py
index 52b1be8a7d..edbcee9bec 100644
--- a/marimo/_sql/connection_utils.py
+++ b/marimo/_sql/connection_utils.py
@@ -1,7 +1,8 @@
# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
from marimo._data.models import DataSourceConnection, DataTable
-from marimo._messaging.ops import SQLMetadata
+from marimo._messaging.notification import SQLMetadata
def update_table_in_connection(
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index c4b272decc..c798bd3eca 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -184,7 +184,7 @@ components:
- displayed_models
title: AiModelConfig
type: object
- Alert:
+ AlertNotification:
properties:
description:
type: string
@@ -203,7 +203,7 @@ components:
- op
- title
- description
- title: Alert
+ title: AlertNotification
type: object
AnthropicConfig:
description: "Configuration options for Anthropic.\n\n **Keys.**\n\n -\
@@ -214,7 +214,7 @@ components:
required: []
title: AnthropicConfig
type: object
- Banner:
+ BannerNotification:
properties:
action:
anyOf:
@@ -239,7 +239,7 @@ components:
- op
- title
- description
- title: Banner
+ title: BannerNotification
type: object
BaseResponse:
properties:
@@ -279,7 +279,7 @@ components:
required: []
title: BedrockConfig
type: object
- CacheCleared:
+ CacheClearedNotification:
description: Result of clearing cache.
properties:
bytes_freed:
@@ -290,9 +290,9 @@ components:
required:
- op
- bytes_freed
- title: CacheCleared
+ title: CacheClearedNotification
type: object
- CacheInfoFetched:
+ CacheInfoNotification:
description: Cache statistics information.
properties:
disk_to_free:
@@ -305,7 +305,7 @@ components:
type: integer
op:
enum:
- - cache-info-fetched
+ - cache-info
time:
type: number
required:
@@ -315,7 +315,7 @@ components:
- time
- disk_to_free
- disk_total
- title: CacheInfoFetched
+ title: CacheInfoNotification
type: object
CellChannel:
description: The channel of a cell's output.
@@ -347,8 +347,8 @@ components:
required: []
title: CellConfig
type: object
- CellOp:
- description: "Op to transition a cell.\n\n A CellOp's data has some optional\
+ 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\
@@ -404,7 +404,7 @@ components:
required:
- op
- cell_id
- title: CellOp
+ title: CellNotification
type: object
CellOutput:
properties:
@@ -653,7 +653,7 @@ components:
required: []
title: ColumnStats
type: object
- CompletedRun:
+ CompletedRunNotification:
description: Written on run completion (of submitted cells and their descendants.
properties:
op:
@@ -661,7 +661,7 @@ components:
- completed-run
required:
- op
- title: CompletedRun
+ title: CompletedRunNotification
type: object
CompletionConfig:
description: "Configuration for code completion.\n\n A dict with key/value\
@@ -721,7 +721,7 @@ components:
- completion_info
title: CompletionOption
type: object
- CompletionResult:
+ CompletionResultNotification:
description: Code completion result.
properties:
completion_id:
@@ -740,7 +740,7 @@ components:
- completion_id
- prefix_length
- options
- title: CompletionResult
+ title: CompletionResultNotification
type: object
CopyNotebookRequest:
properties:
@@ -795,7 +795,7 @@ components:
- edges_with_vars
title: CycleError
type: object
- DataColumnPreview:
+ DataColumnPreviewNotification:
description: Preview of a column in a dataset.
properties:
chart_code:
@@ -836,7 +836,7 @@ components:
- op
- table_name
- column_name
- title: DataColumnPreview
+ title: DataColumnPreviewNotification
type: object
DataSourceConnection:
description: "Represents a data source connection.\n\nAttributes:\n source\
@@ -879,7 +879,7 @@ components:
- databases
title: DataSourceConnection
type: object
- DataSourceConnections:
+ DataSourceConnectionsNotification:
properties:
connections:
items:
@@ -891,7 +891,7 @@ components:
required:
- op
- connections
- title: DataSourceConnections
+ title: DataSourceConnectionsNotification
type: object
DataTable:
description: "Represents a data table.\n\nAttributes:\n source_type (DataTableSource):\
@@ -1021,7 +1021,7 @@ components:
- schemas
title: Database
type: object
- Datasets:
+ DatasetsNotification:
description: List of datasets.
properties:
clear_channel:
@@ -1043,7 +1043,7 @@ components:
required:
- op
- tables
- title: Datasets
+ title: DatasetsNotification
type: object
DatasourcesConfig:
description: "Configuration for datasources panel.\n\n **Keys.**\n\n -\
@@ -1550,7 +1550,7 @@ components:
- success
title: FileUpdateResponse
type: object
- FocusCell:
+ FocusCellNotification:
properties:
cell_id:
type: string
@@ -1560,7 +1560,7 @@ components:
required:
- op
- cell_id
- title: FocusCell
+ title: FocusCellNotification
type: object
FormatRequest:
properties:
@@ -1612,7 +1612,7 @@ components:
- args
title: FunctionCallRequest
type: object
- FunctionCallResult:
+ FunctionCallResultNotification:
description: Result of calling a function.
properties:
function_call_id:
@@ -1628,7 +1628,7 @@ components:
- function_call_id
- return_value
- status
- title: FunctionCallResult
+ title: FunctionCallResultNotification
type: object
GetCacheInfoRequest:
properties: {}
@@ -1750,7 +1750,7 @@ components:
- versions
title: InstallMissingPackagesRequest
type: object
- InstallingPackageAlert:
+ InstallingPackageAlertNotification:
properties:
log_status:
anyOf:
@@ -1781,7 +1781,7 @@ components:
required:
- op
- packages
- title: InstallingPackageAlert
+ title: InstallingPackageAlertNotification
type: object
InstantiateRequest:
properties:
@@ -1799,7 +1799,7 @@ components:
- values
title: InstantiateRequest
type: object
- Interrupted:
+ InterruptedNotification:
description: Written when the kernel is interrupted by the user.
properties:
op:
@@ -1807,7 +1807,7 @@ components:
- interrupted
required:
- op
- title: Interrupted
+ title: InterruptedNotification
type: object
InvokeAiToolRequest:
properties:
@@ -1838,7 +1838,7 @@ components:
- result
title: InvokeAiToolResponse
type: object
- KernelCapabilities:
+ KernelCapabilitiesNotification:
properties:
basedpyright:
default: false
@@ -1853,15 +1853,15 @@ components:
default: false
type: boolean
required: []
- title: KernelCapabilities
+ title: KernelCapabilitiesNotification
type: object
- KernelReady:
+ KernelReadyNotification:
description: Kernel is ready for execution.
properties:
app_config:
$ref: '#/components/schemas/_AppConfig'
capabilities:
- $ref: '#/components/schemas/KernelCapabilities'
+ $ref: '#/components/schemas/KernelCapabilitiesNotification'
cell_ids:
items:
type: string
@@ -1919,7 +1919,7 @@ components:
- app_config
- kiosk
- capabilities
- title: KernelReady
+ title: KernelReadyNotification
type: object
KeymapConfig:
description: "Configuration for keymaps.\n\n **Keys.**\n\n - `preset`:\
@@ -1989,79 +1989,79 @@ components:
syntax: '#/components/schemas/MarimoSyntaxError'
unknown: '#/components/schemas/UnknownError'
propertyName: type
- operation:
- anyOf:
- - $ref: '#/components/schemas/CellOp'
- - $ref: '#/components/schemas/FunctionCallResult'
- - $ref: '#/components/schemas/SendUIElementMessage'
- - $ref: '#/components/schemas/RemoveUIElements'
- - $ref: '#/components/schemas/Reload'
- - $ref: '#/components/schemas/Reconnected'
- - $ref: '#/components/schemas/Interrupted'
- - $ref: '#/components/schemas/CompletedRun'
- - $ref: '#/components/schemas/KernelReady'
- - $ref: '#/components/schemas/CompletionResult'
- - $ref: '#/components/schemas/Alert'
- - $ref: '#/components/schemas/Banner'
- - $ref: '#/components/schemas/MissingPackageAlert'
- - $ref: '#/components/schemas/InstallingPackageAlert'
- - $ref: '#/components/schemas/StartupLogs'
- - $ref: '#/components/schemas/Variables'
- - $ref: '#/components/schemas/VariableValues'
- - $ref: '#/components/schemas/QueryParamsSet'
- - $ref: '#/components/schemas/QueryParamsAppend'
- - $ref: '#/components/schemas/QueryParamsDelete'
- - $ref: '#/components/schemas/QueryParamsClear'
- - $ref: '#/components/schemas/Datasets'
- - $ref: '#/components/schemas/DataColumnPreview'
- - $ref: '#/components/schemas/SQLTablePreview'
- - $ref: '#/components/schemas/SQLTableListPreview'
- - $ref: '#/components/schemas/DataSourceConnections'
- - $ref: '#/components/schemas/ValidateSQLResult'
- - $ref: '#/components/schemas/SecretKeysResult'
- - $ref: '#/components/schemas/CacheCleared'
- - $ref: '#/components/schemas/CacheInfoFetched'
- - $ref: '#/components/schemas/FocusCell'
- - $ref: '#/components/schemas/UpdateCellCodes'
- - $ref: '#/components/schemas/UpdateCellIdsRequest'
+ notification:
+ anyOf:
+ - $ref: '#/components/schemas/CellNotification'
+ - $ref: '#/components/schemas/FunctionCallResultNotification'
+ - $ref: '#/components/schemas/UIElementMessageNotification'
+ - $ref: '#/components/schemas/RemoveUIElementsNotification'
+ - $ref: '#/components/schemas/ReloadNotification'
+ - $ref: '#/components/schemas/ReconnectedNotification'
+ - $ref: '#/components/schemas/InterruptedNotification'
+ - $ref: '#/components/schemas/CompletedRunNotification'
+ - $ref: '#/components/schemas/KernelReadyNotification'
+ - $ref: '#/components/schemas/CompletionResultNotification'
+ - $ref: '#/components/schemas/AlertNotification'
+ - $ref: '#/components/schemas/BannerNotification'
+ - $ref: '#/components/schemas/MissingPackageAlertNotification'
+ - $ref: '#/components/schemas/InstallingPackageAlertNotification'
+ - $ref: '#/components/schemas/StartupLogsNotification'
+ - $ref: '#/components/schemas/VariablesNotification'
+ - $ref: '#/components/schemas/VariableValuesNotification'
+ - $ref: '#/components/schemas/QueryParamsSetNotification'
+ - $ref: '#/components/schemas/QueryParamsAppendNotification'
+ - $ref: '#/components/schemas/QueryParamsDeleteNotification'
+ - $ref: '#/components/schemas/QueryParamsClearNotification'
+ - $ref: '#/components/schemas/DatasetsNotification'
+ - $ref: '#/components/schemas/DataColumnPreviewNotification'
+ - $ref: '#/components/schemas/SQLTablePreviewNotification'
+ - $ref: '#/components/schemas/SQLTableListPreviewNotification'
+ - $ref: '#/components/schemas/DataSourceConnectionsNotification'
+ - $ref: '#/components/schemas/ValidateSQLResultNotification'
+ - $ref: '#/components/schemas/SecretKeysResultNotification'
+ - $ref: '#/components/schemas/CacheClearedNotification'
+ - $ref: '#/components/schemas/CacheInfoNotification'
+ - $ref: '#/components/schemas/FocusCellNotification'
+ - $ref: '#/components/schemas/UpdateCellCodesNotification'
+ - $ref: '#/components/schemas/UpdateCellIdsNotification'
discriminator:
mapping:
- alert: '#/components/schemas/Alert'
- banner: '#/components/schemas/Banner'
- cache-cleared: '#/components/schemas/CacheCleared'
- cache-info-fetched: '#/components/schemas/CacheInfoFetched'
- cell-op: '#/components/schemas/CellOp'
- completed-run: '#/components/schemas/CompletedRun'
- completion-result: '#/components/schemas/CompletionResult'
- data-column-preview: '#/components/schemas/DataColumnPreview'
- data-source-connections: '#/components/schemas/DataSourceConnections'
- datasets: '#/components/schemas/Datasets'
- focus-cell: '#/components/schemas/FocusCell'
- function-call-result: '#/components/schemas/FunctionCallResult'
- installing-package-alert: '#/components/schemas/InstallingPackageAlert'
- interrupted: '#/components/schemas/Interrupted'
- kernel-ready: '#/components/schemas/KernelReady'
- missing-package-alert: '#/components/schemas/MissingPackageAlert'
- query-params-append: '#/components/schemas/QueryParamsAppend'
- query-params-clear: '#/components/schemas/QueryParamsClear'
- query-params-delete: '#/components/schemas/QueryParamsDelete'
- query-params-set: '#/components/schemas/QueryParamsSet'
- reconnected: '#/components/schemas/Reconnected'
- reload: '#/components/schemas/Reload'
- remove-ui-elements: '#/components/schemas/RemoveUIElements'
- secret-keys-result: '#/components/schemas/SecretKeysResult'
- send-ui-element-message: '#/components/schemas/SendUIElementMessage'
- sql-table-list-preview: '#/components/schemas/SQLTableListPreview'
- sql-table-preview: '#/components/schemas/SQLTablePreview'
- startup-logs: '#/components/schemas/StartupLogs'
- update-cell-codes: '#/components/schemas/UpdateCellCodes'
- update-cell-ids: '#/components/schemas/UpdateCellIdsRequest'
- validate-sql-result: '#/components/schemas/ValidateSQLResult'
- variable-values: '#/components/schemas/VariableValues'
- variables: '#/components/schemas/Variables'
+ alert: '#/components/schemas/AlertNotification'
+ banner: '#/components/schemas/BannerNotification'
+ cache-cleared: '#/components/schemas/CacheClearedNotification'
+ cache-info: '#/components/schemas/CacheInfoNotification'
+ cell-op: '#/components/schemas/CellNotification'
+ completed-run: '#/components/schemas/CompletedRunNotification'
+ completion-result: '#/components/schemas/CompletionResultNotification'
+ data-column-preview: '#/components/schemas/DataColumnPreviewNotification'
+ data-source-connections: '#/components/schemas/DataSourceConnectionsNotification'
+ datasets: '#/components/schemas/DatasetsNotification'
+ focus-cell: '#/components/schemas/FocusCellNotification'
+ function-call-result: '#/components/schemas/FunctionCallResultNotification'
+ installing-package-alert: '#/components/schemas/InstallingPackageAlertNotification'
+ interrupted: '#/components/schemas/InterruptedNotification'
+ kernel-ready: '#/components/schemas/KernelReadyNotification'
+ missing-package-alert: '#/components/schemas/MissingPackageAlertNotification'
+ query-params-append: '#/components/schemas/QueryParamsAppendNotification'
+ query-params-clear: '#/components/schemas/QueryParamsClearNotification'
+ query-params-delete: '#/components/schemas/QueryParamsDeleteNotification'
+ query-params-set: '#/components/schemas/QueryParamsSetNotification'
+ reconnected: '#/components/schemas/ReconnectedNotification'
+ reload: '#/components/schemas/ReloadNotification'
+ remove-ui-elements: '#/components/schemas/RemoveUIElementsNotification'
+ secret-keys-result: '#/components/schemas/SecretKeysResultNotification'
+ send-ui-element-message: '#/components/schemas/UIElementMessageNotification'
+ sql-table-list-preview: '#/components/schemas/SQLTableListPreviewNotification'
+ sql-table-preview: '#/components/schemas/SQLTablePreviewNotification'
+ startup-logs: '#/components/schemas/StartupLogsNotification'
+ update-cell-codes: '#/components/schemas/UpdateCellCodesNotification'
+ update-cell-ids: '#/components/schemas/UpdateCellIdsNotification'
+ validate-sql-result: '#/components/schemas/ValidateSQLResultNotification'
+ variable-values: '#/components/schemas/VariableValuesNotification'
+ variables: '#/components/schemas/VariablesNotification'
propertyName: op
required:
- - operation
+ - notification
- error
- data_type
title: KnownUnions
@@ -2417,7 +2417,7 @@ components:
- msg
title: MarimoSyntaxError
type: object
- MissingPackageAlert:
+ MissingPackageAlertNotification:
properties:
isolated:
type: boolean
@@ -2432,7 +2432,7 @@ components:
- op
- packages
- isolated
- title: MissingPackageAlert
+ title: MissingPackageAlertNotification
type: object
ModelMessage:
properties:
@@ -2670,7 +2670,7 @@ components:
required: []
title: PythonLanguageServerConfig
type: object
- QueryParamsAppend:
+ QueryParamsAppendNotification:
properties:
key:
type: string
@@ -2683,18 +2683,18 @@ components:
- op
- key
- value
- title: QueryParamsAppend
+ title: QueryParamsAppendNotification
type: object
- QueryParamsClear:
+ QueryParamsClearNotification:
properties:
op:
enum:
- query-params-clear
required:
- op
- title: QueryParamsClear
+ title: QueryParamsClearNotification
type: object
- QueryParamsDelete:
+ QueryParamsDeleteNotification:
properties:
key:
type: string
@@ -2709,9 +2709,9 @@ components:
- op
- key
- value
- title: QueryParamsDelete
+ title: QueryParamsDeleteNotification
type: object
- QueryParamsSet:
+ QueryParamsSetNotification:
description: Set query parameters.
properties:
key:
@@ -2729,7 +2729,7 @@ components:
- op
- key
- value
- title: QueryParamsSet
+ title: QueryParamsSetNotification
type: object
ReadCodeResponse:
properties:
@@ -2749,23 +2749,23 @@ components:
- files
title: RecentFilesResponse
type: object
- Reconnected:
+ ReconnectedNotification:
properties:
op:
enum:
- reconnected
required:
- op
- title: Reconnected
+ title: ReconnectedNotification
type: object
- Reload:
+ ReloadNotification:
properties:
op:
enum:
- reload
required:
- op
- title: Reload
+ title: ReloadNotification
type: object
RemovePackageRequest:
properties:
@@ -2780,7 +2780,7 @@ components:
- package
title: RemovePackageRequest
type: object
- RemoveUIElements:
+ RemoveUIElementsNotification:
description: Invalidate UI elements for a given cell.
properties:
cell_id:
@@ -2791,7 +2791,7 @@ components:
required:
- op
- cell_id
- title: RemoveUIElements
+ title: RemoveUIElementsNotification
type: object
RenameFileRequest:
properties:
@@ -2945,7 +2945,7 @@ components:
- schema
title: SQLMetadata
type: object
- SQLTableListPreview:
+ SQLTableListPreviewNotification:
description: Preview of a list of tables in a schema.
properties:
error:
@@ -2969,9 +2969,9 @@ components:
- op
- request_id
- metadata
- title: SQLTableListPreview
+ title: SQLTableListPreviewNotification
type: object
- SQLTablePreview:
+ SQLTablePreviewNotification:
description: Preview of a table in a SQL database.
properties:
error:
@@ -2995,7 +2995,7 @@ components:
- request_id
- metadata
- table
- title: SQLTablePreview
+ title: SQLTablePreviewNotification
type: object
SaveAppConfigurationRequest:
properties:
@@ -3109,7 +3109,7 @@ components:
- columns
title: SchemaTable
type: object
- SecretKeysResult:
+ SecretKeysResultNotification:
description: Result of listing secret keys.
properties:
op:
@@ -3125,7 +3125,7 @@ components:
- op
- request_id
- secrets
- title: SecretKeysResult
+ title: SecretKeysResultNotification
type: object
SecretKeysWithProvider:
properties:
@@ -3145,7 +3145,7 @@ components:
- keys
title: SecretKeysWithProvider
type: object
- SendUIElementMessage:
+ UIElementMessageNotification:
description: Send a message to a UI element.
properties:
buffers:
@@ -3174,7 +3174,7 @@ components:
- ui_element
- model_id
- message
- title: SendUIElementMessage
+ title: UIElementMessageNotification
type: object
ServerConfig:
description: "Configuration for the server.\n\n **Keys.**\n\n - `browser`:\
@@ -3403,7 +3403,7 @@ components:
- errors
title: SqlParseResult
type: object
- StartupLogs:
+ StartupLogsNotification:
properties:
content:
type: string
@@ -3419,7 +3419,7 @@ components:
- op
- content
- status
- title: StartupLogs
+ title: StartupLogsNotification
type: object
StdinRequest:
properties:
@@ -3515,7 +3515,7 @@ components:
- msg
title: UnknownError
type: object
- UpdateCellCodes:
+ UpdateCellCodesNotification:
properties:
cell_ids:
items:
@@ -3535,9 +3535,9 @@ components:
- cell_ids
- codes
- code_is_stale
- title: UpdateCellCodes
+ title: UpdateCellCodesNotification
type: object
- UpdateCellIdsRequest:
+ UpdateCellIdsNotification:
description: 'Update the cell ID ordering of the cells in the notebook.
@@ -3555,6 +3555,16 @@ components:
required:
- op
- cell_ids
+ title: UpdateCellIdsNotification
+ type: object
+ UpdateCellIdsRequest:
+ properties:
+ cellIds:
+ items:
+ type: string
+ type: array
+ required:
+ - cellIds
title: UpdateCellIdsRequest
type: object
UpdateComponentValuesRequest:
@@ -3595,7 +3605,7 @@ components:
- onlyParse
title: ValidateSQLRequest
type: object
- ValidateSQLResult:
+ ValidateSQLResultNotification:
properties:
error:
anyOf:
@@ -3620,7 +3630,7 @@ components:
required:
- op
- request_id
- title: ValidateSQLResult
+ title: ValidateSQLResultNotification
type: object
VariableContext:
properties:
@@ -3635,7 +3645,7 @@ components:
- previewValue
title: VariableContext
type: object
- VariableDeclaration:
+ VariableDeclarationNotification:
properties:
declared_by:
items:
@@ -3651,7 +3661,7 @@ components:
- name
- declared_by
- used_by
- title: VariableDeclaration
+ title: VariableDeclarationNotification
type: object
VariableValue:
properties:
@@ -3671,7 +3681,7 @@ components:
- datatype
title: VariableValue
type: object
- VariableValues:
+ VariableValuesNotification:
description: List of variables and their types/values.
properties:
op:
@@ -3684,9 +3694,9 @@ components:
required:
- op
- variables
- title: VariableValues
+ title: VariableValuesNotification
type: object
- Variables:
+ VariablesNotification:
description: List of variable declarations.
properties:
op:
@@ -3694,12 +3704,12 @@ components:
- variables
variables:
items:
- $ref: '#/components/schemas/VariableDeclaration'
+ $ref: '#/components/schemas/VariableDeclarationNotification'
type: array
required:
- op
- variables
- title: Variables
+ title: VariablesNotification
type: object
WorkspaceFilesRequest:
properties:
@@ -4813,4 +4823,3 @@ paths:
summary: Submit login form
tags:
- auth
-
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 8c094d51d8..7180e6b2ca 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -2888,8 +2888,8 @@ export interface components {
displayed_models: string[];
edit_model?: string;
};
- /** Alert */
- Alert: {
+ /** AlertNotification */
+ AlertNotification: {
description: string;
/** @enum {unknown} */
op: "alert";
@@ -2908,8 +2908,8 @@ export interface components {
AnthropicConfig: {
api_key?: string;
};
- /** Banner */
- Banner: {
+ /** BannerNotification */
+ BannerNotification: {
/** @default null */
action?: "restart" | null;
description: string;
@@ -2951,25 +2951,25 @@ export interface components {
region_name?: string;
};
/**
- * CacheCleared
+ * CacheClearedNotification
* @description Result of clearing cache.
*/
- CacheCleared: {
+ CacheClearedNotification: {
bytes_freed: number;
/** @enum {unknown} */
op: "cache-cleared";
};
/**
- * CacheInfoFetched
+ * CacheInfoNotification
* @description Cache statistics information.
*/
- CacheInfoFetched: {
+ CacheInfoNotification: {
disk_to_free: number;
disk_total: number;
hits: number;
misses: number;
/** @enum {unknown} */
- op: "cache-info-fetched";
+ op: "cache-info";
time: number;
};
/**
@@ -2999,10 +2999,10 @@ export interface components {
hide_code?: boolean;
};
/**
- * CellOp
+ * CellNotification
* @description Op to transition a cell.
*
- * A CellOp's data has some optional fields:
+ * A CellNotification's data has some optional fields:
*
* output - a CellOutput
* console - a CellOutput (console msg to append), or a list of
@@ -3018,7 +3018,7 @@ export interface components {
*
* cell_id - the cell id
*/
- CellOp: {
+ CellNotification: {
cell_id: string;
/** @default null */
console?:
@@ -3161,10 +3161,10 @@ export interface components {
unique?: number | null;
};
/**
- * CompletedRun
+ * CompletedRunNotification
* @description Written on run completion (of submitted cells and their descendants.
*/
- CompletedRun: {
+ CompletedRunNotification: {
/** @enum {unknown} */
op: "completed-run";
};
@@ -3199,10 +3199,10 @@ export interface components {
type: string;
};
/**
- * CompletionResult
+ * CompletionResultNotification
* @description Code completion result.
*/
- CompletionResult: {
+ CompletionResultNotification: {
completion_id: string;
/** @enum {unknown} */
op: "completion-result";
@@ -3229,10 +3229,10 @@ export interface components {
type: "cycle";
};
/**
- * DataColumnPreview
+ * DataColumnPreviewNotification
* @description Preview of a column in a dataset.
*/
- DataColumnPreview: {
+ DataColumnPreviewNotification: {
/** @default null */
chart_code?: string | null;
/** @default null */
@@ -3272,8 +3272,8 @@ export interface components {
name: string;
source: string;
};
- /** DataSourceConnections */
- DataSourceConnections: {
+ /** DataSourceConnectionsNotification */
+ DataSourceConnectionsNotification: {
connections: components["schemas"]["DataSourceConnection"][];
/** @enum {unknown} */
op: "data-source-connections";
@@ -3359,10 +3359,10 @@ export interface components {
schemas: components["schemas"]["Schema"][];
};
/**
- * Datasets
+ * DatasetsNotification
* @description List of datasets.
*/
- Datasets: {
+ DatasetsNotification: {
/** @default null */
clear_channel?: ("catalog" | "connection" | "duckdb" | "local") | null;
/** @enum {unknown} */
@@ -3610,8 +3610,8 @@ export interface components {
message?: string | null;
success: boolean;
};
- /** FocusCell */
- FocusCell: {
+ /** FocusCellNotification */
+ FocusCellNotification: {
cell_id: string;
/** @enum {unknown} */
op: "focus-cell";
@@ -3648,10 +3648,10 @@ export interface components {
namespace: string;
};
/**
- * FunctionCallResult
+ * FunctionCallResultNotification
* @description Result of calling a function.
*/
- FunctionCallResult: {
+ FunctionCallResultNotification: {
function_call_id: string;
/** @enum {unknown} */
op: "function-call-result";
@@ -3739,8 +3739,8 @@ export interface components {
[key: string]: string;
};
};
- /** InstallingPackageAlert */
- InstallingPackageAlert: {
+ /** InstallingPackageAlertNotification */
+ InstallingPackageAlertNotification: {
/** @default null */
log_status?: ("append" | "done" | "start") | null;
/** @default null */
@@ -3761,10 +3761,10 @@ export interface components {
values: unknown[];
};
/**
- * Interrupted
+ * InterruptedNotification
* @description Written when the kernel is interrupted by the user.
*/
- Interrupted: {
+ InterruptedNotification: {
/** @enum {unknown} */
op: "interrupted";
};
@@ -3781,8 +3781,8 @@ export interface components {
success: boolean;
toolName: string;
};
- /** KernelCapabilities */
- KernelCapabilities: {
+ /** KernelCapabilitiesNotification */
+ KernelCapabilitiesNotification: {
/** @default false */
basedpyright?: boolean;
/** @default false */
@@ -3793,12 +3793,12 @@ export interface components {
ty?: boolean;
};
/**
- * KernelReady
+ * KernelReadyNotification
* @description Kernel is ready for execution.
*/
- KernelReady: {
+ KernelReadyNotification: {
app_config: components["schemas"]["_AppConfig"];
- capabilities: components["schemas"]["KernelCapabilities"];
+ capabilities: components["schemas"]["KernelCapabilitiesNotification"];
cell_ids: string[];
codes: string[];
configs: components["schemas"]["CellConfig"][];
@@ -3862,40 +3862,40 @@ export interface components {
| components["schemas"]["MarimoInternalError"]
| components["schemas"]["MarimoSQLError"]
| components["schemas"]["UnknownError"];
- operation:
- | components["schemas"]["CellOp"]
- | components["schemas"]["FunctionCallResult"]
- | components["schemas"]["SendUIElementMessage"]
- | components["schemas"]["RemoveUIElements"]
- | components["schemas"]["Reload"]
- | components["schemas"]["Reconnected"]
- | components["schemas"]["Interrupted"]
- | components["schemas"]["CompletedRun"]
- | components["schemas"]["KernelReady"]
- | components["schemas"]["CompletionResult"]
- | components["schemas"]["Alert"]
- | components["schemas"]["Banner"]
- | components["schemas"]["MissingPackageAlert"]
- | components["schemas"]["InstallingPackageAlert"]
- | components["schemas"]["StartupLogs"]
- | components["schemas"]["Variables"]
- | components["schemas"]["VariableValues"]
- | components["schemas"]["QueryParamsSet"]
- | components["schemas"]["QueryParamsAppend"]
- | components["schemas"]["QueryParamsDelete"]
- | components["schemas"]["QueryParamsClear"]
- | components["schemas"]["Datasets"]
- | components["schemas"]["DataColumnPreview"]
- | components["schemas"]["SQLTablePreview"]
- | components["schemas"]["SQLTableListPreview"]
- | components["schemas"]["DataSourceConnections"]
- | components["schemas"]["ValidateSQLResult"]
- | components["schemas"]["SecretKeysResult"]
- | components["schemas"]["CacheCleared"]
- | components["schemas"]["CacheInfoFetched"]
- | components["schemas"]["FocusCell"]
- | components["schemas"]["UpdateCellCodes"]
- | components["schemas"]["UpdateCellIdsRequest"];
+ notification:
+ | components["schemas"]["CellNotification"]
+ | components["schemas"]["FunctionCallResultNotification"]
+ | components["schemas"]["UIElementMessageNotification"]
+ | components["schemas"]["RemoveUIElementsNotification"]
+ | components["schemas"]["ReloadNotification"]
+ | components["schemas"]["ReconnectedNotification"]
+ | components["schemas"]["InterruptedNotification"]
+ | components["schemas"]["CompletedRunNotification"]
+ | components["schemas"]["KernelReadyNotification"]
+ | components["schemas"]["CompletionResultNotification"]
+ | components["schemas"]["AlertNotification"]
+ | components["schemas"]["BannerNotification"]
+ | components["schemas"]["MissingPackageAlertNotification"]
+ | components["schemas"]["InstallingPackageAlertNotification"]
+ | components["schemas"]["StartupLogsNotification"]
+ | components["schemas"]["VariablesNotification"]
+ | components["schemas"]["VariableValuesNotification"]
+ | components["schemas"]["QueryParamsSetNotification"]
+ | components["schemas"]["QueryParamsAppendNotification"]
+ | components["schemas"]["QueryParamsDeleteNotification"]
+ | components["schemas"]["QueryParamsClearNotification"]
+ | components["schemas"]["DatasetsNotification"]
+ | components["schemas"]["DataColumnPreviewNotification"]
+ | components["schemas"]["SQLTablePreviewNotification"]
+ | components["schemas"]["SQLTableListPreviewNotification"]
+ | components["schemas"]["DataSourceConnectionsNotification"]
+ | components["schemas"]["ValidateSQLResultNotification"]
+ | components["schemas"]["SecretKeysResultNotification"]
+ | components["schemas"]["CacheClearedNotification"]
+ | components["schemas"]["CacheInfoNotification"]
+ | components["schemas"]["FocusCellNotification"]
+ | components["schemas"]["UpdateCellCodesNotification"]
+ | components["schemas"]["UpdateCellIdsNotification"];
};
/**
* LanguageServersConfig
@@ -4073,8 +4073,8 @@ export interface components {
/** @enum {unknown} */
type: "syntax";
};
- /** MissingPackageAlert */
- MissingPackageAlert: {
+ /** MissingPackageAlertNotification */
+ MissingPackageAlertNotification: {
isolated: boolean;
/** @enum {unknown} */
op: "missing-package-alert";
@@ -4216,30 +4216,30 @@ export interface components {
enable_ruff?: boolean;
enabled?: boolean;
};
- /** QueryParamsAppend */
- QueryParamsAppend: {
+ /** QueryParamsAppendNotification */
+ QueryParamsAppendNotification: {
key: string;
/** @enum {unknown} */
op: "query-params-append";
value: string;
};
- /** QueryParamsClear */
- QueryParamsClear: {
+ /** QueryParamsClearNotification */
+ QueryParamsClearNotification: {
/** @enum {unknown} */
op: "query-params-clear";
};
- /** QueryParamsDelete */
- QueryParamsDelete: {
+ /** QueryParamsDeleteNotification */
+ QueryParamsDeleteNotification: {
key: string;
/** @enum {unknown} */
op: "query-params-delete";
value: string | null;
};
/**
- * QueryParamsSet
+ * QueryParamsSetNotification
* @description Set query parameters.
*/
- QueryParamsSet: {
+ QueryParamsSetNotification: {
key: string;
/** @enum {unknown} */
op: "query-params-set";
@@ -4253,13 +4253,13 @@ export interface components {
RecentFilesResponse: {
files: components["schemas"]["MarimoFile"][];
};
- /** Reconnected */
- Reconnected: {
+ /** ReconnectedNotification */
+ ReconnectedNotification: {
/** @enum {unknown} */
op: "reconnected";
};
- /** Reload */
- Reload: {
+ /** ReloadNotification */
+ ReloadNotification: {
/** @enum {unknown} */
op: "reload";
};
@@ -4270,10 +4270,10 @@ export interface components {
package: string;
};
/**
- * RemoveUIElements
+ * RemoveUIElementsNotification
* @description Invalidate UI elements for a given cell.
*/
- RemoveUIElements: {
+ RemoveUIElementsNotification: {
cell_id: string;
/** @enum {unknown} */
op: "remove-ui-elements";
@@ -4372,10 +4372,10 @@ export interface components {
type: "sql-metadata";
};
/**
- * SQLTableListPreview
+ * SQLTableListPreviewNotification
* @description Preview of a list of tables in a schema.
*/
- SQLTableListPreview: {
+ SQLTableListPreviewNotification: {
/** @default null */
error?: string | null;
metadata: components["schemas"]["SQLMetadata"];
@@ -4386,10 +4386,10 @@ export interface components {
tables?: components["schemas"]["DataTable"][];
};
/**
- * SQLTablePreview
+ * SQLTablePreviewNotification
* @description Preview of a table in a SQL database.
*/
- SQLTablePreview: {
+ SQLTablePreviewNotification: {
/** @default null */
error?: string | null;
metadata: components["schemas"]["SQLMetadata"];
@@ -4451,10 +4451,10 @@ export interface components {
name: string;
};
/**
- * SecretKeysResult
+ * SecretKeysResultNotification
* @description Result of listing secret keys.
*/
- SecretKeysResult: {
+ SecretKeysResultNotification: {
/** @enum {unknown} */
op: "secret-keys-result";
request_id: string;
@@ -4468,10 +4468,10 @@ export interface components {
provider: "dotenv" | "env";
};
/**
- * SendUIElementMessage
+ * UIElementMessageNotification
* @description Send a message to a UI element.
*/
- SendUIElementMessage: {
+ UIElementMessageNotification: {
/** @default null */
buffers?: string[] | null;
message: Record<string, any>;
@@ -4609,8 +4609,8 @@ export interface components {
errors: components["schemas"]["SqlParseError"][];
success: boolean;
};
- /** StartupLogs */
- StartupLogs: {
+ /** StartupLogsNotification */
+ StartupLogsNotification: {
content: string;
/** @enum {unknown} */
op: "startup-logs";
@@ -4667,8 +4667,8 @@ export interface components {
/** @enum {unknown} */
type: "unknown";
};
- /** UpdateCellCodes */
- UpdateCellCodes: {
+ /** UpdateCellCodesNotification */
+ UpdateCellCodesNotification: {
cell_ids: string[];
code_is_stale: boolean;
codes: string[];
@@ -4676,17 +4676,21 @@ export interface components {
op: "update-cell-codes";
};
/**
- * UpdateCellIdsRequest
+ * UpdateCellIdsNotification
* @description Update the cell ID ordering of the cells in the notebook.
*
* Right now we send the entire list of cell IDs,
* but in the future we might want to send change-deltas.
*/
- UpdateCellIdsRequest: {
+ UpdateCellIdsNotification: {
cell_ids: string[];
/** @enum {unknown} */
op: "update-cell-ids";
};
+ /** UpdateCellIdsRequest */
+ UpdateCellIdsRequest: {
+ cellIds: string[];
+ };
/** UpdateComponentValuesRequest */
UpdateComponentValuesRequest: {
objectIds: string[];
@@ -4705,8 +4709,8 @@ export interface components {
query: string;
requestId: string;
};
- /** ValidateSQLResult */
- ValidateSQLResult: {
+ /** ValidateSQLResultNotification */
+ ValidateSQLResultNotification: {
/** @default null */
error?: string | null;
/** @enum {unknown} */
@@ -4723,8 +4727,8 @@ export interface components {
previewValue: unknown;
valueType: string;
};
- /** VariableDeclaration */
- VariableDeclaration: {
+ /** VariableDeclarationNotification */
+ VariableDeclarationNotification: {
declared_by: string[];
name: string;
used_by: string[];
@@ -4736,22 +4740,22 @@ export interface components {
value: string | null;
};
/**
- * VariableValues
+ * VariableValuesNotification
* @description List of variables and their types/values.
*/
- VariableValues: {
+ VariableValuesNotification: {
/** @enum {unknown} */
op: "variable-values";
variables: components["schemas"]["VariableValue"][];
};
/**
- * Variables
+ * VariablesNotification
* @description List of variable declarations.
*/
- Variables: {
+ VariablesNotification: {
/** @enum {unknown} */
op: "variables";
- variables: components["schemas"]["VariableDeclaration"][];
+ variables: components["schemas"]["VariableDeclarationNotification"][];
};
/** WorkspaceFilesRequest */
WorkspaceFilesRequest: {
diff --git a/scripts/generate_schemas.py b/scripts/generate_schemas.py
index e6beac46fe..fb51e90295 100755
--- a/scripts/generate_schemas.py
+++ b/scripts/generate_schemas.py
@@ -9,7 +9,7 @@ with app.setup:
import marimo as mo
import marimo._schemas.session as s
import marimo._schemas.notebook as n
- import marimo._messaging.ops as o
+ import marimo._messaging.notification as o
import typing as t
SESSION_MESSAGES = [
@@ -32,39 +32,39 @@ with app.setup:
]
OPS_MESSAGES = [
# Message operations
- o.CellOp,
- o.FunctionCallResult,
- o.RemoveUIElements,
- o.SendUIElementMessage,
- o.Interrupted,
- o.CompletedRun,
- o.KernelReady,
- o.CompletionResult,
- o.Alert,
- o.MissingPackageAlert,
- o.InstallingPackageAlert,
- o.Reconnected,
- o.StartupLogs,
- o.Banner,
- o.Reload,
- o.Variables,
- o.VariableValues,
- o.Datasets,
- o.SQLTablePreview,
- o.SQLTableListPreview,
- o.DataColumnPreview,
- o.DataSourceConnections,
- o.ValidateSQLResult,
- o.QueryParamsSet,
- o.QueryParamsAppend,
- o.QueryParamsDelete,
- o.QueryParamsClear,
- o.FocusCell,
- o.UpdateCellCodes,
- o.SecretKeysResult,
- o.CacheCleared,
- o.CacheInfoFetched,
- o.UpdateCellIdsRequest,
+ o.CellNotification,
+ o.FunctionCallResultNotification,
+ o.RemoveUIElementsNotification,
+ o.UIElementMessageNotification,
+ o.InterruptedNotification,
+ o.CompletedRunNotification,
+ o.KernelReadyNotification,
+ o.CompletionResultNotification,
+ o.AlertNotification,
+ o.MissingPackageAlertNotification,
+ o.InstallingPackageAlertNotification,
+ o.ReconnectedNotification,
+ o.StartupLogsNotification,
+ o.BannerNotification,
+ o.ReloadNotification,
+ o.VariablesNotification,
+ o.VariableValuesNotification,
+ o.DatasetsNotification,
+ o.SQLTablePreviewNotification,
+ o.SQLTableListPreviewNotification,
+ o.DataColumnPreviewNotification,
+ o.DataSourceConnectionsNotification,
+ o.ValidateSQLResultNotification,
+ o.QueryParamsSetNotification,
+ o.QueryParamsAppendNotification,
+ o.QueryParamsDeleteNotification,
+ o.QueryParamsClearNotification,
+ o.FocusCellNotification,
+ o.UpdateCellCodesNotification,
+ o.SecretKeysResultNotification,
+ o.CacheClearedNotification,
+ o.CacheInfoNotification,
+ o.UpdateCellIdsNotification,
]
diff --git a/tests/_ai/tools/test_base.py b/tests/_ai/tools/test_base.py
index 081b26fbe8..13a9ed22f8 100644
--- a/tests/_ai/tools/test_base.py
+++ b/tests/_ai/tools/test_base.py
@@ -139,7 +139,7 @@ def test_get_notebook_errors_orders_by_cell_manager():
context = ToolContext()
- # Mock error cell_op
+ # Mock error cell_notification
error_op = Mock()
error_op.output = Mock()
error_op.output.channel = CellChannel.MARIMO_ERROR
@@ -149,7 +149,7 @@ def test_get_notebook_errors_orders_by_cell_manager():
# Mock session with cells c1, c2, c3
session = Mock()
session_view = Mock()
- session_view.cell_operations = {
+ session_view.cell_notifications = {
CellId_t("c1"): error_op,
CellId_t("c2"): error_op,
CellId_t("c3"): error_op,
@@ -187,16 +187,18 @@ def test_get_cell_errors_extracts_from_output():
context = ToolContext()
- # Mock cell_op with error
- cell_op = Mock()
- cell_op.output = Mock()
- cell_op.output.channel = CellChannel.MARIMO_ERROR
- cell_op.output.data = [
+ # Mock cell_notification with error
+ cell_notification = Mock()
+ cell_notification.output = Mock()
+ cell_notification.output.channel = CellChannel.MARIMO_ERROR
+ cell_notification.output.data = [
{"type": "ValueError", "msg": "bad value", "traceback": ["line 1"]}
]
errors = context.get_cell_errors(
- SessionId("test"), CellId_t("c1"), maybe_cell_op=cell_op
+ SessionId("test"),
+ CellId_t("c1"),
+ maybe_cell_notif=cell_notification,
)
assert len(errors) == 1
@@ -213,7 +215,7 @@ def test_get_cell_console_outputs_separates_stdout_stderr():
context = ToolContext()
- # Mock cell_op with stdout and stderr
+ # Mock cell_notification with stdout and stderr
stdout_output = Mock()
stdout_output.channel = CellChannel.STDOUT
stdout_output.data = "hello"
@@ -222,10 +224,10 @@ def test_get_cell_console_outputs_separates_stdout_stderr():
stderr_output.channel = CellChannel.STDERR
stderr_output.data = "warning"
- cell_op = Mock()
- cell_op.console = [stdout_output, stderr_output]
+ cell_notification = Mock()
+ cell_notification.console = [stdout_output, stderr_output]
- result = context.get_cell_console_outputs(cell_op)
+ result = context.get_cell_console_outputs(cell_notification)
assert len(result.stdout) == 1
assert "hello" in result.stdout[0]
diff --git a/tests/_ai/tools/test_utils.py b/tests/_ai/tools/test_utils.py
index 07f1eaee34..73c1c79125 100644
--- a/tests/_ai/tools/test_utils.py
+++ b/tests/_ai/tools/test_utils.py
@@ -11,14 +11,14 @@ from typing import Any
class MockSessionView:
"""Mock session view for testing."""
- cell_operations: dict | None = None
+ cell_notifications: dict | None = None
last_execution_time: dict | None = None
variable_values: dict | None = None
data_connectors: Any = None
def __post_init__(self) -> None:
- if self.cell_operations is None:
- self.cell_operations = {}
+ if self.cell_notifications is None:
+ self.cell_notifications = {}
if self.last_execution_time is None:
self.last_execution_time = {}
if self.variable_values is None:
diff --git a/tests/_ai/tools/tools/test_cells.py b/tests/_ai/tools/tools/test_cells.py
index 7e925b4a54..0d9fd5d6f8 100644
--- a/tests/_ai/tools/tools/test_cells.py
+++ b/tests/_ai/tools/tools/test_cells.py
@@ -13,13 +13,13 @@ from marimo._ai._tools.tools.cells import (
GetCellRuntimeData,
GetLightweightCellMap,
)
-from marimo._messaging.ops import VariableValue
+from marimo._messaging.notification import VariableValue
from marimo._types.ids import CellId_t, SessionId
from tests._ai.tools.test_utils import MockSession, MockSessionView
@dataclass
-class MockCellOp:
+class MockCellNotification:
output: object | None = None
console: object | None = None
status: object | None = None
@@ -56,10 +56,11 @@ def test_is_markdown_cell():
def test_get_cell_metadata_basic():
tool = GetCellRuntimeData(ToolContext())
- cell_op = MockCellOp(status="idle")
+ cell_notification = MockCellNotification(status="idle")
session = MockSession(
_session_view=MockSessionView(
- cell_operations={"c1": cell_op}, last_execution_time={"c1": 42.5}
+ cell_notifications={"c1": cell_notification},
+ last_execution_time={"c1": 42.5},
)
)
@@ -69,7 +70,7 @@ def test_get_cell_metadata_basic():
)
-def test_get_cell_metadata_no_cell_op():
+def test_get_cell_metadata_no_cell_notification():
tool = GetCellRuntimeData(ToolContext())
session = MockSession(_session_view=MockSessionView())
@@ -157,17 +158,17 @@ def test_get_cell_runtime_data_invalid_cell():
def test_get_visual_output_with_html():
tool = GetCellOutputs(ToolContext())
output = MockOutput(data="<div>test</div>", mimetype="text/html")
- cell_op = MockCellOp(output=output)
+ cell_notification = MockCellNotification(output=output)
- visual_output, mimetype = tool._get_visual_output(cell_op) # type: ignore[arg-type]
+ visual_output, mimetype = tool._get_visual_output(cell_notification) # type: ignore[arg-type]
assert visual_output == "<div>test</div>"
assert mimetype == "text/html"
def test_get_visual_output_no_output():
tool = GetCellOutputs(ToolContext())
- cell_op = MockCellOp(output=None)
+ cell_notification = MockCellNotification(output=None)
- visual_output, mimetype = tool._get_visual_output(cell_op) # type: ignore[arg-type]
+ visual_output, mimetype = tool._get_visual_output(cell_notification) # type: ignore[arg-type]
assert visual_output is None
assert mimetype is None
diff --git a/tests/_ai/tools/tools/test_datasource_tool.py b/tests/_ai/tools/tools/test_datasource_tool.py
index c265a25d81..89b05cf222 100644
--- a/tests/_ai/tools/tools/test_datasource_tool.py
+++ b/tests/_ai/tools/tools/test_datasource_tool.py
@@ -15,7 +15,7 @@ from marimo._ai._tools.tools.datasource import (
)
from marimo._ai._tools.utils.exceptions import ToolExecutionError
from marimo._data.models import Database, DataTable, DataTableColumn, Schema
-from marimo._messaging.ops import DataSourceConnections
+from marimo._messaging.notification import DataSourceConnectionsNotification
from marimo._sql.engines.duckdb import INTERNAL_DUCKDB_ENGINE
from tests._ai.tools.test_utils import MockSession, MockSessionView
@@ -89,7 +89,7 @@ def sample_session(sample_connection: MockDataSourceConnection) -> MockSession:
"""Sample session with data connectors."""
return MockSession(
_session_view=MockSessionView(
- data_connectors=DataSourceConnections(
+ data_connectors=DataSourceConnectionsNotification(
connections=[sample_connection]
)
)
@@ -146,7 +146,9 @@ def multi_table_session() -> MockSession:
return MockSession(
_session_view=MockSessionView(
- data_connectors=DataSourceConnections(connections=[connection])
+ data_connectors=DataSourceConnectionsNotification(
+ connections=[connection]
+ )
)
)
@@ -263,7 +265,7 @@ def test_get_tables_empty_connections(tool: GetDatabaseTables):
"""Test getting tables when no connections exist."""
empty_session = MockSession(
_session_view=MockSessionView(
- data_connectors=DataSourceConnections(connections=[])
+ data_connectors=DataSourceConnectionsNotification(connections=[])
)
)
@@ -370,7 +372,9 @@ def test_multiple_connections(tool: GetDatabaseTables):
multi_conn_session = MockSession(
_session_view=MockSessionView(
- data_connectors=DataSourceConnections(connections=[conn1, conn2])
+ data_connectors=DataSourceConnectionsNotification(
+ connections=[conn1, conn2]
+ )
)
)
@@ -436,7 +440,9 @@ def test_query_matches_multiple_levels(tool: GetDatabaseTables):
session = MockSession(
_session_view=MockSessionView(
- data_connectors=DataSourceConnections(connections=[connection])
+ data_connectors=DataSourceConnectionsNotification(
+ connections=[connection]
+ )
)
)
@@ -520,7 +526,9 @@ def test_query_no_duplicates(tool: GetDatabaseTables):
session = MockSession(
_session_view=MockSessionView(
- data_connectors=DataSourceConnections(connections=[connection])
+ data_connectors=DataSourceConnectionsNotification(
+ connections=[connection]
+ )
)
)
diff --git a/tests/_ai/tools/tools/test_errors_tool.py b/tests/_ai/tools/tools/test_errors_tool.py
index 2bb8f6578f..88f48bcead 100644
--- a/tests/_ai/tools/tools/test_errors_tool.py
+++ b/tests/_ai/tools/tools/test_errors_tool.py
@@ -15,7 +15,7 @@ from marimo._types.ids import CellId_t, SessionId
@dataclass
-class MockCellOp:
+class MockCellNotification:
output: object | None = None
console: object | None = None
@@ -39,12 +39,12 @@ class MockUpdateCellIdsRequest:
@dataclass
class MockSessionView:
- cell_operations: dict | None = None
+ cell_notifications: dict | None = None
cell_ids: MockUpdateCellIdsRequest | None = None
def __post_init__(self) -> None:
- if self.cell_operations is None:
- self.cell_operations = {}
+ if self.cell_notifications is None:
+ self.cell_notifications = {}
@dataclass
diff --git a/tests/_ai/tools/tools/test_tables_variables.py b/tests/_ai/tools/tools/test_tables_variables.py
index bdd8a593bb..5d8505144e 100644
--- a/tests/_ai/tools/tools/test_tables_variables.py
+++ b/tests/_ai/tools/tools/test_tables_variables.py
@@ -11,7 +11,7 @@ from marimo._ai._tools.tools.tables_and_variables import (
TablesAndVariablesOutput,
)
from marimo._data.models import DataTableColumn
-from marimo._messaging.ops import VariableValue
+from marimo._messaging.notification import VariableValue
from marimo._server.sessions import Session
diff --git a/tests/_messaging/mocks.py b/tests/_messaging/mocks.py
index db4d676631..93ef7affd8 100644
--- a/tests/_messaging/mocks.py
+++ b/tests/_messaging/mocks.py
@@ -3,9 +3,9 @@ from __future__ import annotations
from typing import Any, Optional
from marimo._messaging.mimetypes import ConsoleMimeType
-from marimo._messaging.ops import (
- CellOp,
- MessageOperation,
+from marimo._messaging.notification import (
+ CellNotification,
+ NotificationMessage,
)
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage, Stderr, Stream
@@ -30,14 +30,18 @@ class MockStream(Stream):
return [json.loads(op_data) for op_data in self.messages]
@property
- def parsed_operations(self) -> list[MessageOperation]:
+ def parsed_operations(self) -> list[NotificationMessage]:
return [
deserialize_kernel_message(op_data) for op_data in self.messages
]
@property
- def cell_ops(self) -> list[CellOp]:
- return [op for op in self.parsed_operations if isinstance(op, CellOp)]
+ def cell_notifications(self) -> list[CellNotification]:
+ return [
+ op
+ for op in self.parsed_operations
+ if isinstance(op, CellNotification)
+ ]
class MockStderr(Stderr):
diff --git a/tests/_messaging/test_ops.py b/tests/_messaging/test_notifications.py
similarity index 83%
rename from tests/_messaging/test_ops.py
rename to tests/_messaging/test_notifications.py
index 9e1dd31c30..5621f18c47 100644
--- a/tests/_messaging/test_ops.py
+++ b/tests/_messaging/test_notifications.py
@@ -4,16 +4,16 @@ from __future__ import annotations
from unittest.mock import MagicMock
from marimo._ast.toplevel import HINT_UNPARSABLE, TopLevelStatus
+from marimo._messaging.notification import (
+ CellNotification,
+ InstallingPackageAlertNotification,
+ StartupLogsNotification,
+ UIElementMessageNotification,
+ VariableValue,
+)
from marimo._messaging.notification_utils import (
CellNotificationUtils,
- broadcast_op,
-)
-from marimo._messaging.ops import (
- CellOp,
- InstallingPackageAlert,
- SendUIElementMessage,
- StartupLogs,
- VariableValue,
+ broadcast_notification,
)
from marimo._output.hypertext import Html
from marimo._plugins.ui._impl.input import slider
@@ -61,13 +61,17 @@ def test_broadcast_serialization() -> None:
assert len(stream.messages) == 1
assert stream.operations[0]["serialization"] == str(HINT_UNPARSABLE)
- cell_op = stream.operations[0]
+ cell_notification = stream.operations[0]
- assert isinstance(parse_raw(cell_op, CellOp), CellOp)
+ assert isinstance(
+ parse_raw(cell_notification, CellNotification), CellNotification
+ )
def test_startup_logs_creation() -> None:
- startup_log = StartupLogs(content="Starting up...", status="start")
+ startup_log = StartupLogsNotification(
+ content="Starting up...", status="start"
+ )
assert startup_log.name == "startup-logs"
assert startup_log.content == "Starting up..."
assert startup_log.status == "start"
@@ -75,14 +79,16 @@ def test_startup_logs_creation() -> None:
def test_startup_logs_all_statuses() -> None:
for status in ["start", "append", "done"]:
- startup_log = StartupLogs(content=f"Test {status}", status=status)
+ startup_log = StartupLogsNotification(
+ content=f"Test {status}", status=status
+ )
assert startup_log.status == status
assert startup_log.content == f"Test {status}"
def test_installing_package_alert_basic() -> None:
"""Test basic InstallingPackageAlert without streaming logs."""
- alert = InstallingPackageAlert(
+ alert = InstallingPackageAlertNotification(
packages={"numpy": "queued", "pandas": "installing"}
)
assert alert.name == "installing-package-alert"
@@ -96,7 +102,7 @@ def test_installing_package_alert_with_logs() -> None:
packages = {"numpy": "installing"}
logs = {"numpy": "Installing numpy...\n"}
- alert = InstallingPackageAlert(
+ alert = InstallingPackageAlertNotification(
packages=packages, logs=logs, log_status="start"
)
@@ -110,14 +116,14 @@ def test_send_ui_element_message_broadcast() -> None:
"""Test SendUIElementMessage broadcasting and serialization."""
stream = MockStream()
- msg = SendUIElementMessage(
+ msg = UIElementMessageNotification(
ui_element="test_element",
model_id=None,
message={"action": "update", "value": 42},
buffers=[b"buffer1", b"buffer2"],
)
- broadcast_op(msg, stream)
+ broadcast_notification(msg, stream)
assert len(stream.messages) == 1
diff --git a/tests/_messaging/test_serde.py b/tests/_messaging/test_serde.py
index 1863527767..3830eda8b4 100644
--- a/tests/_messaging/test_serde.py
+++ b/tests/_messaging/test_serde.py
@@ -6,14 +6,14 @@ import json
import msgspec
import pytest
-from marimo._messaging.ops import (
- Alert,
- CompletedRun,
- Interrupted,
+from marimo._messaging.notification import (
+ AlertNotification,
+ CompletedRunNotification,
+ InterruptedNotification,
)
from marimo._messaging.serde import (
deserialize_kernel_message,
- deserialize_kernel_operation_name,
+ deserialize_kernel_notification_name,
serialize_kernel_message,
)
from marimo._messaging.types import KernelMessage
@@ -22,7 +22,7 @@ from marimo._messaging.types import KernelMessage
class TestSerializeKernelMessage:
def test_serialize_interrupted(self) -> None:
"""Test serializing an Interrupted message."""
- message = Interrupted()
+ message = InterruptedNotification()
result = serialize_kernel_message(message)
@@ -33,7 +33,7 @@ class TestSerializeKernelMessage:
def test_serialize_alert(self) -> None:
"""Test serializing an Alert message."""
- message = Alert(
+ message = AlertNotification(
title="Test Alert",
description="This is a test alert",
variant="danger",
@@ -59,7 +59,7 @@ class TestDeserializeKernelMessage:
result = deserialize_kernel_message(kernel_message)
- assert isinstance(result, Interrupted)
+ assert isinstance(result, InterruptedNotification)
def test_deserialize_alert(self) -> None:
"""Test deserializing an Alert message."""
@@ -74,7 +74,7 @@ class TestDeserializeKernelMessage:
result = deserialize_kernel_message(kernel_message)
- assert isinstance(result, Alert)
+ assert isinstance(result, AlertNotification)
assert result.title == "Test Alert"
assert result.description == "This is a test alert"
assert result.variant == "danger"
@@ -111,16 +111,16 @@ class TestDeserializeKernelMessage:
class TestRoundTripSerialization:
def test_round_trip_interrupted(self) -> None:
"""Test round-trip for Interrupted message."""
- original = Interrupted()
+ original = InterruptedNotification()
serialized = serialize_kernel_message(original)
deserialized = deserialize_kernel_message(serialized)
- assert isinstance(deserialized, Interrupted)
+ assert isinstance(deserialized, InterruptedNotification)
def test_round_trip_alert(self) -> None:
"""Test round-trip for Alert message."""
- original = Alert(
+ original = AlertNotification(
title="Warning",
description="Something went wrong",
variant="danger",
@@ -129,14 +129,14 @@ class TestRoundTripSerialization:
serialized = serialize_kernel_message(original)
deserialized = deserialize_kernel_message(serialized)
- assert isinstance(deserialized, Alert)
+ assert isinstance(deserialized, AlertNotification)
assert deserialized.title == original.title
assert deserialized.description == original.description
assert deserialized.variant == original.variant
def test_round_trip_with_unicode(self) -> None:
"""Test round-trip with unicode characters."""
- original = Alert(
+ original = AlertNotification(
title="测试标题",
description="Тестовое описание with émojis 🚀",
variant="danger",
@@ -145,14 +145,13 @@ class TestRoundTripSerialization:
serialized = serialize_kernel_message(original)
deserialized = deserialize_kernel_message(serialized)
- assert isinstance(deserialized, Alert)
+ assert isinstance(deserialized, AlertNotification)
assert deserialized.title == original.title
assert deserialized.description == original.description
assert deserialized.variant == original.variant
-def test_deserialize_kernel_operation_name() -> None:
- """Test deserializing a KernelOperationName message."""
- original = CompletedRun()
+def test_deserialize_kernel_notification_name() -> None:
+ original = CompletedRunNotification()
serialized = serialize_kernel_message(original)
- assert deserialize_kernel_operation_name(serialized) == "completed-run"
+ assert deserialize_kernel_notification_name(serialized) == "completed-run"
diff --git a/tests/_plugins/ui/_impl/test_comm.py b/tests/_plugins/ui/_impl/test_comm.py
index 8e63978148..1709b82f06 100644
--- a/tests/_plugins/ui/_impl/test_comm.py
+++ b/tests/_plugins/ui/_impl/test_comm.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from unittest.mock import MagicMock, patch
import pytest
@@ -164,7 +166,7 @@ def test_comm_flush(comm: MarimoComm):
)
with patch(
- "marimo._messaging.ops.SendUIElementMessage"
+ "marimo._messaging.notification.UIElementMessageNotification"
) as MockSendUIElementMessage:
comm.flush()
MockSendUIElementMessage.assert_called_once()
diff --git a/tests/_runtime/output/test_output.py b/tests/_runtime/output/test_output.py
index cccbfbc77c..7c2f33aa24 100644
--- a/tests/_runtime/output/test_output.py
+++ b/tests/_runtime/output/test_output.py
@@ -1,7 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from marimo._messaging.ops import CellOp
+from marimo._messaging.notification import CellNotification
from marimo._runtime import output
from tests.conftest import ExecReqProvider, MockedKernel
@@ -25,7 +25,7 @@ async def test_spinner_removed(
found_progress = False
for i, msg in enumerate(mocked_kernel.stream.operations):
if (
- isinstance(msg, CellOp)
+ isinstance(msg, CellNotification)
and msg.output is not None
and "marimo-progress" in msg.output.data
):
@@ -59,7 +59,7 @@ async def test_mutating_appended_outputs(
)
outputs: list[str] = []
for msg in mocked_kernel.stream.operations:
- if isinstance(msg, CellOp) and msg.output is not None:
+ if isinstance(msg, CellNotification) and msg.output is not None:
outputs.append(str(msg.output.data))
assert len(outputs) == 2
assert "before" in outputs[0]
@@ -84,7 +84,7 @@ async def test_nested_output(
)
outputs: list[str] = []
for msg in mocked_kernel.stream.operations:
- if isinstance(msg, CellOp) and msg.output is not None:
+ if isinstance(msg, CellNotification) and msg.output is not None:
outputs.append(str(msg.output.data))
assert len(outputs) == 1
assert outputs[0] == "['hi', [...], [...], [...], [...], [...]]"
diff --git a/tests/_runtime/test_complete.py b/tests/_runtime/test_complete.py
index 5e1027320d..dc817ff030 100644
--- a/tests/_runtime/test_complete.py
+++ b/tests/_runtime/test_complete.py
@@ -13,7 +13,7 @@ import pytest
import marimo
from marimo._dependencies.dependencies import DependencyManager
-from marimo._messaging.ops import CompletionResult
+from marimo._messaging.notification import CompletionResultNotification
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage, Stream
from marimo._runtime.complete import (
@@ -490,7 +490,7 @@ mixed_keys = {"static_key": "foo", str(random.randint(0, 10)): "bar"}
options_values = [option["name"] for option in options]
assert len(local_stream.messages) == 1
- assert message_name == CompletionResult.name
+ assert message_name == CompletionResultNotification.name
# TODO if `expects_completions=False`, something else than `_maybe_get_key_options()`
# could be returning values
if expects_key_completion is False:
diff --git a/tests/_runtime/test_manage_script_metadata.py b/tests/_runtime/test_manage_script_metadata.py
index 8d1ca32edd..c4f755d1e1 100644
--- a/tests/_runtime/test_manage_script_metadata.py
+++ b/tests/_runtime/test_manage_script_metadata.py
@@ -12,7 +12,10 @@ from marimo._config.config import merge_default_config
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._dependencies.dependencies import DependencyManager
from marimo._dependencies.errors import ManyModulesNotFoundError
-from marimo._messaging.ops import InstallingPackageAlert, MissingPackageAlert
+from marimo._messaging.notification import (
+ InstallingPackageAlertNotification,
+ MissingPackageAlertNotification,
+)
from marimo._runtime.packages.package_managers import create_package_manager
from marimo._runtime.packages.pypi_package_manager import (
MicropipPackageManager,
@@ -295,13 +298,16 @@ async def test_missing_packages_hook(
"""Test that missing_packages_hook correctly handles missing packages for micropip"""
k = mocked_kernel.k
control_requests: list[ControlRequest] = []
- broadcast_messages: list[InstallingPackageAlert | MissingPackageAlert] = []
+ broadcast_messages: list[
+ InstallingPackageAlertNotification | MissingPackageAlertNotification
+ ] = []
def mock_enqueue(request: ControlRequest) -> None:
control_requests.append(request)
def mock_broadcast(
- msg: InstallingPackageAlert | MissingPackageAlert,
+ msg: InstallingPackageAlertNotification
+ | MissingPackageAlertNotification,
stream: Any = None,
) -> None:
del stream
@@ -331,7 +337,9 @@ async def test_missing_packages_hook(
}
with (
- patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),
+ patch(
+ "marimo._runtime.runtime.broadcast_notification", mock_broadcast
+ ),
patch("micropip.install", new_callable=AsyncMock),
):
# Case 1: Auto-install enabled
@@ -366,7 +374,7 @@ async def test_missing_packages_hook(
assert len(control_requests) == 0
assert len(broadcast_messages) == 1
alert = broadcast_messages[0]
- assert isinstance(alert, MissingPackageAlert)
+ assert isinstance(alert, MissingPackageAlertNotification)
assert alert.packages == [
"grouped-one",
"grouped-two",
@@ -428,13 +436,16 @@ def test_missing_packages_hook_pip(
"""Test that missing_packages_hook correctly handles missing packages for pip"""
k = mocked_kernel.k
control_requests: list[ControlRequest] = []
- broadcast_messages: list[InstallingPackageAlert | MissingPackageAlert] = []
+ broadcast_messages: list[
+ InstallingPackageAlertNotification | MissingPackageAlertNotification
+ ] = []
def mock_enqueue(request: ControlRequest) -> None:
control_requests.append(request)
def mock_broadcast(
- msg: InstallingPackageAlert | MissingPackageAlert,
+ msg: InstallingPackageAlertNotification
+ | MissingPackageAlertNotification,
stream: Any = None,
) -> None:
del stream
@@ -460,7 +471,9 @@ def test_missing_packages_hook_pip(
}
with (
- patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),
+ patch(
+ "marimo._runtime.runtime.broadcast_notification", mock_broadcast
+ ),
):
k.packages_callbacks.package_manager = create_package_manager("pip")
package_manager = k.packages_callbacks.package_manager
@@ -477,7 +490,7 @@ def test_missing_packages_hook_pip(
assert len(control_requests) == 0
assert len(broadcast_messages) == 1
alert = broadcast_messages[0]
- assert isinstance(alert, MissingPackageAlert)
+ assert isinstance(alert, MissingPackageAlertNotification)
assert alert.packages == ["ibis-framework[duckdb]", "numpy", "pandas"]
assert alert.isolated == is_python_isolated()
@@ -511,12 +524,12 @@ async def test_install_missing_packages_with_streaming_logs(
) -> None:
"""Test that install_missing_packages uses streaming logs functionality."""
k = mocked_kernel.k
- broadcast_messages: list[InstallingPackageAlert] = []
+ broadcast_messages: list[InstallingPackageAlertNotification] = []
def mock_broadcast(msg, stream=None):
- """Mock the broadcast_op function to capture alerts"""
+ """Mock the broadcast_notification function to capture alerts"""
del stream
- if isinstance(msg, InstallingPackageAlert):
+ if isinstance(msg, InstallingPackageAlertNotification):
broadcast_messages.append(msg)
# Mock package manager
@@ -542,7 +555,9 @@ async def test_install_missing_packages_with_streaming_logs(
k.packages_callbacks.package_manager = mock_package_manager
with (
- patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),
+ patch(
+ "marimo._runtime.runtime.broadcast_notification", mock_broadcast
+ ),
):
# Create install request
request = InstallMissingPackagesRequest(
@@ -589,11 +604,11 @@ async def test_install_missing_packages_streaming_logs_failure(
) -> None:
"""Test streaming logs when package installation fails."""
k = mocked_kernel.k
- broadcast_messages: list[InstallingPackageAlert] = []
+ broadcast_messages: list[InstallingPackageAlertNotification] = []
def mock_broadcast(msg, stream=None):
del stream
- if isinstance(msg, InstallingPackageAlert):
+ if isinstance(msg, InstallingPackageAlertNotification):
broadcast_messages.append(msg)
# Mock package manager
@@ -615,7 +630,9 @@ async def test_install_missing_packages_streaming_logs_failure(
k.packages_callbacks.package_manager = mock_package_manager
with (
- patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),
+ patch(
+ "marimo._runtime.runtime.broadcast_notification", mock_broadcast
+ ),
):
request = InstallMissingPackagesRequest(
manager="pip", versions={"nonexistent-package": ""}
@@ -645,11 +662,11 @@ async def test_install_missing_packages_streaming_logs_multiple_packages(
) -> None:
"""Test streaming logs for multiple packages."""
k = mocked_kernel.k
- broadcast_messages: list[InstallingPackageAlert] = []
+ broadcast_messages: list[InstallingPackageAlertNotification] = []
def mock_broadcast(msg, stream=None):
del stream
- if isinstance(msg, InstallingPackageAlert):
+ if isinstance(msg, InstallingPackageAlertNotification):
broadcast_messages.append(msg)
# Mock package manager
@@ -676,7 +693,9 @@ async def test_install_missing_packages_streaming_logs_multiple_packages(
k.packages_callbacks.package_manager = mock_package_manager
with (
- patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),
+ patch(
+ "marimo._runtime.runtime.broadcast_notification", mock_broadcast
+ ),
):
request = InstallMissingPackagesRequest(
manager="pip", versions={"numpy": "", "pandas": "", "scipy": ""}
@@ -722,11 +741,11 @@ async def test_install_missing_packages_no_logs_backward_compatibility(
) -> None:
"""Test that package installation still works without streaming logs (backward compatibility)."""
k = mocked_kernel.k
- broadcast_messages: list[InstallingPackageAlert] = []
+ broadcast_messages: list[InstallingPackageAlertNotification] = []
def mock_broadcast(msg, stream=None):
del stream
- if isinstance(msg, InstallingPackageAlert):
+ if isinstance(msg, InstallingPackageAlertNotification):
broadcast_messages.append(msg)
# Mock package manager that doesn't use log callbacks
@@ -748,7 +767,9 @@ async def test_install_missing_packages_no_logs_backward_compatibility(
k.packages_callbacks.package_manager = mock_package_manager
with (
- patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),
+ patch(
+ "marimo._runtime.runtime.broadcast_notification", mock_broadcast
+ ),
):
request = InstallMissingPackagesRequest(
manager="pip", versions={"requests": ""}
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 672c9e3496..304645a165 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -23,9 +23,9 @@ from marimo._messaging.errors import (
MarimoSyntaxError,
MultipleDefinitionError,
)
-from marimo._messaging.ops import (
- CellOp,
- Variables,
+from marimo._messaging.notification import (
+ CellNotification,
+ VariablesNotification,
)
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import NoopStream
@@ -463,10 +463,14 @@ class TestExecution:
await k.run([er1])
stream = MockStream(k.stream)
- cell_ops = [deserialize_kernel_message(msg) for msg in stream.messages]
- cell_ops = [op for op in cell_ops if isinstance(op, CellOp)]
+ cell_notifications = [
+ deserialize_kernel_message(msg) for msg in stream.messages
+ ]
+ cell_notifications = [
+ op for op in cell_notifications if isinstance(op, CellNotification)
+ ]
er1_set_not_stale_before_run = False
- for op in cell_ops:
+ for op in cell_notifications:
if op.cell_id == er1.cell_id and op.status == "running":
break
if (
@@ -563,14 +567,16 @@ class TestExecution:
# Check the stream for stale broadcasts
stream = MockStream(k.stream)
- cell_ops = [
- op for op in stream.parsed_operations if isinstance(op, CellOp)
+ cell_notifications = [
+ op
+ for op in stream.parsed_operations
+ if isinstance(op, CellNotification)
]
# Filter for stale broadcasts
stale_broadcasts = [
op
- for op in cell_ops
+ for op in cell_notifications
if op.stale_inputs is not None and op.stale_inputs
]
@@ -1760,18 +1766,20 @@ except NameError:
await k.run([exec_req.get("print(2)")])
stream = MockStream(mocked_kernel.stream)
- cell_ops = [
- parse_raw(op_data, CellOp)
+ cell_notifications = [
+ parse_raw(op_data, CellNotification)
for op_data in stream.operations
if op_data["op"] == "cell-op"
]
- assert len(cell_ops) == 4 # queued -> running -> output -> idle
- for cell_op in cell_ops:
- if cell_op.status == "idle":
- assert cell_op.run_id is None
+ assert (
+ len(cell_notifications) == 4
+ ) # queued -> running -> output -> idle
+ for cell_notification in cell_notifications:
+ if cell_notification.status == "idle":
+ assert cell_notification.run_id is None
else:
- assert cell_op.run_id is not None
+ assert cell_notification.run_id is not None
async def test_sync_graph_basic(self, execution_kernel: Kernel) -> None:
"""Test basic synchronization: file changes cell B in A→B→C chain.
@@ -2504,8 +2512,8 @@ class TestStoredOutput:
# Check that the output was still broadcast (even if formatting failed)
stream = MockStream(mocked_kernel.stream)
- cell_ops = stream.cell_ops
- output_ops = [op for op in cell_ops if op.output is not None]
+ cell_notifications = stream.cell_notifications
+ output_ops = [op for op in cell_notifications if op.output is not None]
# Should have output, even if formatter failed (falls back to plain formatter)
assert len(output_ops) > 0
op_names = [op.get("op") for op in stream.operations]
@@ -2546,8 +2554,8 @@ class TestStoredOutput:
# Check that the output was still broadcast (even if formatting failed)
stream = MockStream(mocked_kernel.stream)
- cell_ops = stream.cell_ops
- output_ops = [op for op in cell_ops if op.output is not None]
+ cell_notifications = stream.cell_notifications
+ output_ops = [op for op in cell_notifications if op.output is not None]
# Should have output, even if formatter failed (falls back to plain formatter)
assert len(output_ops) > 0
op_names = [op.get("op") for op in stream.operations]
@@ -3259,15 +3267,19 @@ class TestStateTransitions:
)
stream = MockStream(mocked_kernel.stream)
- cell_ops = stream.cell_ops
+ cell_notifications = stream.cell_notifications
- n_queued = sum([1 for op in cell_ops if op.status == "queued"])
+ n_queued = sum(
+ [1 for op in cell_notifications if op.status == "queued"]
+ )
assert n_queued == 1
- n_running = sum([1 for op in cell_ops if op.status == "running"])
+ n_running = sum(
+ [1 for op in cell_notifications if op.status == "running"]
+ )
assert n_running == 1
- n_idle = sum([1 for op in cell_ops if op.status == "idle"])
+ n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
assert n_idle == 1
async def test_statuses_not_repeated_on_stop(
@@ -3280,15 +3292,19 @@ class TestStateTransitions:
]
)
- cell_ops = mocked_kernel.stream.cell_ops
+ cell_notifications = mocked_kernel.stream.cell_notifications
- n_queued = sum([1 for op in cell_ops if op.status == "queued"])
+ n_queued = sum(
+ [1 for op in cell_notifications if op.status == "queued"]
+ )
assert n_queued == 1
- n_running = sum([1 for op in cell_ops if op.status == "running"])
+ n_running = sum(
+ [1 for op in cell_notifications if op.status == "running"]
+ )
assert n_running == 1
- n_idle = sum([1 for op in cell_ops if op.status == "idle"])
+ n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
assert n_idle == 1
async def test_statuses_not_repeated_on_interruption(
@@ -3304,15 +3320,19 @@ class TestStateTransitions:
)
stream = MockStream(mocked_kernel.stream)
- cell_ops = stream.cell_ops
+ cell_notifications = stream.cell_notifications
- n_queued = sum([1 for op in cell_ops if op.status == "queued"])
+ n_queued = sum(
+ [1 for op in cell_notifications if op.status == "queued"]
+ )
assert n_queued == 1
- n_running = sum([1 for op in cell_ops if op.status == "running"])
+ n_running = sum(
+ [1 for op in cell_notifications if op.status == "running"]
+ )
assert n_running == 1
- n_idle = sum([1 for op in cell_ops if op.status == "idle"])
+ n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
assert n_idle == 1
async def test_statuses_not_repeated_on_exception(
@@ -3326,15 +3346,19 @@ class TestStateTransitions:
)
stream = MockStream(mocked_kernel.stream)
- cell_ops = stream.cell_ops
+ cell_notifications = stream.cell_notifications
- n_queued = sum([1 for op in cell_ops if op.status == "queued"])
+ n_queued = sum(
+ [1 for op in cell_notifications if op.status == "queued"]
+ )
assert n_queued == 1
- n_running = sum([1 for op in cell_ops if op.status == "running"])
+ n_running = sum(
+ [1 for op in cell_notifications if op.status == "running"]
+ )
assert n_running == 1
- n_idle = sum([1 for op in cell_ops if op.status == "idle"])
+ n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
assert n_idle == 1
async def test_descendant_status_reset_to_idle_on_error(
@@ -3349,18 +3373,22 @@ class TestStateTransitions:
)
stream = MockStream(mocked_kernel.stream)
- cell_ops = stream.cell_ops
+ cell_notifications = stream.cell_notifications
# er_1 and er_2
- n_queued = sum([1 for op in cell_ops if op.status == "queued"])
+ n_queued = sum(
+ [1 for op in cell_notifications if op.status == "queued"]
+ )
assert n_queued == 2
# only er_1 runs
- n_running = sum([1 for op in cell_ops if op.status == "running"])
+ n_running = sum(
+ [1 for op in cell_notifications if op.status == "running"]
+ )
assert n_running == 1
# er_1 and er_2
- n_idle = sum([1 for op in cell_ops if op.status == "idle"])
+ n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
assert n_idle == 2
assert k.graph.cells[er_1.cell_id].runtime_state == "idle"
@@ -3385,18 +3413,22 @@ class TestStateTransitions:
)
stream = MockStream(mocked_kernel.stream)
- cell_ops = stream.cell_ops
+ cell_notifications = stream.cell_notifications
# er_1 and er_2
- n_queued = sum([1 for op in cell_ops if op.status == "queued"])
+ n_queued = sum(
+ [1 for op in cell_notifications if op.status == "queued"]
+ )
assert n_queued == 2
# only er_1 runs
- n_running = sum([1 for op in cell_ops if op.status == "running"])
+ n_running = sum(
+ [1 for op in cell_notifications if op.status == "running"]
+ )
assert n_running == 1
# er_1 and er_2
- n_idle = sum([1 for op in cell_ops if op.status == "idle"])
+ n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
assert n_idle == 2
assert k.graph.cells[er_1.cell_id].runtime_state == "idle"
@@ -3413,7 +3445,11 @@ class TestStateTransitions:
er = exec_req.get("x = 1")
await k.run([er])
initial_messages = len(
- [m for m in stream.operations if isinstance(m, Variables)]
+ [
+ m
+ for m in stream.operations
+ if isinstance(m, VariablesNotification)
+ ]
)
assert initial_messages == 1
@@ -3421,7 +3457,12 @@ class TestStateTransitions:
stream.messages.clear()
await k.run([er])
assert (
- sum(1 for m in stream.operations if isinstance(m, Variables)) == 1
+ sum(
+ 1
+ for m in stream.operations
+ if isinstance(m, VariablesNotification)
+ )
+ == 1
)
# Adding a new variable should broadcast Variables
@@ -3429,14 +3470,24 @@ class TestStateTransitions:
er_2 = exec_req.get("y = 1")
await k.run([er_2])
assert (
- sum(1 for m in stream.operations if isinstance(m, Variables)) == 1
+ sum(
+ 1
+ for m in stream.operations
+ if isinstance(m, VariablesNotification)
+ )
+ == 1
)
# Adding a new edge should broadcast Variables
stream.messages.clear()
await k.run([exec_req.get("z = y")])
assert (
- sum(1 for m in stream.operations if isinstance(m, Variables)) == 1
+ sum(
+ 1
+ for m in stream.operations
+ if isinstance(m, VariablesNotification)
+ )
+ == 1
)
# Modifying value without changing edges/defs should now broadcast
@@ -3444,14 +3495,24 @@ class TestStateTransitions:
er_2.code = "y = 2"
await k.run([exec_req.get_with_id(er_2.cell_id, er_2.code)])
assert (
- sum(1 for m in stream.operations if isinstance(m, Variables)) == 1
+ sum(
+ 1
+ for m in stream.operations
+ if isinstance(m, VariablesNotification)
+ )
+ == 1
)
# Deleting a cell should broadcast Variables
stream.messages.clear()
await k.delete_cell(DeleteCellRequest(cell_id=er_2.cell_id))
assert (
- sum(1 for m in stream.operations if isinstance(m, Variables)) == 1
+ sum(
+ 1
+ for m in stream.operations
+ if isinstance(m, VariablesNotification)
+ )
+ == 1
)
@staticmethod
@@ -3515,10 +3576,10 @@ class TestErrorHandling:
) -> None:
k = mocked_kernel.k
await k.run([exec_req.get("raise ValueError('some secret error')")])
- cell_ops = mocked_kernel.stream.cell_ops
- error_cell_op = _filter_to_error_ops(cell_ops)
- assert len(error_cell_op) == 1
- errors = _parse_error_output(error_cell_op[0])
+ cell_notifications = mocked_kernel.stream.cell_notifications
+ error_cell_notification = _filter_to_error_ops(cell_notifications)
+ assert len(error_cell_notification) == 1
+ errors = _parse_error_output(error_cell_notification[0])
assert len(errors) == 1
assert isinstance(errors[0], MarimoExceptionRaisedError)
@@ -3530,10 +3591,10 @@ class TestErrorHandling:
) -> None:
k = run_mode_kernel.k
await k.run([exec_req.get("raise ValueError('some secret error')")])
- cell_ops = run_mode_kernel.stream.cell_ops
- error_cell_op = _filter_to_error_ops(cell_ops)
- assert len(error_cell_op) == 1
- errors = _parse_error_output(error_cell_op[0])
+ cell_notifications = run_mode_kernel.stream.cell_notifications
+ error_cell_notification = _filter_to_error_ops(cell_notifications)
+ assert len(error_cell_notification) == 1
+ errors = _parse_error_output(error_cell_notification[0])
assert len(errors) == 1
assert isinstance(errors[0], MarimoInternalError)
@@ -3549,10 +3610,10 @@ class TestErrorHandling:
exec_req.get("x = 20"),
]
)
- cell_ops = run_mode_kernel.stream.cell_ops
- error_cell_op = _filter_to_error_ops(cell_ops)
- assert len(error_cell_op) == 2
- for op in error_cell_op:
+ cell_notifications = run_mode_kernel.stream.cell_notifications
+ error_cell_notification = _filter_to_error_ops(cell_notifications)
+ assert len(error_cell_notification) == 2
+ for op in error_cell_notification:
errors = _parse_error_output(op)
assert len(errors) == 1
assert isinstance(errors[0], MarimoInternalError)
@@ -3640,17 +3701,25 @@ class TestMarkdownHandling:
assert "regular_cell" in k._uninstantiated_execution_requests
# Check that the markdown cell output was broadcast
- cell_ops = [deserialize_kernel_message(msg) for msg in stream.messages]
- cell_ops = [op for op in cell_ops if isinstance(op, CellOp)]
+ cell_notifications = [
+ deserialize_kernel_message(msg) for msg in stream.messages
+ ]
+ cell_notifications = [
+ op for op in cell_notifications if isinstance(op, CellNotification)
+ ]
# Find operations for the markdown cell
- md_cell_ops = [op for op in cell_ops if op.cell_id == "md_cell"]
+ md_cell_notifications = [
+ op for op in cell_notifications if op.cell_id == "md_cell"
+ ]
# Should have at least one output operation and one stale operation
- assert len(md_cell_ops) >= 2
+ assert len(md_cell_notifications) >= 2
# Check that there's an output operation with HTML content
- output_ops = [op for op in md_cell_ops if op.output is not None]
+ output_ops = [
+ op for op in md_cell_notifications if op.output is not None
+ ]
assert len(output_ops) == 1
output_op = output_ops[0]
@@ -3661,16 +3730,20 @@ class TestMarkdownHandling:
assert output_op.status == "idle"
# Check that the cell was marked as not stale
- stale_ops = [op for op in md_cell_ops if op.stale_inputs is not None]
+ stale_ops = [
+ op for op in md_cell_notifications if op.stale_inputs is not None
+ ]
assert len(stale_ops) == 1
assert stale_ops[0].stale_inputs is False
# Check that regular cell was marked as stale
- regular_cell_ops = [
- op for op in cell_ops if op.cell_id == "regular_cell"
+ regular_cell_notifications = [
+ op for op in cell_notifications if op.cell_id == "regular_cell"
]
regular_stale_ops = [
- op for op in regular_cell_ops if op.stale_inputs is not None
+ op
+ for op in regular_cell_notifications
+ if op.stale_inputs is not None
]
assert len(regular_stale_ops) == 1
assert regular_stale_ops[0].stale_inputs is True
@@ -3791,13 +3864,21 @@ class TestMarkdownHandling:
assert "cell2" in k._uninstantiated_execution_requests
# Check that all cells were marked as stale
- cell_ops = [deserialize_kernel_message(msg) for msg in stream.messages]
- cell_ops = [op for op in cell_ops if isinstance(op, CellOp)]
+ cell_notifications = [
+ deserialize_kernel_message(msg) for msg in stream.messages
+ ]
+ cell_notifications = [
+ op for op in cell_notifications if isinstance(op, CellNotification)
+ ]
for cell_id in ["cell1", "cell2"]:
- cell_ops_for_id = [op for op in cell_ops if op.cell_id == cell_id]
+ cell_notifications_for_id = [
+ op for op in cell_notifications if op.cell_id == cell_id
+ ]
stale_ops = [
- op for op in cell_ops_for_id if op.stale_inputs is not None
+ op
+ for op in cell_notifications_for_id
+ if op.stale_inputs is not None
]
assert len(stale_ops) == 1
assert stale_ops[0].stale_inputs is True
@@ -3850,20 +3931,30 @@ class TestMarkdownHandling:
assert "good_md" not in k._uninstantiated_execution_requests
# Check operations
- cell_ops = [deserialize_kernel_message(msg) for msg in stream.messages]
- cell_ops = [op for op in cell_ops if isinstance(op, CellOp)]
+ cell_notifications = [
+ deserialize_kernel_message(msg) for msg in stream.messages
+ ]
+ cell_notifications = [
+ op for op in cell_notifications if isinstance(op, CellNotification)
+ ]
# Bad cell should be marked as stale
- bad_cell_ops = [op for op in cell_ops if op.cell_id == "bad_cell"]
+ bad_cell_notifications = [
+ op for op in cell_notifications if op.cell_id == "bad_cell"
+ ]
bad_stale_ops = [
- op for op in bad_cell_ops if op.stale_inputs is not None
+ op for op in bad_cell_notifications if op.stale_inputs is not None
]
assert len(bad_stale_ops) == 1
assert bad_stale_ops[0].stale_inputs is True
# Good cell should have output and be marked as not stale
- good_cell_ops = [op for op in cell_ops if op.cell_id == "good_md"]
- good_output_ops = [op for op in good_cell_ops if op.output is not None]
+ good_cell_notifications = [
+ op for op in cell_notifications if op.cell_id == "good_md"
+ ]
+ good_output_ops = [
+ op for op in good_cell_notifications if op.output is not None
+ ]
assert len(good_output_ops) == 1
assert "Good" in good_output_ops[0].output.data
@@ -3903,24 +3994,32 @@ class TestMarkdownHandling:
assert "regular_cell" in k._uninstantiated_execution_requests
# Check that all cells were marked as stale
- cell_ops = [deserialize_kernel_message(msg) for msg in stream.messages]
- cell_ops = [op for op in cell_ops if isinstance(op, CellOp)]
+ cell_notifications = [
+ deserialize_kernel_message(msg) for msg in stream.messages
+ ]
+ cell_notifications = [
+ op for op in cell_notifications if isinstance(op, CellNotification)
+ ]
for cell_id in ["md_cell1", "md_cell2", "regular_cell"]:
- cell_ops_for_id = [op for op in cell_ops if op.cell_id == cell_id]
+ cell_notifications_for_id = [
+ op for op in cell_notifications if op.cell_id == cell_id
+ ]
stale_ops = [
- op for op in cell_ops_for_id if op.stale_inputs is not None
+ op
+ for op in cell_notifications_for_id
+ if op.stale_inputs is not None
]
assert len(stale_ops) == 1
assert stale_ops[0].stale_inputs is True
# No cells should have output operations
- output_ops = [op for op in cell_ops if op.output is not None]
+ output_ops = [op for op in cell_notifications if op.output is not None]
assert len(output_ops) == 0
-def _parse_error_output(cell_op: CellOp) -> list[Error]:
- error_output = cell_op.output
+def _parse_error_output(cell_notification: CellNotification) -> list[Error]:
+ error_output = cell_notification.output
assert error_output is not None
assert error_output.channel == CellChannel.MARIMO_ERROR
assert error_output.mimetype == "application/vnd.marimo+error"
@@ -3928,10 +4027,12 @@ def _parse_error_output(cell_op: CellOp) -> list[Error]:
return cast(list[Error], data)
-def _filter_to_error_ops(cell_ops: list[CellOp]) -> list[CellOp]:
+def _filter_to_error_ops(
+ cell_notifications: list[CellNotification],
+) -> list[CellNotification]:
return [
op
- for op in cell_ops
+ for op in cell_notifications
if op.output is not None
and op.output.channel == CellChannel.MARIMO_ERROR
]
diff --git a/tests/_runtime/test_runtime_datasets.py b/tests/_runtime/test_runtime_datasets.py
index 940f7ee247..d34f9e44d4 100644
--- a/tests/_runtime/test_runtime_datasets.py
+++ b/tests/_runtime/test_runtime_datasets.py
@@ -5,12 +5,12 @@ from __future__ import annotations
import pytest
from marimo._dependencies.dependencies import DependencyManager
-from marimo._messaging.ops import (
- DataSourceConnections,
+from marimo._messaging.notification import (
+ DataSourceConnectionsNotification,
SQLMetadata,
- SQLTableListPreview,
- SQLTablePreview,
- ValidateSQLResult,
+ SQLTableListPreviewNotification,
+ SQLTablePreviewNotification,
+ ValidateSQLResultNotification,
)
from marimo._runtime.requests import (
ExecutionRequest,
@@ -96,10 +96,12 @@ class TestPreviewSQLTable:
await k.handle_message(preview_sql_table_request)
preview_sql_table_results = [
- op for op in stream.operations if isinstance(op, SQLTablePreview)
+ op
+ for op in stream.operations
+ if isinstance(op, SQLTablePreviewNotification)
]
assert preview_sql_table_results == [
- SQLTablePreview(
+ SQLTablePreviewNotification(
request_id=RequestId("0"),
table=None,
error="Engine not found",
@@ -129,10 +131,12 @@ class TestPreviewSQLTable:
await k.handle_message(preview_sql_table_request)
preview_sql_table_results = [
- op for op in stream.operations if isinstance(op, SQLTablePreview)
+ op
+ for op in stream.operations
+ if isinstance(op, SQLTablePreviewNotification)
]
assert preview_sql_table_results == [
- SQLTablePreview(
+ SQLTablePreviewNotification(
request_id=RequestId("0"),
table=None,
error=None,
@@ -162,10 +166,12 @@ class TestPreviewSQLTable:
await k.handle_message(preview_sql_table_request)
preview_sql_table_results = [
- op for op in stream.operations if isinstance(op, SQLTablePreview)
+ op
+ for op in stream.operations
+ if isinstance(op, SQLTablePreviewNotification)
]
assert preview_sql_table_results == [
- SQLTablePreview(
+ SQLTablePreviewNotification(
request_id=RequestId("0"),
table=None,
error="Connection does not support catalog operations",
@@ -194,10 +200,10 @@ class TestPreviewSQLTableList:
preview_sql_table_list_results = [
op
for op in stream.operations
- if isinstance(op, SQLTableListPreview)
+ if isinstance(op, SQLTableListPreviewNotification)
]
assert preview_sql_table_list_results == [
- SQLTableListPreview(
+ SQLTableListPreviewNotification(
request_id=RequestId("0"),
tables=[],
error="Engine not found",
@@ -228,10 +234,10 @@ class TestPreviewSQLTableList:
preview_sql_table_list_results = [
op
for op in stream.operations
- if isinstance(op, SQLTableListPreview)
+ if isinstance(op, SQLTableListPreviewNotification)
]
assert preview_sql_table_list_results == [
- SQLTableListPreview(
+ SQLTableListPreviewNotification(
request_id=RequestId("0"),
tables=[],
error=None,
@@ -262,10 +268,10 @@ class TestPreviewSQLTableList:
preview_sql_table_list_results = [
op
for op in stream.operations
- if isinstance(op, SQLTableListPreview)
+ if isinstance(op, SQLTableListPreviewNotification)
]
assert preview_sql_table_list_results == [
- SQLTableListPreview(
+ SQLTableListPreviewNotification(
request_id=RequestId("0"),
tables=[],
error="Connection does not support catalog operations",
@@ -290,7 +296,7 @@ class TestPreviewDatasourceConnection:
preview_datasource_connection_results = [
op
for op in stream.operations
- if isinstance(op, DataSourceConnections)
+ if isinstance(op, DataSourceConnectionsNotification)
]
assert preview_datasource_connection_results == []
@@ -315,7 +321,7 @@ class TestPreviewDatasourceConnection:
preview_datasource_connection_results = [
op
for op in stream.operations
- if isinstance(op, DataSourceConnections)
+ if isinstance(op, DataSourceConnectionsNotification)
]
assert len(preview_datasource_connection_results) == 2
@@ -337,10 +343,12 @@ class TestSQLValidate:
)
await k.handle_message(validate_sql_request)
validate_sql_results = [
- op for op in stream.operations if isinstance(op, ValidateSQLResult)
+ op
+ for op in stream.operations
+ if isinstance(op, ValidateSQLResultNotification)
]
assert validate_sql_results == [
- ValidateSQLResult(
+ ValidateSQLResultNotification(
request_id=RequestId("0"),
parse_result=None,
validate_result=None,
@@ -363,9 +371,11 @@ class TestSQLValidate:
)
await k.handle_message(validate_sql_request)
validate_sql_results = [
- op for op in stream.operations if isinstance(op, ValidateSQLResult)
+ op
+ for op in stream.operations
+ if isinstance(op, ValidateSQLResultNotification)
]
- assert validate_sql_results[-1] == ValidateSQLResult(
+ assert validate_sql_results[-1] == ValidateSQLResultNotification(
request_id=RequestId("1"),
parse_result=SqlParseResult(success=True, errors=[]),
validate_result=SqlCatalogCheckResult(
@@ -389,7 +399,9 @@ class TestSQLValidate:
)
await k.handle_message(validate_sql_request)
validate_sql_results = [
- op for op in stream.operations if isinstance(op, ValidateSQLResult)
+ op
+ for op in stream.operations
+ if isinstance(op, ValidateSQLResultNotification)
]
latest_validate_sql_result = validate_sql_results[-1]
assert latest_validate_sql_result.request_id == RequestId("2")
@@ -427,11 +439,13 @@ class TestSQLValidate:
)
await k.handle_message(validate_sql_request)
validate_sql_results = [
- op for op in stream.operations if isinstance(op, ValidateSQLResult)
+ op
+ for op in stream.operations
+ if isinstance(op, ValidateSQLResultNotification)
]
assert (
validate_sql_results[-1]
- == ValidateSQLResult(
+ == ValidateSQLResultNotification(
request_id=RequestId("3"),
parse_result=None, # Currently does not support parse errors for non-duckdb engines
validate_result=SqlCatalogCheckResult(
@@ -460,9 +474,11 @@ class TestSQLValidate:
await k.handle_message(validate_sql_request)
validate_sql_results = [
- op for op in stream.operations if isinstance(op, ValidateSQLResult)
+ op
+ for op in stream.operations
+ if isinstance(op, ValidateSQLResultNotification)
]
- assert validate_sql_results[-1] == ValidateSQLResult(
+ assert validate_sql_results[-1] == ValidateSQLResultNotification(
request_id=RequestId("4"),
parse_result=None,
validate_result=None,
@@ -488,9 +504,11 @@ class TestSQLValidate:
await k.handle_message(validate_sql_request)
validate_sql_results = [
- op for op in stream.operations if isinstance(op, ValidateSQLResult)
+ op
+ for op in stream.operations
+ if isinstance(op, ValidateSQLResultNotification)
]
- assert validate_sql_results[-1] == ValidateSQLResult(
+ assert validate_sql_results[-1] == ValidateSQLResultNotification(
request_id=RequestId("5"),
parse_result=None,
validate_result=None,
@@ -516,9 +534,11 @@ class TestSQLValidate:
await k.handle_message(validate_sql_request)
validate_sql_results = [
- op for op in stream.operations if isinstance(op, ValidateSQLResult)
+ op
+ for op in stream.operations
+ if isinstance(op, ValidateSQLResultNotification)
]
- assert validate_sql_results[-1] == ValidateSQLResult(
+ assert validate_sql_results[-1] == ValidateSQLResultNotification(
request_id=RequestId("6"),
parse_result=SqlParseResult(success=True, errors=[]),
validate_result=None,
@@ -543,9 +563,11 @@ class TestSQLValidate:
await k.handle_message(validate_sql_request)
validate_sql_results = [
- op for op in stream.operations if isinstance(op, ValidateSQLResult)
+ op
+ for op in stream.operations
+ if isinstance(op, ValidateSQLResultNotification)
]
- assert validate_sql_results[-1] == ValidateSQLResult(
+ assert validate_sql_results[-1] == ValidateSQLResultNotification(
request_id=RequestId("7"),
parse_result=None,
validate_result=None,
diff --git a/tests/_runtime/test_runtime_secrets.py b/tests/_runtime/test_runtime_secrets.py
index 7cc6b8f9b7..65492e70a9 100644
--- a/tests/_runtime/test_runtime_secrets.py
+++ b/tests/_runtime/test_runtime_secrets.py
@@ -5,7 +5,7 @@ from unittest.mock import MagicMock
import pytest
-from marimo._messaging.ops import SecretKeysResult
+from marimo._messaging.notification import SecretKeysResultNotification
from marimo._runtime.requests import (
ListSecretKeysRequest,
RefreshSecretsRequest,
@@ -38,7 +38,7 @@ async def test_list_secrets_with_values(
secret_messages = [
msg
for msg in stream.parsed_operations
- if isinstance(msg, SecretKeysResult)
+ if isinstance(msg, SecretKeysResultNotification)
]
assert len(secret_messages) == 1
first_secret_message = secret_messages[0]
diff --git a/tests/_runtime/test_threads.py b/tests/_runtime/test_threads.py
index 37a01bf652..15dc83b73d 100644
--- a/tests/_runtime/test_threads.py
+++ b/tests/_runtime/test_threads.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import time
from marimo._runtime.requests import DeleteCellRequest
@@ -90,14 +92,16 @@ async def test_thread_output_append(
assert not k.errors
time.sleep(0.01) # noqa: ASYNC251
# The main thread should not have any output, but the new thread should
- cell_ops = MockStream(k.globals["stream"]).cell_ops
- for m in cell_ops:
+ cell_notifications = MockStream(k.globals["stream"]).cell_notifications
+ for m in cell_notifications:
if m.output is not None:
assert "hello" not in m.output.data
assert "world" not in m.output.data
- thread_stream_cell_ops = MockStream(k.globals["thread_stream"]).cell_ops
- assert "hello" in thread_stream_cell_ops[0].output.data
- assert "world" in thread_stream_cell_ops[1].output.data
+ thread_stream_cell_notifications = MockStream(
+ k.globals["thread_stream"]
+ ).cell_notifications
+ assert "hello" in thread_stream_cell_notifications[0].output.data
+ assert "world" in thread_stream_cell_notifications[1].output.data
async def test_thread_print(k: Kernel, exec_req: ExecReqProvider) -> None:
diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.py
index 6e7d19e0e4..5b8601b6f8 100644
--- a/tests/_server/api/endpoints/test_execution.py
+++ b/tests/_server/api/endpoints/test_execution.py
@@ -412,10 +412,12 @@ def get_printed_object(
start = time.time()
console = None
while time.time() - start < timeout:
- if cell_id not in session.session_view.cell_operations:
+ if cell_id not in session.session_view.cell_notifications:
time.sleep(0.1)
continue
- console = first(session.session_view.cell_operations[cell_id].console)
+ console = first(
+ session.session_view.cell_notifications[cell_id].console
+ )
if console:
break
assert console
diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.py
index b5a14ddab6..2d87ef62e6 100644
--- a/tests/_server/api/endpoints/test_export.py
+++ b/tests/_server/api/endpoints/test_export.py
@@ -12,7 +12,7 @@ import pytest
from marimo import __version__
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel, CellOutput
-from marimo._messaging.ops import CellOp
+from marimo._messaging.notification import CellNotification
from marimo._output.utils import uri_encode_component
from marimo._types.ids import CellId_t, SessionId
from marimo._utils.platform import is_windows
@@ -205,8 +205,8 @@ def test_auto_export_html(client: TestClient, temp_marimo_file: str) -> None:
assert session
assert temp_marimo_file is not None
session.app_file_manager.filename = temp_marimo_file
- session.session_view.add_operation(
- CellOp(
+ session.session_view.add_notification(
+ CellNotification(
cell_id=CellId_t("new_cell"),
output=CellOutput(
data="hello",
@@ -253,8 +253,8 @@ def test_auto_export_html_no_code(
session = get_session_manager(client).get_session(SESSION_ID)
assert session
session.app_file_manager.filename = temp_marimo_file
- session.session_view.add_operation(
- CellOp(
+ session.session_view.add_notification(
+ CellNotification(
cell_id=CellId_t("new_cell"),
output=None,
console=[CellOutput.stdout("hello")],
@@ -445,17 +445,20 @@ def test_auto_export_ipynb_with_new_cell(
# Wait for the cell operation to be created
timeout = 2
start = time.time()
- cell_op = None
+ cell_notification = None
while time.time() - start < timeout:
- if "new_cell" not in session.session_view.cell_operations:
+ if "new_cell" not in session.session_view.cell_notifications:
time.sleep(0.1)
continue
- cell_op = session.session_view.cell_operations["new_cell"]
- if cell_op.output is not None and cell_op.output.data:
+ cell_notification = session.session_view.cell_notifications["new_cell"]
+ if (
+ cell_notification.output is not None
+ and cell_notification.output.data
+ ):
break
- assert cell_op
- assert cell_op.output is not None
- assert "3.14" in cell_op.output.data
+ assert cell_notification
+ assert cell_notification.output is not None
+ assert "3.14" in cell_notification.output.data
# Now attempt to auto-export as ipynb
export_response = client.post(
diff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.py
index 107300e663..974adaa07f 100644
--- a/tests/_server/api/endpoints/test_kiosk.py
+++ b/tests/_server/api/endpoints/test_kiosk.py
@@ -6,7 +6,10 @@ from typing import TYPE_CHECKING, Any, Optional
import pytest
from marimo._messaging.msgspec_encoder import asdict
-from marimo._messaging.ops import KernelCapabilities, KernelReady
+from marimo._messaging.notification import (
+ KernelCapabilitiesNotification,
+ KernelReadyNotification,
+)
from marimo._utils.parse_dataclass import parse_raw
from tests._server.mocks import token_header
@@ -29,7 +32,7 @@ def create_response(
"kiosk": False,
"configs": [{"disabled": False, "hide_code": False}],
"app_config": {"width": "full"},
- "capabilities": asdict(KernelCapabilities()),
+ "capabilities": asdict(KernelCapabilitiesNotification()),
}
response.update(partial_response)
return response
@@ -46,8 +49,8 @@ def assert_kernel_ready_response(
) -> None:
if response is None:
response = create_response({})
- data = parse_raw(raw_data["data"], KernelReady)
- expected = parse_raw(response, KernelReady)
+ data = parse_raw(raw_data["data"], KernelReadyNotification)
+ expected = parse_raw(response, KernelReadyNotification)
assert data.cell_ids == expected.cell_ids
assert data.codes == expected.codes
assert data.names == expected.names
@@ -61,7 +64,7 @@ def assert_kernel_ready_response(
def assert_parse_ready_response(raw_data: dict[str, Any]) -> None:
- data = parse_raw(raw_data["data"], KernelReady)
+ data = parse_raw(raw_data["data"], KernelReadyNotification)
assert data is not None
diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.py
index 30083f627b..0c81e62512 100644
--- a/tests/_server/api/endpoints/test_resume_session.py
+++ b/tests/_server/api/endpoints/test_resume_session.py
@@ -9,7 +9,11 @@ import pytest
from marimo._config.manager import UserConfigManager
from marimo._messaging.msgspec_encoder import asdict
-from marimo._messaging.ops import CellOp, KernelCapabilities, KernelReady
+from marimo._messaging.notification import (
+ CellNotification,
+ KernelCapabilitiesNotification,
+ KernelReadyNotification,
+)
from marimo._server.sessions import Session
from marimo._types.ids import SessionId
from marimo._utils.parse_dataclass import parse_raw
@@ -35,7 +39,7 @@ def create_response(
"kiosk": False,
"configs": [{"disabled": False, "hide_code": False}],
"app_config": {"width": "full"},
- "capabilities": asdict(KernelCapabilities()),
+ "capabilities": asdict(KernelCapabilitiesNotification()),
}
response.update(partial_response)
return response
@@ -56,9 +60,9 @@ HEADERS = {
def assert_kernel_ready_response(
raw_data: dict[str, Any], response: dict[str, Any]
) -> None:
- data = parse_raw(raw_data["data"], KernelReady)
+ data = parse_raw(raw_data["data"], KernelReadyNotification)
print(response)
- expected = parse_raw(response, KernelReady)
+ expected = parse_raw(response, KernelReadyNotification)
assert data.cell_ids == expected.cell_ids
assert data.codes == expected.codes
assert data.names == expected.names
@@ -93,10 +97,10 @@ def test_refresh_session(client: TestClient) -> None:
session_view = session.session_view
# Mimic cell execution time save
- cell_op = CellOp("Hbol")
- session_view.save_execution_time(cell_op, "start")
+ cell_notification = CellNotification("Hbol")
+ session_view.save_execution_time(cell_notification, "start")
time.sleep(0.123)
- session_view.save_execution_time(cell_op, "end")
+ session_view.save_execution_time(cell_notification, "end")
last_exec_time = session_view.last_execution_time["Hbol"]
# New session with new ID (simulates refresh)
@@ -346,7 +350,7 @@ def test_resume_session_with_watch(client: TestClient) -> None:
# Check for KernelReady message
data = websocket.receive_json()
- assert parse_raw(data["data"], KernelReady)
+ assert parse_raw(data["data"], KernelReadyNotification)
messages: list[dict[str, Any]] = []
# Wait for update-cell-codes message
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 85d3ffb4bb..a7d7184bf8 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -12,7 +12,10 @@ from starlette.websockets import WebSocketDisconnect
from marimo._config.config import ExperimentalConfig
from marimo._config.manager import UserConfigManager
from marimo._messaging.msgspec_encoder import asdict
-from marimo._messaging.ops import KernelCapabilities, KernelReady
+from marimo._messaging.notification import (
+ KernelCapabilitiesNotification,
+ KernelReadyNotification,
+)
from marimo._server.codes import WebSocketCodes
from marimo._server.model import SessionMode
from marimo._server.sessions import SessionManager
@@ -39,7 +42,7 @@ def create_response(
"kiosk": False,
"configs": [{"disabled": False, "hide_code": False}],
"app_config": {"width": "full"},
- "capabilities": asdict(KernelCapabilities()),
+ "capabilities": asdict(KernelCapabilitiesNotification()),
}
response.update(partial_response)
return response
@@ -70,8 +73,8 @@ def assert_kernel_ready_response(
) -> None:
if response is None:
response = create_response({})
- data = parse_raw(raw_data["data"], KernelReady)
- expected = parse_raw(response, KernelReady)
+ data = parse_raw(raw_data["data"], KernelReadyNotification)
+ expected = parse_raw(response, KernelReadyNotification)
assert data.cell_ids == expected.cell_ids
assert data.codes == expected.codes
assert data.names == expected.names
@@ -85,7 +88,7 @@ def assert_kernel_ready_response(
def assert_parse_ready_response(raw_data: dict[str, Any]) -> None:
- data = parse_raw(raw_data["data"], KernelReady)
+ data = parse_raw(raw_data["data"], KernelReadyNotification)
assert data is not None
@@ -447,7 +450,7 @@ async def test_session_resumption(client: TestClient) -> None:
assert kernel_ready_msg["op"] == "kernel-ready"
# Verify resumed flag is True
- data = parse_raw(kernel_ready_msg["data"], KernelReady)
+ data = parse_raw(kernel_ready_msg["data"], KernelReadyNotification)
assert data.resumed is True
# Should replay operations - collect some messages
diff --git a/tests/_server/api/endpoints/test_ws_rtc.py b/tests/_server/api/endpoints/test_ws_rtc.py
index e04f1bc551..551c535205 100644
--- a/tests/_server/api/endpoints/test_ws_rtc.py
+++ b/tests/_server/api/endpoints/test_ws_rtc.py
@@ -9,7 +9,10 @@ from starlette.websockets import WebSocketDisconnect
from marimo._config.manager import UserConfigManager
from marimo._messaging.msgspec_encoder import asdict
-from marimo._messaging.ops import KernelCapabilities, KernelReady
+from marimo._messaging.notification import (
+ KernelCapabilitiesNotification,
+ KernelReadyNotification,
+)
from marimo._server.api.endpoints.ws_endpoint import DOC_MANAGER
from marimo._utils.parse_dataclass import parse_raw
from tests._server.conftest import get_session_manager, get_user_config_manager
@@ -36,7 +39,7 @@ def create_response(
"kiosk": False,
"configs": [{"disabled": False, "hide_code": False}],
"app_config": {"width": "full"},
- "capabilities": asdict(KernelCapabilities()),
+ "capabilities": asdict(KernelCapabilitiesNotification()),
}
response.update(partial_response)
return response
@@ -59,8 +62,8 @@ def assert_kernel_ready_response(
) -> None:
if response is None:
response = create_response({})
- data = parse_raw(raw_data["data"], KernelReady)
- expected = parse_raw(response, KernelReady)
+ data = parse_raw(raw_data["data"], KernelReadyNotification)
+ expected = parse_raw(response, KernelReadyNotification)
assert data.cell_ids == expected.cell_ids
assert data.codes == expected.codes
assert data.names == expected.names
@@ -74,7 +77,7 @@ def assert_kernel_ready_response(
def assert_parse_ready_response(raw_data: dict[str, Any]) -> None:
- data = parse_raw(raw_data["data"], KernelReady)
+ data = parse_raw(raw_data["data"], KernelReadyNotification)
assert data is not None
diff --git a/tests/_server/conftest.py b/tests/_server/conftest.py
index f554709a64..b8e5c74492 100644
--- a/tests/_server/conftest.py
+++ b/tests/_server/conftest.py
@@ -99,5 +99,5 @@ def session_view() -> Generator[SessionView, None, None]:
yield sv
# Test all operations can be serialized/deserialized
- for operation in sv.operations:
+ for operation in sv.notifications:
assert_serialize_roundtrip(operation)
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index 86787186e3..d68088d702 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -13,7 +13,7 @@ from marimo._config.config import DEFAULT_CONFIG
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.msgspec_encoder import encode_json_str
-from marimo._messaging.ops import CellOp
+from marimo._messaging.notification import CellNotification
from marimo._server.export import (
export_as_wasm,
run_app_then_export_as_ipynb,
@@ -274,8 +274,15 @@ async def test_run_until_completion_with_stop():
argv=None,
)
assert did_error is False
- cell_ops = [op for op in session_view.operations if isinstance(op, CellOp)]
- snapshot("run_until_completion_with_stop.txt", _print_messages(cell_ops))
+ cell_notifications = [
+ op
+ for op in session_view.notifications
+ if isinstance(op, CellNotification)
+ ]
+ snapshot(
+ "run_until_completion_with_stop.txt",
+ _print_messages(cell_notifications),
+ )
@pytest.mark.skipif(
@@ -313,9 +320,13 @@ async def test_run_until_completion_with_stack_trace():
file_manager, cli_args={}, argv=None
)
assert did_error is True
- cell_ops = [op for op in session_view.operations if isinstance(op, CellOp)]
+ cell_notifications = [
+ op
+ for op in session_view.notifications
+ if isinstance(op, CellNotification)
+ ]
- messages = _print_messages(cell_ops)
+ messages = _print_messages(cell_notifications)
snapshot(
"run_until_completion_with_stack_trace.txt",
_delete_lines_with_files(messages),
@@ -403,7 +414,7 @@ def __():
assert "data:application/json" in result.contents
-def _print_messages(messages: list[CellOp]) -> str:
+def _print_messages(messages: list[CellNotification]) -> str:
result: list[dict[str, Any]] = []
for message in messages:
result.append(
@@ -488,10 +499,14 @@ async def test_run_until_completion_with_console_output(mock_echo: MagicMock):
if n_tries > limit:
_assert_contents()
- cell_ops = [op for op in session_view.operations if isinstance(op, CellOp)]
+ cell_notifications = [
+ op
+ for op in session_view.notifications
+ if isinstance(op, CellNotification)
+ ]
snapshot(
"run_until_completion_with_console_output.txt",
- _print_messages(cell_ops),
+ _print_messages(cell_notifications),
)
@@ -515,7 +530,7 @@ def test_export_as_html_with_serialization(session_view: SessionView):
# Add some test data to session view
cell_ids = list(file_manager.app.cell_manager.cell_ids())
- session_view.cell_operations[cell_ids[0]] = CellOp(
+ session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
@@ -536,7 +551,7 @@ def test_export_as_html_with_serialization(session_view: SessionView):
"print('Hello World')\nreturn 10"
)
- session_view.cell_operations[cell_ids[1]] = CellOp(
+ session_view.cell_notifications[cell_ids[1]] = CellNotification(
cell_id=cell_ids[1],
status="idle",
output=CellOutput(
@@ -586,7 +601,7 @@ def test_export_as_html_without_code(session_view: SessionView):
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
- session_view.cell_operations[cell_ids[0]] = CellOp(
+ session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
@@ -645,7 +660,7 @@ def test_export_as_html_with_files(session_view: SessionView):
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
- session_view.cell_operations[cell_ids[0]] = CellOp(
+ session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=None,
@@ -692,7 +707,7 @@ def test_export_as_html_with_cell_configs(session_view: SessionView):
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
- session_view.cell_operations[cell_ids[0]] = CellOp(
+ session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
@@ -751,7 +766,7 @@ def test_export_as_html_preserves_output_order(session_view: SessionView):
# Add cells in different order than execution
for i, cell_id in enumerate(cell_ids):
- session_view.cell_operations[cell_id] = CellOp(
+ session_view.cell_notifications[cell_id] = CellNotification(
cell_id=cell_id,
status="idle",
output=CellOutput(
@@ -808,7 +823,7 @@ def test_export_as_html_with_error_outputs(session_view: SessionView):
raising_cell=cell_ids[0],
)
- session_view.cell_operations[cell_ids[0]] = CellOp(
+ session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput.errors([error]),
@@ -851,7 +866,7 @@ def test_export_as_html_code_hash_consistency(session_view: SessionView):
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
- session_view.cell_operations[cell_ids[0]] = CellOp(
+ session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=None,
@@ -941,7 +956,7 @@ def test_export_html_replaces_virtual_files_in_outputs(
'<img src="./@file/100-test.png" alt="Test image">'
)
- session_view.cell_operations[cell_ids[0]] = CellOp(
+ session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
@@ -1020,7 +1035,7 @@ def test_export_html_replaces_multiple_virtual_files_complex(
cell_ids = list(file_manager.app.cell_manager.cell_ids())
# Cell 1: Image with virtual file
- session_view.cell_operations[cell_ids[0]] = CellOp(
+ session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
@@ -1036,7 +1051,7 @@ def test_export_html_replaces_multiple_virtual_files_complex(
)
# Cell 2: Markdown with virtual file
- session_view.cell_operations[cell_ids[1]] = CellOp(
+ session_view.cell_notifications[cell_ids[1]] = CellNotification(
cell_id=cell_ids[1],
status="idle",
output=CellOutput(
@@ -1052,7 +1067,7 @@ def test_export_html_replaces_multiple_virtual_files_complex(
)
# Cell 3: Mixed - virtual file and external URL
- session_view.cell_operations[cell_ids[2]] = CellOp(
+ session_view.cell_notifications[cell_ids[2]] = CellNotification(
cell_id=cell_ids[2],
status="idle",
output=CellOutput(
diff --git a/tests/_server/session/test_serialize_session.py b/tests/_server/session/test_serialize_session.py
index 627f7501a2..a5372a60bd 100644
--- a/tests/_server/session/test_serialize_session.py
+++ b/tests/_server/session/test_serialize_session.py
@@ -13,7 +13,7 @@ from marimo._ast.cell import CellConfig
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.ops import CellOp
+from marimo._messaging.notification import CellNotification
from marimo._runtime.requests import ExecuteMultipleRequest
from marimo._schemas.session import NotebookSessionV1
from marimo._server.session.serialize import (
@@ -47,7 +47,7 @@ def _build_code_hash_to_cell_id_mapping(
def test_serialize_basic_session(session_view: SessionView):
"""Test serialization of a basic session with a single cell with data output"""
view = session_view
- view.cell_operations[CellId_t("cell1")] = CellOp(
+ view.cell_notifications[CellId_t("cell1")] = CellNotification(
cell_id=CellId_t("cell1"),
status="idle",
output=CellOutput(
@@ -67,7 +67,7 @@ def test_serialize_basic_session(session_view: SessionView):
def test_serialize_session_with_error(session_view: SessionView):
"""Test serialization of a session with an error output"""
view = session_view
- view.cell_operations[CellId_t("cell1")] = CellOp(
+ view.cell_notifications[CellId_t("cell1")] = CellNotification(
cell_id=CellId_t("cell1"),
status="idle",
output=CellOutput(
@@ -89,7 +89,7 @@ def test_serialize_session_with_error(session_view: SessionView):
def test_serialize_session_with_console(session_view: SessionView):
"""Test serialization of a session with console output"""
view = session_view
- view.cell_operations["cell1"] = CellOp(
+ view.cell_notifications["cell1"] = CellNotification(
cell_id="cell1",
status="idle",
output=None,
@@ -116,7 +116,7 @@ def test_serialize_session_with_console(session_view: SessionView):
def test_serialize_session_with_mime_bundle(session_view: SessionView):
"""Test serialization of a session with a mime bundle output"""
view = session_view
- view.cell_operations["cell1"] = CellOp(
+ view.cell_notifications["cell1"] = CellNotification(
cell_id="cell1",
status="idle",
output=CellOutput(
@@ -151,7 +151,7 @@ def test_serialize_notebook_basic(session_view: SessionView):
)
# Add to session view
- view.cell_operations[cell_id] = CellOp(
+ view.cell_notifications[cell_id] = CellNotification(
cell_id=cell_id,
status="idle",
output=CellOutput(
@@ -203,7 +203,7 @@ def test_serialize_notebook_multiple_cells(session_view: SessionView):
)
# Add first cell to session view
- view.cell_operations[cell_id1] = CellOp(
+ view.cell_notifications[cell_id1] = CellNotification(
cell_id=cell_id1,
status="idle",
output=None,
@@ -213,7 +213,7 @@ def test_serialize_notebook_multiple_cells(session_view: SessionView):
view.last_executed_code[cell_id1] = "x = 1"
# Add second cell to session view
- view.cell_operations[cell_id2] = CellOp(
+ view.cell_notifications[cell_id2] = CellNotification(
cell_id=cell_id2,
status="idle",
output=CellOutput(
@@ -274,7 +274,7 @@ def test_serialize_notebook_multiple_cells_not_top_down(
config=CellConfig(column=0, disabled=False),
)
- view.cell_operations[cell_id2] = CellOp(
+ view.cell_notifications[cell_id2] = CellNotification(
cell_id=cell_id2,
status="idle",
output=None,
@@ -284,7 +284,7 @@ def test_serialize_notebook_multiple_cells_not_top_down(
view.last_executed_code[cell_id2] = "x = 1"
# Add second cell to session view
- view.cell_operations[cell_id1] = CellOp(
+ view.cell_notifications[cell_id1] = CellNotification(
cell_id=cell_id1,
status="idle",
output=CellOutput(
@@ -331,7 +331,7 @@ def test_serialize_notebook_empty_code(session_view: SessionView):
)
# Add to session view but without executed code
- view.cell_operations[cell_id] = CellOp(
+ view.cell_notifications[cell_id] = CellNotification(
cell_id=cell_id,
status="idle",
output=None,
@@ -382,7 +382,7 @@ def test_serialize_notebook_missing_cell_data(session_view: SessionView):
# Add cell to session view but don't register it with cell manager
cell_id = CellId_t("orphan_cell")
- view.cell_operations[cell_id] = CellOp(
+ view.cell_notifications[cell_id] = CellNotification(
cell_id=cell_id,
status="idle",
output=CellOutput(
@@ -429,8 +429,8 @@ def test_deserialize_basic_session():
code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
view = deserialize_session(session, code_hash_to_cell_id)
- assert CellId_t("cell1") in view.cell_operations
- cell = view.cell_operations[CellId_t("cell1")]
+ assert CellId_t("cell1") in view.cell_notifications
+ cell = view.cell_notifications[CellId_t("cell1")]
assert cell.output is not None
assert cell.output.channel == CellChannel.OUTPUT
assert cell.output.mimetype == "text/plain"
@@ -461,8 +461,8 @@ def test_deserialize_session_with_error():
code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
view = deserialize_session(session, code_hash_to_cell_id)
- assert "cell1" in view.cell_operations
- cell = view.cell_operations["cell1"]
+ assert "cell1" in view.cell_notifications
+ cell = view.cell_notifications["cell1"]
assert cell.output is not None
assert cell.output.channel == CellChannel.MARIMO_ERROR
assert cell.output.mimetype == "application/vnd.marimo+error"
@@ -500,8 +500,8 @@ def test_deserialize_session_with_console():
code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
view = deserialize_session(session, code_hash_to_cell_id)
- assert "cell1" in view.cell_operations
- cell = view.cell_operations["cell1"]
+ assert "cell1" in view.cell_notifications
+ cell = view.cell_notifications["cell1"]
assert isinstance(cell.console, list)
assert len(cell.console) == 2
console_outputs = cell.console
@@ -516,7 +516,7 @@ def test_deserialize_session_with_console():
async def test_session_cache_writer(session_view: SessionView):
"""Test AsyncWriter writes session data periodically"""
view = session_view
- view.cell_operations["cell1"] = CellOp(
+ view.cell_notifications["cell1"] = CellNotification(
cell_id="cell1",
status="idle",
output=CellOutput(
@@ -614,8 +614,8 @@ def test_deserialize_mime_bundle():
code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
view = deserialize_session(session, code_hash_to_cell_id)
- assert "cell1" in view.cell_operations
- cell = view.cell_operations["cell1"]
+ assert "cell1" in view.cell_notifications
+ cell = view.cell_notifications["cell1"]
assert cell.output is not None
assert cell.output.channel == CellChannel.OUTPUT
assert cell.output.mimetype == "application/vnd.marimo+mimebundle"
@@ -642,8 +642,8 @@ def test_deserialize_empty_data():
code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
view = deserialize_session(session, code_hash_to_cell_id)
- assert "cell1" in view.cell_operations
- cell = view.cell_operations["cell1"]
+ assert "cell1" in view.cell_notifications
+ cell = view.cell_notifications["cell1"]
assert cell.output is None
@@ -690,8 +690,8 @@ def test_deserialize_error_with_traceback():
code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
view = deserialize_session(session, code_hash_to_cell_id)
- assert "eAXK" in view.cell_operations
- cell = view.cell_operations["eAXK"]
+ assert "eAXK" in view.cell_notifications
+ cell = view.cell_notifications["eAXK"]
assert cell.output is not None
assert cell.output.channel == CellChannel.MARIMO_ERROR
assert cell.output.mimetype == "application/vnd.marimo+error"
@@ -740,8 +740,8 @@ def test_deserialize_session_with_console_mimetype():
code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
view = deserialize_session(session, code_hash_to_cell_id)
- assert "cell1" in view.cell_operations
- cell = view.cell_operations["cell1"]
+ assert "cell1" in view.cell_notifications
+ cell = view.cell_notifications["cell1"]
assert isinstance(cell.console, list)
assert len(cell.console) == 2
console_outputs = cell.console
@@ -756,7 +756,7 @@ def test_deserialize_session_with_console_mimetype():
def test_serialize_session_with_dict_error():
"""Test serialization of a session with a dictionary error"""
view = SessionView()
- view.cell_operations["cell1"] = CellOp(
+ view.cell_notifications["cell1"] = CellNotification(
cell_id="cell1",
status="idle",
output=CellOutput(
@@ -798,7 +798,7 @@ def test_serialize_session_with_mixed_error_formats(session_view: SessionView):
UnknownError(msg="Runtime error occurred", error_type="RuntimeError"),
]
- view.cell_operations[CellId_t("cell1")] = CellOp(
+ view.cell_notifications[CellId_t("cell1")] = CellNotification(
cell_id=CellId_t("cell1"),
status="idle",
output=CellOutput(
@@ -899,7 +899,7 @@ class TestSessionCacheManager:
):
"""Test reading session view from cache file"""
view = session_view
- view.cell_operations["cell1"] = CellOp(
+ view.cell_notifications["cell1"] = CellNotification(
cell_id="cell1",
status="idle",
output=CellOutput(
@@ -929,14 +929,14 @@ class TestSessionCacheManager:
cell_ids=("cell1",),
)
)
- assert loaded_view.cell_operations is not None
+ assert loaded_view.cell_notifications is not None
async def test_read_session_view_cache_miss_code(
self, session_view: SessionView
):
"""Test reading session view from cache file"""
view = session_view
- view.cell_operations["cell1"] = CellOp(
+ view.cell_notifications["cell1"] = CellNotification(
cell_id="cell1",
status="idle",
output=CellOutput(
@@ -970,7 +970,7 @@ class TestSessionCacheManager:
cell_ids=("cell1",),
)
)
- assert not loaded_view.cell_operations
+ assert not loaded_view.cell_notifications
async def test_read_session_view_cache_miss_version(
self, session_view: SessionView
@@ -1002,14 +1002,14 @@ class TestSessionCacheManager:
cell_ids=("1", "2"),
)
)
- assert not loaded_view.cell_operations
+ assert not loaded_view.cell_notifications
async def test_read_session_view_cache_hit(
self, session_view: SessionView
):
"""Test reading session view from cache file"""
view = session_view
- view.cell_operations["cell1"] = CellOp(
+ view.cell_notifications["cell1"] = CellNotification(
cell_id="cell1",
status="idle",
output=CellOutput(
@@ -1020,7 +1020,7 @@ class TestSessionCacheManager:
console=[],
timestamp=0,
)
- view.cell_operations["cell2"] = CellOp(
+ view.cell_notifications["cell2"] = CellNotification(
cell_id="cell2",
status="idle",
output=CellOutput(
@@ -1060,4 +1060,4 @@ class TestSessionCacheManager:
)
)
# cache hit: codes and version match
- assert len(loaded_view.cell_operations) == 2
+ assert len(loaded_view.cell_notifications) == 2
diff --git a/tests/_server/session/test_serialize_session_missing_type.py b/tests/_server/session/test_serialize_session_missing_type.py
index 9bc72f41fc..b61f107064 100644
--- a/tests/_server/session/test_serialize_session_missing_type.py
+++ b/tests/_server/session/test_serialize_session_missing_type.py
@@ -1,5 +1,7 @@
+from __future__ import annotations
+
from marimo._messaging.cell_output import CellChannel, CellOutput
-from marimo._messaging.ops import CellOp
+from marimo._messaging.notification import CellNotification
from marimo._server.session.serialize import serialize_session_view
from marimo._server.session.session_view import SessionView
@@ -7,7 +9,7 @@ from marimo._server.session.session_view import SessionView
def test_serialize_session_with_dict_error_missing_type():
"""Test serialization of a session with a dictionary error missing the type key"""
view = SessionView()
- view.cell_operations["cell1"] = CellOp(
+ view.cell_notifications["cell1"] = CellNotification(
cell_id="cell1",
status="idle",
output=CellOutput(
diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.py
index 71e4e80f0c..a5142bacd5 100644
--- a/tests/_server/session/test_session_view.py
+++ b/tests/_server/session/test_session_view.py
@@ -14,22 +14,22 @@ from marimo._data.models import (
)
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.msgspec_encoder import asdict as serialize
-from marimo._messaging.ops import (
- CellOp,
- Datasets,
- DataSourceConnections,
- InstallingPackageAlert,
- SendUIElementMessage,
+from marimo._messaging.notification import (
+ CellNotification,
+ DatasetsNotification,
+ DataSourceConnectionsNotification,
+ InstallingPackageAlertNotification,
SQLMetadata,
- SQLTableListPreview,
- SQLTablePreview,
- StartupLogs,
- UpdateCellCodes,
- UpdateCellIdsRequest,
- VariableDeclaration,
- Variables,
+ SQLTableListPreviewNotification,
+ SQLTablePreviewNotification,
+ StartupLogsNotification,
+ UIElementMessageNotification,
+ UpdateCellCodesNotification,
+ UpdateCellIdsNotification,
+ VariableDeclarationNotification,
+ VariablesNotification,
VariableValue,
- VariableValues,
+ VariableValuesNotification,
serialize_kernel_message,
)
from marimo._runtime.requests import (
@@ -63,86 +63,88 @@ updated_status: RuntimeStateType = "running"
def test_cell_ids(session_view: SessionView) -> None:
assert session_view.cell_ids is None
- session_view.add_operation(
- UpdateCellIdsRequest(
+ session_view.add_notification(
+ UpdateCellIdsNotification(
cell_ids=[cell_id],
)
)
- operation = session_view.operations[0]
- assert isinstance(operation, UpdateCellIdsRequest)
+ operation = session_view.notifications[0]
+ assert isinstance(operation, UpdateCellIdsNotification)
assert operation.cell_ids == [cell_id]
-def test_session_view_cell_op(session_view: SessionView) -> None:
- # Create initial CellOp
- initial_cell_op = CellOp(
+def test_session_view_cell_notification(session_view: SessionView) -> None:
+ # Create initial CellNotification
+ initial_cell_notification = CellNotification(
cell_id=cell_id, output=initial_output, status=initial_status
)
- session_view.add_operation(initial_cell_op)
+ session_view.add_notification(initial_cell_notification)
- # Add updated CellOp to SessionView
- updated_cell_op = CellOp(
+ # Add updated CellNotification to SessionView
+ updated_cell_notification = CellNotification(
cell_id=cell_id, output=updated_output, status=updated_status
)
- session_view.add_operation(updated_cell_op)
+ session_view.add_notification(updated_cell_notification)
- assert session_view.cell_operations[cell_id].output == updated_output
- assert session_view.cell_operations[cell_id].status == updated_status
+ assert session_view.cell_notifications[cell_id].output == updated_output
+ assert session_view.cell_notifications[cell_id].status == updated_status
# Test adding Variables to SessionView
def test_session_view_variables(session_view: SessionView) -> None:
# Create Variables operation
- variables_op = Variables(
+ variables_op = VariablesNotification(
variables=[
- VariableDeclaration(name="var1", declared_by=[], used_by=[])
+ VariableDeclarationNotification(
+ name="var1", declared_by=[], used_by=[]
+ )
]
)
- session_view.add_operation(variables_op)
+ session_view.add_notification(variables_op)
# Check if the Variables operation was added correctly
- assert session_view.variable_operations == variables_op
+ assert session_view.variable_notifications == variables_op
# Test adding VariableValues to SessionView
def test_session_view_variable_values(session_view: SessionView) -> None:
# Create Variables operation
- variables_op = Variables(
+ variables_op = VariablesNotification(
variables=[
- VariableDeclaration(
+ VariableDeclarationNotification(
name="var1", declared_by=[cell_id], used_by=[]
),
- VariableDeclaration(
+ VariableDeclarationNotification(
name="var2", declared_by=[cell_id], used_by=[]
),
]
)
- session_view.add_operation(variables_op)
+ session_view.add_notification(variables_op)
# Create VariableValues operation
- variable_values_op = VariableValues(
+ variable_values_op = VariableValuesNotification(
variables=[
VariableValue.create(name="var1", value=1),
VariableValue.create(name="var2", value="hello"),
]
)
- session_view.add_operation(variable_values_op)
+ session_view.add_notification(variable_values_op)
variables_names = session_view.variable_values.keys()
assert list(variables_names) == ["var1", "var2"]
# Add new Variable operation without the previous variables
- variables_op = Variables(
+ variables_op = VariablesNotification(
variables=[
- VariableDeclaration(
+ VariableDeclarationNotification(
name="var2", declared_by=[cell_id], used_by=[]
),
- VariableDeclaration(
+ VariableDeclarationNotification(
name="var3", declared_by=[cell_id], used_by=[]
),
]
)
- session_view.add_operation(variables_op)
+ session_view.add_notification(variables_op)
variables_names = session_view.variable_values.keys()
# var1 was removed, var2 was not changed, var3 has no value yet
@@ -185,8 +187,8 @@ def test_model_message_values(session_view: SessionView) -> None:
model_id = WidgetModelId("test_model")
model_id2 = WidgetModelId("test_model2")
- session_view.add_operation(
- SendUIElementMessage(
+ session_view.add_notification(
+ UIElementMessageNotification(
model_id=model_id,
message={"key": "value"},
ui_element=None,
@@ -196,8 +198,8 @@ def test_model_message_values(session_view: SessionView) -> None:
assert session_view.model_messages[model_id][0].message == {"key": "value"}
# Can add to existing model
- session_view.add_operation(
- SendUIElementMessage(
+ session_view.add_notification(
+ UIElementMessageNotification(
model_id=model_id,
message={"key": "new_value"},
ui_element=None,
@@ -209,8 +211,8 @@ def test_model_message_values(session_view: SessionView) -> None:
}
# Can add multiple models
- session_view.add_operation(
- SendUIElementMessage(
+ session_view.add_notification(
+ UIElementMessageNotification(
model_id=model_id2,
message={"key2": "value2"},
ui_element=None,
@@ -265,23 +267,23 @@ def test_serialize_parse_variable_value() -> None:
def test_add_variables(session_view: SessionView) -> None:
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- Variables(
+ VariablesNotification(
variables=[
- VariableDeclaration(
+ VariableDeclarationNotification(
name="var1", declared_by=[cell_id], used_by=[]
),
- VariableDeclaration(
+ VariableDeclarationNotification(
name="var2", declared_by=[cell_id], used_by=[]
),
]
)
)
)
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- VariableValues(
+ VariableValuesNotification(
variables=[
VariableValue.create(name="var1", value=1),
VariableValue.create(name="var2", value="hello"),
@@ -290,8 +292,8 @@ def test_add_variables(session_view: SessionView) -> None:
)
)
- assert session_view.variable_operations.variables[0].name == "var1"
- assert session_view.variable_operations.variables[1].name == "var2"
+ assert session_view.variable_notifications.variables[0].name == "var1"
+ assert session_view.variable_notifications.variables[1].name == "var2"
assert session_view.variable_values["var1"].value == "1"
assert session_view.variable_values["var1"].datatype == "int"
assert session_view.variable_values["var2"].value == "hello"
@@ -299,9 +301,9 @@ def test_add_variables(session_view: SessionView) -> None:
def test_add_datasets(session_view: SessionView) -> None:
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- Datasets(
+ DatasetsNotification(
tables=[
DataTable(
source_type="local",
@@ -347,9 +349,9 @@ def test_add_datasets(session_view: SessionView) -> None:
# Can add a new table and overwrite an existing table
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- Datasets(
+ DatasetsNotification(
tables=[
DataTable(
source_type="local",
@@ -391,11 +393,11 @@ def test_add_datasets(session_view: SessionView) -> None:
assert session_view.datasets.tables[2].variable_name == "df3"
# Can filter out tables from new variables
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- Variables(
+ VariablesNotification(
variables=[
- VariableDeclaration(
+ VariableDeclarationNotification(
name="df2", declared_by=[cell_id], used_by=[]
),
]
@@ -408,9 +410,9 @@ def test_add_datasets(session_view: SessionView) -> None:
def test_add_datasets_clear_channel(session_view: SessionView) -> None:
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- Datasets(
+ DatasetsNotification(
tables=[
DataTable(
source_type="duckdb",
@@ -441,9 +443,9 @@ def test_add_datasets_clear_channel(session_view: SessionView) -> None:
assert "db.table1" in names
assert "df1" in names
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- Datasets(
+ DatasetsNotification(
tables=[
DataTable(
source_type="local",
@@ -469,9 +471,9 @@ def test_add_datasets_clear_channel(session_view: SessionView) -> None:
def test_add_data_source_connections(session_view: SessionView) -> None:
# Add initial connections
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- DataSourceConnections(
+ DataSourceConnectionsNotification(
connections=[
DataSourceConnection(
source="duckdb",
@@ -506,9 +508,9 @@ def test_add_data_source_connections(session_view: SessionView) -> None:
assert INTERNAL_DUCKDB_ENGINE in names
# Add new connection and update existing
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- DataSourceConnections(
+ DataSourceConnectionsNotification(
connections=[
DataSourceConnection(
source="duckdb",
@@ -544,14 +546,14 @@ def test_add_data_source_connections(session_view: SessionView) -> None:
assert INTERNAL_DUCKDB_ENGINE in names
# Check connectors in operations
- assert session_view.data_connectors in session_view.operations
+ assert session_view.data_connectors in session_view.notifications
# Filter out connections from variables
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- Variables(
+ VariablesNotification(
variables=[
- VariableDeclaration(
+ VariableDeclarationNotification(
name="mysql1", declared_by=[cell_id], used_by=[]
),
]
@@ -570,9 +572,9 @@ def test_add_sql_table_previews() -> None:
session_view = SessionView()
# Add initial connections
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- DataSourceConnections(
+ DataSourceConnectionsNotification(
connections=[
DataSourceConnection(
source="duckdb",
@@ -620,9 +622,9 @@ def test_add_sql_table_previews() -> None:
)
]
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- SQLTablePreview(
+ SQLTablePreviewNotification(
metadata=SQLMetadata(
connection="connection1", database="db1", schema="db1"
),
@@ -646,9 +648,9 @@ def test_add_sql_table_previews() -> None:
)
# Add sql table preview list
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- SQLTableListPreview(
+ SQLTableListPreviewNotification(
metadata=SQLMetadata(
connection="connection1", database="db1", schema="db1"
),
@@ -685,17 +687,17 @@ def test_add_sql_table_previews() -> None:
]
-def test_add_cell_op(session_view: SessionView) -> None:
- session_view.add_raw_operation(
+def test_add_cell_notification(session_view: SessionView) -> None:
+ session_view.add_raw_notification(
serialize_kernel_message(
- CellOp(
+ CellNotification(
cell_id=cell_id, output=initial_output, status=initial_status
)
)
)
- assert session_view.cell_operations[cell_id].output == initial_output
- assert session_view.cell_operations[cell_id].status == initial_status
+ assert session_view.cell_notifications[cell_id].output == initial_output
+ assert session_view.cell_notifications[cell_id].status == initial_status
# patch time
@@ -704,15 +706,15 @@ def test_combine_console_outputs(
time_mock: Any, session_view: SessionView
) -> None:
del time_mock
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout("one"),
status="running",
)
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout("two"),
status="running",
@@ -720,42 +722,42 @@ def test_combine_console_outputs(
)
# Consecutive text/plain stdout outputs are merged
- assert session_view.cell_operations[cell_id].console == [
+ assert session_view.cell_notifications[cell_id].console == [
CellOutput.stdout("onetwo"),
]
# Moves to queued
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=None,
status="queued",
)
)
- assert session_view.cell_operations[cell_id].console == [
+ assert session_view.cell_notifications[cell_id].console == [
CellOutput.stdout("onetwo"),
]
# Moves to running clears console
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=None,
status="running",
)
)
- assert session_view.cell_operations[cell_id].console == []
+ assert session_view.cell_notifications[cell_id].console == []
# Write again
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout("three"),
status="running",
)
)
- assert session_view.cell_operations[cell_id].console == [
+ assert session_view.cell_notifications[cell_id].console == [
CellOutput.stdout("three")
]
@@ -763,29 +765,29 @@ def test_combine_console_outputs(
@patch("time.time", return_value=123)
def test_stdin(time_mock: Any, session_view: SessionView) -> None:
del time_mock
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout("Hello"),
status="running",
)
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdin("What is your name?"),
status="running",
)
)
- assert session_view.cell_operations[cell_id].console == [
+ assert session_view.cell_notifications[cell_id].console == [
CellOutput.stdout("Hello"),
CellOutput.stdin("What is your name?"),
]
session_view.add_stdin("marimo")
- assert session_view.cell_operations[cell_id].console == [
+ assert session_view.cell_notifications[cell_id].console == [
CellOutput.stdout("Hello"),
CellOutput.stdout("What is your name? marimo\n"),
]
@@ -799,22 +801,22 @@ def test_merge_consecutive_text_plain_outputs(
del time_mock
# Add multiple consecutive stdout outputs
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout("Hello "),
status="running",
)
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout("World"),
status="running",
)
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout("!"),
status="running",
@@ -822,12 +824,13 @@ def test_merge_consecutive_text_plain_outputs(
)
# Should be merged into a single output
- assert len(session_view.cell_operations[cell_id].console) == 1
+ assert len(session_view.cell_notifications[cell_id].console) == 1
assert (
- session_view.cell_operations[cell_id].console[0].data == "Hello World!"
+ session_view.cell_notifications[cell_id].console[0].data
+ == "Hello World!"
)
assert (
- session_view.cell_operations[cell_id].console[0].channel
+ session_view.cell_notifications[cell_id].console[0].channel
== CellChannel.STDOUT
)
@@ -839,15 +842,15 @@ def test_merge_different_channels_not_merged(
"""Test that outputs with different channels are not merged."""
del time_mock
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout("stdout message"),
status="running",
)
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stderr("stderr message"),
status="running",
@@ -855,13 +858,13 @@ def test_merge_different_channels_not_merged(
)
# Should remain separate
- assert len(session_view.cell_operations[cell_id].console) == 2
+ assert len(session_view.cell_notifications[cell_id].console) == 2
assert (
- session_view.cell_operations[cell_id].console[0].channel
+ session_view.cell_notifications[cell_id].console[0].channel
== CellChannel.STDOUT
)
assert (
- session_view.cell_operations[cell_id].console[1].channel
+ session_view.cell_notifications[cell_id].console[1].channel
== CellChannel.STDERR
)
@@ -873,15 +876,15 @@ def test_merge_different_mimetypes_not_merged(
"""Test that outputs with different mimetypes are not merged."""
del time_mock
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout("plain text", mimetype="text/plain"),
status="running",
)
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout("html content", mimetype="text/html"),
status="running",
@@ -889,13 +892,13 @@ def test_merge_different_mimetypes_not_merged(
)
# Should remain separate
- assert len(session_view.cell_operations[cell_id].console) == 2
+ assert len(session_view.cell_notifications[cell_id].console) == 2
assert (
- session_view.cell_operations[cell_id].console[0].mimetype
+ session_view.cell_notifications[cell_id].console[0].mimetype
== "text/plain"
)
assert (
- session_view.cell_operations[cell_id].console[1].mimetype
+ session_view.cell_notifications[cell_id].console[1].mimetype
== "text/html"
)
@@ -907,15 +910,15 @@ def test_merge_with_non_string_data_not_merged(
"""Test that outputs with non-string data are not merged."""
del time_mock
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput.stdout("text"),
status="running",
)
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=CellOutput(
channel=CellChannel.STDOUT,
@@ -927,22 +930,22 @@ def test_merge_with_non_string_data_not_merged(
)
# Should remain separate
- assert len(session_view.cell_operations[cell_id].console) == 2
+ assert len(session_view.cell_notifications[cell_id].console) == 2
@patch("time.time", return_value=123)
def test_get_cell_outputs(time_mock: Any, session_view: SessionView) -> None:
del time_mock
cell_2_id = "cell_2"
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
output=initial_output,
status=initial_status,
),
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_2_id,
output=None,
status=updated_status,
@@ -956,15 +959,15 @@ def test_get_cell_outputs(time_mock: Any, session_view: SessionView) -> None:
cell_id: initial_output
}
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
output=updated_output,
status=updated_status,
)
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_2_id,
output=updated_output,
status=updated_status,
@@ -983,15 +986,15 @@ def test_get_cell_console_outputs(
) -> None:
del time_mock
cell_2_id = "cell_2"
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=[CellOutput.stdout("one")],
status=initial_status,
)
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_2_id,
console=None,
status=updated_status,
@@ -1005,15 +1008,15 @@ def test_get_cell_console_outputs(
cell_id: [CellOutput.stdout("one")],
}
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
console=[CellOutput.stdout("two")],
status=updated_status,
)
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_2_id,
console=[CellOutput.stdout("two")],
status=updated_status,
@@ -1043,8 +1046,8 @@ def test_mark_auto_export(session_view: SessionView):
session_view.mark_auto_export_html()
session_view.mark_auto_export_md()
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
output=initial_output,
status=initial_status,
@@ -1065,50 +1068,50 @@ def test_stale_code(session_view: SessionView) -> None:
assert session_view.stale_code is None
# Add stale code operation
- stale_code_op = UpdateCellCodes(
+ stale_code_op = UpdateCellCodesNotification(
cell_ids=["cell1"],
codes=["print('hello')"],
code_is_stale=True,
)
- session_view.add_operation(stale_code_op)
+ session_view.add_notification(stale_code_op)
# Verify stale code is tracked
assert session_view.stale_code == stale_code_op
- assert session_view.stale_code in session_view.operations
+ assert session_view.stale_code in session_view.notifications
# Add non-stale code operation
- non_stale_code_op = UpdateCellCodes(
+ non_stale_code_op = UpdateCellCodesNotification(
cell_ids=["cell2"],
codes=["print('world')"],
code_is_stale=False,
)
- session_view.add_operation(non_stale_code_op)
+ session_view.add_notification(non_stale_code_op)
# Verify non-stale code doesn't affect stale_code tracking
assert session_view.stale_code == stale_code_op
- assert session_view.stale_code in session_view.operations
+ assert session_view.stale_code in session_view.notifications
# Update stale code
- new_stale_code_op = UpdateCellCodes(
+ new_stale_code_op = UpdateCellCodesNotification(
cell_ids=["cell3"],
codes=["print('updated')"],
code_is_stale=True,
)
- session_view.add_operation(new_stale_code_op)
+ session_view.add_notification(new_stale_code_op)
# Verify stale code is updated
assert session_view.stale_code == new_stale_code_op
- assert session_view.stale_code in session_view.operations
- assert stale_code_op not in session_view.operations
+ assert session_view.stale_code in session_view.notifications
+ assert stale_code_op not in session_view.notifications
def test_dataset_filter_by_engine_and_variable(
session_view: SessionView,
) -> None:
# Initially add three tables: one with an engine, one with a variable name, and one with neither
- session_view.add_raw_operation(
+ session_view.add_raw_notification(
serialize_kernel_message(
- Datasets(
+ DatasetsNotification(
tables=[
DataTable(
source_type="connection",
@@ -1148,13 +1151,13 @@ def test_dataset_filter_by_engine_and_variable(
assert len(session_view.datasets.tables) == 3
# Step 1: Add operation of all variables
- session_view.add_operation(
- Variables(
+ session_view.add_notification(
+ VariablesNotification(
variables=[
- VariableDeclaration(
+ VariableDeclarationNotification(
name="some_engine", declared_by=[], used_by=[]
),
- VariableDeclaration(
+ VariableDeclarationNotification(
name="some_var", declared_by=[], used_by=[]
),
]
@@ -1163,10 +1166,10 @@ def test_dataset_filter_by_engine_and_variable(
assert len(session_view.datasets.tables) == 3
# Step 2: Only "some_engine" is in scope => keep table_with_engine + table_none
- session_view.add_operation(
- Variables(
+ session_view.add_notification(
+ VariablesNotification(
variables=[
- VariableDeclaration(
+ VariableDeclarationNotification(
name="some_engine", declared_by=[], used_by=[]
)
]
@@ -1178,7 +1181,7 @@ def test_dataset_filter_by_engine_and_variable(
assert "table_none" in table_names
# Step 3: No variables => only table with neither engine nor variable_name is kept
- session_view.add_operation(Variables(variables=[]))
+ session_view.add_notification(VariablesNotification(variables=[]))
table_names = [t.name for t in session_view.datasets.tables]
assert table_names == ["table_none"]
@@ -1190,16 +1193,16 @@ def test_is_empty(session_view: SessionView) -> None:
assert session_view.is_empty()
# Add a cell operation without output or console
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
status=initial_status,
)
)
# Add a cell operation
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id=cell_id,
output=initial_output,
status=initial_status,
@@ -1214,15 +1217,15 @@ def test_is_empty_multiple_operations(session_view: SessionView) -> None:
assert session_view.is_empty()
# Add multiple operations - should still not be empty
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id="cell1",
output=initial_output,
status="idle",
)
)
- session_view.add_operation(
- CellOp(
+ session_view.add_notification(
+ CellNotification(
cell_id="cell2",
output=updated_output,
status="idle",
@@ -1233,16 +1236,20 @@ def test_is_empty_multiple_operations(session_view: SessionView) -> None:
def test_session_view_startup_logs(session_view: SessionView) -> None:
# Test adding a startup log with "start" status
- start_log = StartupLogs(content="Starting process...", status="start")
- session_view.add_operation(start_log)
+ start_log = StartupLogsNotification(
+ content="Starting process...", status="start"
+ )
+ session_view.add_notification(start_log)
assert session_view.startup_logs is not None
assert session_view.startup_logs.content == "Starting process..."
assert session_view.startup_logs.status == "start"
# Test appending to startup log
- append_log = StartupLogs(content=" more content", status="append")
- session_view.add_operation(append_log)
+ append_log = StartupLogsNotification(
+ content=" more content", status="append"
+ )
+ session_view.add_notification(append_log)
assert session_view.startup_logs is not None
assert (
@@ -1251,8 +1258,8 @@ def test_session_view_startup_logs(session_view: SessionView) -> None:
assert session_view.startup_logs.status == "append"
# Test marking startup log as done
- done_log = StartupLogs(content=" done!", status="done")
- session_view.add_operation(done_log)
+ done_log = StartupLogsNotification(content=" done!", status="done")
+ session_view.add_notification(done_log)
assert session_view.startup_logs is not None
assert (
@@ -1266,22 +1273,26 @@ def test_session_view_startup_logs_operations_exclude_done(
session_view: SessionView,
) -> None:
# Add startup log in progress
- start_log = StartupLogs(content="Starting...", status="start")
- session_view.add_operation(start_log)
+ start_log = StartupLogsNotification(content="Starting...", status="start")
+ session_view.add_notification(start_log)
# Should include in operations while in progress
- operations = session_view.operations
- startup_ops = [op for op in operations if isinstance(op, StartupLogs)]
+ operations = session_view.notifications
+ startup_ops = [
+ op for op in operations if isinstance(op, StartupLogsNotification)
+ ]
assert len(startup_ops) == 1
assert startup_ops[0].status == "start"
# Mark as done
- done_log = StartupLogs(content=" complete", status="done")
- session_view.add_operation(done_log)
+ done_log = StartupLogsNotification(content=" complete", status="done")
+ session_view.add_notification(done_log)
# Should not include done startup logs in operations
- operations = session_view.operations
- startup_ops = [op for op in operations if isinstance(op, StartupLogs)]
+ operations = session_view.notifications
+ startup_ops = [
+ op for op in operations if isinstance(op, StartupLogsNotification)
+ ]
assert len(startup_ops) == 0
@@ -1289,8 +1300,10 @@ def test_session_view_startup_logs_standalone_done(
session_view: SessionView,
) -> None:
# Add a standalone "done" log without prior start/append
- done_log = StartupLogs(content="Process complete", status="done")
- session_view.add_operation(done_log)
+ done_log = StartupLogsNotification(
+ content="Process complete", status="done"
+ )
+ session_view.add_notification(done_log)
assert session_view.startup_logs is not None
assert session_view.startup_logs.content == "Process complete"
@@ -1309,13 +1322,13 @@ def test_session_view_package_logs_initialization(
def test_session_view_package_logs_start(session_view: SessionView) -> None:
"""Test SessionView handles package logs start status."""
- alert = InstallingPackageAlert(
+ alert = InstallingPackageAlertNotification(
packages={"numpy": "installing"},
logs={"numpy": "Installing numpy...\n"},
log_status="start",
)
- session_view.add_operation(alert)
+ session_view.add_notification(alert)
assert "numpy" in session_view.package_logs
assert session_view.package_logs["numpy"] == "Installing numpy...\n"
@@ -1325,20 +1338,20 @@ def test_session_view_package_logs_append(session_view: SessionView) -> None:
"""Test SessionView handles package logs append status."""
# Start with initial log
- start_alert = InstallingPackageAlert(
+ start_alert = InstallingPackageAlertNotification(
packages={"pandas": "installing"},
logs={"pandas": "Starting installation...\n"},
log_status="start",
)
- session_view.add_operation(start_alert)
+ session_view.add_notification(start_alert)
# Append more logs
- append_alert = InstallingPackageAlert(
+ append_alert = InstallingPackageAlertNotification(
packages={"pandas": "installing"},
logs={"pandas": "Downloading dependencies...\n"},
log_status="append",
)
- session_view.add_operation(append_alert)
+ session_view.add_notification(append_alert)
expected_content = (
"Starting installation...\nDownloading dependencies...\n"
@@ -1350,28 +1363,28 @@ def test_session_view_package_logs_done(session_view: SessionView) -> None:
"""Test SessionView handles package logs done status."""
# Start installation
- start_alert = InstallingPackageAlert(
+ start_alert = InstallingPackageAlertNotification(
packages={"scipy": "installing"},
logs={"scipy": "Installing scipy...\n"},
log_status="start",
)
- session_view.add_operation(start_alert)
+ session_view.add_notification(start_alert)
# Add progress log
- append_alert = InstallingPackageAlert(
+ append_alert = InstallingPackageAlertNotification(
packages={"scipy": "installing"},
logs={"scipy": "Building wheels...\n"},
log_status="append",
)
- session_view.add_operation(append_alert)
+ session_view.add_notification(append_alert)
# Finish installation
- done_alert = InstallingPackageAlert(
+ done_alert = InstallingPackageAlertNotification(
packages={"scipy": "installed"},
logs={"scipy": "Successfully installed scipy!\n"},
log_status="done",
)
- session_view.add_operation(done_alert)
+ session_view.add_notification(done_alert)
expected_content = (
"Installing scipy...\n"
@@ -1387,7 +1400,7 @@ def test_session_view_package_logs_multiple_packages(
"""Test SessionView handles logs for multiple packages simultaneously."""
# Start installing multiple packages
- multi_alert = InstallingPackageAlert(
+ multi_alert = InstallingPackageAlertNotification(
packages={"numpy": "installing", "pandas": "installing"},
logs={
"numpy": "Starting numpy install...\n",
@@ -1395,23 +1408,23 @@ def test_session_view_package_logs_multiple_packages(
},
log_status="start",
)
- session_view.add_operation(multi_alert)
+ session_view.add_notification(multi_alert)
# Add logs for numpy only
- numpy_alert = InstallingPackageAlert(
+ numpy_alert = InstallingPackageAlertNotification(
packages={"numpy": "installing", "pandas": "installing"},
logs={"numpy": "Numpy progress...\n"},
log_status="append",
)
- session_view.add_operation(numpy_alert)
+ session_view.add_notification(numpy_alert)
# Add logs for pandas only
- pandas_alert = InstallingPackageAlert(
+ pandas_alert = InstallingPackageAlertNotification(
packages={"numpy": "installing", "pandas": "installing"},
logs={"pandas": "Pandas progress...\n"},
log_status="append",
)
- session_view.add_operation(pandas_alert)
+ session_view.add_notification(pandas_alert)
assert len(session_view.package_logs) == 2
assert "numpy" in session_view.package_logs
@@ -1431,8 +1444,10 @@ def test_session_view_package_logs_without_logs(
"""Test SessionView handles InstallingPackageAlert without logs (backward compatibility)."""
# Old-style alert without logs
- alert = InstallingPackageAlert(packages={"requests": "installing"})
- session_view.add_operation(alert)
+ alert = InstallingPackageAlertNotification(
+ packages={"requests": "installing"}
+ )
+ session_view.add_notification(alert)
# Should not add any package logs
assert len(session_view.package_logs) == 0
@@ -1444,12 +1459,12 @@ def test_session_view_package_logs_partial_logs(
"""Test SessionView handles alerts with logs but no log_status."""
# Alert with logs but no log_status
- alert = InstallingPackageAlert(
+ alert = InstallingPackageAlertNotification(
packages={"matplotlib": "installing"},
logs={"matplotlib": "Some log content...\n"},
# log_status is None
)
- session_view.add_operation(alert)
+ session_view.add_notification(alert)
# Should not add any package logs since log_status is missing
assert len(session_view.package_logs) == 0
@@ -1460,12 +1475,12 @@ def test_session_view_package_logs_start_without_existing(
) -> None:
"""Test package logs start status on package that doesn't exist yet."""
- alert = InstallingPackageAlert(
+ alert = InstallingPackageAlertNotification(
packages={"new_package": "installing"},
logs={"new_package": "Starting fresh install...\n"},
log_status="start",
)
- session_view.add_operation(alert)
+ session_view.add_notification(alert)
assert (
session_view.package_logs["new_package"]
@@ -1479,12 +1494,12 @@ def test_session_view_package_logs_append_without_existing(
"""Test package logs append status on package that doesn't exist yet."""
# Append to non-existing package should start with empty string
- alert = InstallingPackageAlert(
+ alert = InstallingPackageAlertNotification(
packages={"orphan_package": "installing"},
logs={"orphan_package": "Appending to nothing...\n"},
log_status="append",
)
- session_view.add_operation(alert)
+ session_view.add_notification(alert)
assert (
session_view.package_logs["orphan_package"]
@@ -1497,12 +1512,12 @@ def test_session_view_package_logs_empty_content(
) -> None:
"""Test SessionView handles empty log content."""
- alert = InstallingPackageAlert(
+ alert = InstallingPackageAlertNotification(
packages={"empty_logs": "installing"},
logs={"empty_logs": ""},
log_status="start",
)
- session_view.add_operation(alert)
+ session_view.add_notification(alert)
assert "empty_logs" in session_view.package_logs
assert session_view.package_logs["empty_logs"] == ""
diff --git a/tests/_server/sessions/test_file_change_handler.py b/tests/_server/sessions/test_file_change_handler.py
index 92a7b6a591..ace40991e6 100644
--- a/tests/_server/sessions/test_file_change_handler.py
+++ b/tests/_server/sessions/test_file_change_handler.py
@@ -11,7 +11,11 @@ import pytest
from marimo._ast.cell import CellConfig
from marimo._config.manager import get_default_config_manager
-from marimo._messaging.ops import Reload, UpdateCellCodes, UpdateCellIdsRequest
+from marimo._messaging.notification import (
+ ReloadNotification,
+ UpdateCellCodesNotification,
+ UpdateCellIdsNotification,
+)
from marimo._runtime.requests import DeleteCellRequest, SyncGraphRequest
from marimo._server.models.models import SaveNotebookRequest
from marimo._server.notebook import AppFileManager
@@ -90,7 +94,7 @@ def test_edit_mode_reload_strategy_lazy(
update_ids_calls = [
call
for call in mock_session.notify.call_args_list
- if isinstance(call[0][0], UpdateCellIdsRequest)
+ if isinstance(call[0][0], UpdateCellIdsNotification)
]
assert len(update_ids_calls) == 1
@@ -98,7 +102,7 @@ def test_edit_mode_reload_strategy_lazy(
update_codes_calls = [
call
for call in mock_session.notify.call_args_list
- if isinstance(call[0][0], UpdateCellCodes)
+ if isinstance(call[0][0], UpdateCellCodesNotification)
]
assert len(update_codes_calls) == 1
assert update_codes_calls[0][0][0].code_is_stale is True
@@ -135,7 +139,7 @@ def test_edit_mode_reload_strategy_autorun(
update_ids_calls = [
call
for call in mock_session.notify.call_args_list
- if isinstance(call[0][0], UpdateCellIdsRequest)
+ if isinstance(call[0][0], UpdateCellIdsNotification)
]
assert len(update_ids_calls) == 1
@@ -195,7 +199,7 @@ def test_run_mode_reload_strategy(mock_session: MagicMock) -> None:
# Should send Reload operation
mock_session.notify.assert_called_once()
operation = mock_session.notify.call_args[0][0]
- assert isinstance(operation, Reload)
+ assert isinstance(operation, ReloadNotification)
async def test_file_change_coordinator_handles_change(
diff --git a/tests/_server/test_lsp.py b/tests/_server/test_lsp.py
index 00238c5ee1..66b00454ed 100644
--- a/tests/_server/test_lsp.py
+++ b/tests/_server/test_lsp.py
@@ -16,7 +16,7 @@ from marimo._config.manager import (
MarimoConfigReaderWithOverrides,
)
from marimo._loggers import get_log_directory
-from marimo._messaging.ops import Alert
+from marimo._messaging.notification import AlertNotification
from marimo._server.lsp import (
BasedpyrightServer,
BaseLspServer,
@@ -60,8 +60,10 @@ class MockLspServer(BaseLspServer):
def get_command(self) -> list[str]:
return ["mock_binary", "--port", str(self.port)]
- def missing_binary_alert(self) -> Alert:
- return Alert(title="Mock Alert", description="Mock missing binary")
+ def missing_binary_alert(self) -> AlertNotification:
+ return AlertNotification(
+ title="Mock Alert", description="Mock missing binary"
+ )
async def test_base_lsp_server_start_stop(
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index 4ae0863383..5b82983906 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -23,9 +23,9 @@ from marimo._ast.app_config import _AppConfig
from marimo._config.manager import (
get_default_config_manager,
)
-from marimo._messaging.ops import (
- MessageOperation,
- UpdateCellCodes,
+from marimo._messaging.notification import (
+ NotificationMessage,
+ UpdateCellCodesNotification,
)
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage
@@ -70,7 +70,7 @@ app_metadata = AppMetadata(
class MockSessionConsumer(SessionConsumer):
def __init__(self) -> None:
- self.notify_calls: list[MessageOperation] = []
+ self.notify_calls: list[NotificationMessage] = []
def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:
pass
@@ -549,7 +549,7 @@ def __():
update_ops = [
op
for op in session_consumer.notify_calls
- if isinstance(op, UpdateCellCodes)
+ if isinstance(op, UpdateCellCodesNotification)
]
assert len(update_ops) == 1
assert "2" == update_ops[0].codes[0]
@@ -588,12 +588,12 @@ def __():
update_ops = [
op
for op in session_consumer.notify_calls
- if isinstance(op, UpdateCellCodes)
+ if isinstance(op, UpdateCellCodesNotification)
]
update_ops2 = [
op
for op in session_consumer2.notify_calls
- if isinstance(op, UpdateCellCodes)
+ if isinstance(op, UpdateCellCodesNotification)
]
assert len(update_ops) == 1
assert len(update_ops2) == 1
@@ -625,7 +625,7 @@ def __():
update_ops2 = [
op
for op in session_consumer2.notify_calls
- if isinstance(op, UpdateCellCodes)
+ if isinstance(op, UpdateCellCodesNotification)
]
assert len(update_ops2) == 1
assert "4" == update_ops2[0].codes[0]
@@ -773,13 +773,13 @@ async def test_watch_mode_with_watcher_on_save_autorun(tmp_path: Path) -> None:
)
# Wait for the watcher to detect the change and send UpdateCellCodes
- update_ops: list[UpdateCellCodes] = []
+ update_ops: list[UpdateCellCodesNotification] = []
for _ in range(20): # noqa: B007
await asyncio.sleep(0.1)
update_ops = [
op
for op in session_consumer.notify_calls
- if isinstance(op, UpdateCellCodes)
+ if isinstance(op, UpdateCellCodesNotification)
]
if update_ops:
break
@@ -889,7 +889,7 @@ async def test_watch_mode_with_watcher_on_save_lazy(tmp_path: Path) -> None:
update_ops = [
op
for op in session_consumer.notify_calls
- if isinstance(op, UpdateCellCodes)
+ if isinstance(op, UpdateCellCodesNotification)
]
assert len(update_ops) == 1
assert "2" in update_ops[0].codes[0]
@@ -1004,7 +1004,9 @@ def __():
# Check that UpdateCellCodes was sent with the new code
update_ops = [
- op for op in operations if isinstance(op, UpdateCellCodes)
+ op
+ for op in operations
+ if isinstance(op, UpdateCellCodesNotification)
]
assert len(update_ops) == 1
assert "2" == update_ops[0].codes[0]
diff --git a/tests/_sql/test_connection_utils.py b/tests/_sql/test_connection_utils.py
index 225d3f17b7..833673815d 100644
--- a/tests/_sql/test_connection_utils.py
+++ b/tests/_sql/test_connection_utils.py
@@ -1,4 +1,5 @@
# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
import time
from typing import Callable
@@ -12,7 +13,7 @@ from marimo._data.models import (
DataTableColumn,
Schema,
)
-from marimo._messaging.ops import SQLMetadata
+from marimo._messaging.notification import SQLMetadata
from marimo._sql.connection_utils import (
update_table_in_connection,
update_table_list_in_connection,
diff --git a/tests/conftest.py b/tests/conftest.py
index b811a1bf51..10217f82c9 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -18,9 +18,9 @@ from marimo._ast.app_config import _AppConfig
from marimo._ast.cell_manager import CellManager
from marimo._config.config import DEFAULT_CONFIG
from marimo._messaging.mimetypes import ConsoleMimeType
-from marimo._messaging.ops import (
- CellOp,
- MessageOperation,
+from marimo._messaging.notification import (
+ CellNotification,
+ NotificationMessage,
)
from marimo._messaging.print_override import print_override
from marimo._messaging.serde import deserialize_kernel_message
@@ -79,14 +79,16 @@ class _MockStream(ThreadSafeStream):
deserialize_kernel_message(data)
@property
- def operations(self) -> list[MessageOperation]:
+ def operations(self) -> list[NotificationMessage]:
return [
deserialize_kernel_message(op_data) for op_data in self.messages
]
@property
- def cell_ops(self) -> list[CellOp]:
- return [op for op in self.operations if isinstance(op, CellOp)]
+ def cell_notifications(self) -> list[CellNotification]:
+ return [
+ op for op in self.operations if isinstance(op, CellNotification)
+ ]
class MockStdout(ThreadSafeStdout):