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: more session extensions (#7602)

Myles Scolnickeeec789d2275
diff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.py
index d139bff04c..c54ffedf39 100644
--- a/marimo/_runtime/commands.py
+++ b/marimo/_runtime/commands.py
@@ -742,6 +742,7 @@ CommandMessage = Union[
# Notebook operations
CreateNotebookCommand,
RenameNotebookCommand,
+ CodeCompletionCommand,
# Cell execution and management
ExecuteCellsCommand,
ExecuteScratchpadCommand,
diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.py
index 64dc478db5..787e144c4f 100644
--- a/marimo/_server/api/endpoints/editing.py
+++ b/marimo/_server/api/endpoints/editing.py
@@ -48,11 +48,7 @@ async def code_complete(request: Request) -> BaseResponse:
schema:
$ref: "#/components/schemas/SuccessResponse"
"""
- app_state = AppState(request)
- body = await parse_request(request, cls=CodeCompletionRequest)
- app_state.require_current_session().put_completion_request(body)
-
- return SuccessResponse()
+ return await dispatch_control_request(request, cls=CodeCompletionRequest)
@router.post("/delete")
diff --git a/marimo/_server/sessions/events.py b/marimo/_server/sessions/events.py
index 901a1763a3..b65a3e697c 100644
--- a/marimo/_server/sessions/events.py
+++ b/marimo/_server/sessions/events.py
@@ -6,13 +6,14 @@ Provides an event bus and listeners for session creation, closure, and resumptio
from __future__ import annotations
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Optional
from marimo import _loggers
from marimo._messaging.types import KernelMessage
-from marimo._types.ids import SessionId
+from marimo._types.ids import ConsumerId, SessionId
if TYPE_CHECKING:
+ from marimo._runtime import commands
from marimo._server.sessions.session import Session
LOGGER = _loggers.marimo_logger()
@@ -58,6 +59,24 @@ class SessionEventListener:
del notification
return None
+ def on_received_command(
+ self,
+ session: Session,
+ request: commands.CommandMessage,
+ from_consumer_id: Optional[ConsumerId],
+ ) -> None:
+ """Called when a command is received."""
+ del session
+ del request
+ del from_consumer_id
+ return None
+
+ def on_received_stdin(self, session: Session, stdin: str) -> None:
+ """Called when stdin is received."""
+ del session
+ del stdin
+ return None
+
class SessionEventBus:
"""Event bus for coordinating session lifecycle events.
@@ -147,3 +166,36 @@ class SessionEventBus:
e,
)
continue
+
+ def emit_received_command(
+ self,
+ session: Session,
+ request: commands.CommandMessage,
+ from_consumer_id: Optional[ConsumerId],
+ ) -> None:
+ """Emit a received command event."""
+ for listener in self._listeners:
+ try:
+ listener.on_received_command(
+ session, request, from_consumer_id
+ )
+ except Exception as e:
+ LOGGER.error(
+ "Error handling received command event for listener %s: %s",
+ listener,
+ e,
+ )
+ continue
+
+ def emit_received_stdin(self, session: Session, stdin: str) -> None:
+ """Emit a received stdin event."""
+ for listener in self._listeners:
+ try:
+ listener.on_received_stdin(session, stdin)
+ except Exception as e:
+ LOGGER.error(
+ "Error handling received stdin event for listener %s: %s",
+ listener,
+ e,
+ )
+ continue
diff --git a/marimo/_server/sessions/extensions/extensions.py b/marimo/_server/sessions/extensions/extensions.py
index 94cd203fe8..cc84576dcc 100644
--- a/marimo/_server/sessions/extensions/extensions.py
+++ b/marimo/_server/sessions/extensions/extensions.py
@@ -8,11 +8,12 @@ Extensions provide a way to add cross-cutting concerns to sessions
from __future__ import annotations
import asyncio
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Optional, Union
from marimo import _loggers
from marimo._cli.print import red
from marimo._messaging.types import KernelMessage
+from marimo._runtime import commands
from marimo._server.session.serialize import (
SessionCacheKey,
SessionCacheManager,
@@ -38,7 +39,7 @@ if TYPE_CHECKING:
SessionEventBus,
)
from marimo._server.sessions.types import Session
- from marimo._types.ids import SessionId
+ from marimo._types.ids import ConsumerId, SessionId
LOGGER = _loggers.marimo_logger()
@@ -263,3 +264,152 @@ class LoggingExtension(SessionExtension, SessionEventListener):
session.initialization_id,
old_path,
)
+
+
+class SessionViewExtension(SessionExtension, SessionEventListener):
+ """Extension for listening to session view updates."""
+
+ def __init__(self) -> None:
+ self.event_bus: Optional[SessionEventBus] = None
+
+ def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:
+ """Attach the session view extension to a session."""
+ del session
+ self.event_bus = event_bus
+ self.event_bus.subscribe(self)
+
+ def on_detach(self) -> None:
+ """Detach the session view extension from a session."""
+ if self.event_bus:
+ self.event_bus.unsubscribe(self)
+ self.event_bus = None
+
+ def on_received_command(
+ self,
+ session: Session,
+ request: Union[
+ commands.CommandMessage, commands.CodeCompletionCommand
+ ],
+ from_consumer_id: Optional[ConsumerId],
+ ) -> None:
+ """Called when a command is received."""
+ del from_consumer_id
+ # Only add control requests to session view, not completion requests
+ if not isinstance(request, commands.CodeCompletionCommand):
+ session.session_view.add_control_request(request)
+
+ def on_received_stdin(self, session: Session, stdin: str) -> None:
+ """Called when stdin is received."""
+ session.session_view.add_stdin(stdin)
+
+ def on_notification_sent(
+ self, session: Session, notification: KernelMessage
+ ) -> None:
+ """Called when a notification is sent."""
+ session.session_view.add_raw_notification(notification)
+
+
+class QueueExtension(SessionExtension, SessionEventListener):
+ """Extension for handling queue operations."""
+
+ def __init__(self, queue_manager: QueueManager) -> None:
+ self.queue_manager = queue_manager
+ self.event_bus: Optional[SessionEventBus] = None
+
+ def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:
+ """Attach the queue extension to a session."""
+ del session
+ self.event_bus = event_bus
+ self.event_bus.subscribe(self)
+
+ def on_detach(self) -> None:
+ """Detach the queue extension from a session."""
+ if self.event_bus:
+ self.event_bus.unsubscribe(self)
+ self.event_bus = None
+
+ def on_received_command(
+ self,
+ session: Session,
+ request: Union[
+ commands.CommandMessage, commands.CodeCompletionCommand
+ ],
+ from_consumer_id: Optional[ConsumerId],
+ ) -> None:
+ """Called when a command is received."""
+ del session
+ del from_consumer_id
+ self.queue_manager.put_control_request(request)
+
+ def on_received_stdin(self, session: Session, stdin: str) -> None:
+ """Called when stdin is received."""
+ del session
+ self.queue_manager.put_input(stdin)
+
+
+class ReplayExtension(SessionExtension, SessionEventListener):
+ """Extension for replaying commands from one session to another."""
+
+ def __init__(self) -> None:
+ self.event_bus: Optional[SessionEventBus] = None
+
+ def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:
+ """Attach the replay extension to a session."""
+ del session
+ self.event_bus = event_bus
+ self.event_bus.subscribe(self)
+
+ def on_detach(self) -> None:
+ """Detach the replay extension from a session."""
+ if self.event_bus:
+ self.event_bus.unsubscribe(self)
+ self.event_bus = None
+
+ def on_received_command(
+ self,
+ session: Session,
+ request: Union[
+ commands.CommandMessage, commands.CodeCompletionCommand
+ ],
+ from_consumer_id: Optional[ConsumerId],
+ ) -> None:
+ """Called when a command is received."""
+ from marimo._messaging.notification import (
+ FocusCellNotification,
+ UpdateCellCodesNotification,
+ )
+ from marimo._runtime.commands import (
+ ExecuteCellsCommand,
+ SyncGraphCommand,
+ )
+
+ # Only propagate execute cells and sync graph commands to the room
+ if not isinstance(request, (ExecuteCellsCommand, SyncGraphCommand)):
+ return
+
+ # Collect cell ids and codes
+ if isinstance(request, ExecuteCellsCommand):
+ cell_ids = request.cell_ids
+ codes = request.codes
+ else:
+ cell_ids = request.run_ids
+ codes = [request.cells[cell_id] for cell_id in cell_ids]
+
+ # Send update cell codes notification
+ if cell_ids:
+ session.notify(
+ UpdateCellCodesNotification(
+ cell_ids=cell_ids,
+ codes=codes,
+ # Not stale because we just ran the code
+ code_is_stale=False,
+ ),
+ from_consumer_id=from_consumer_id,
+ )
+
+ # Send focus cell notification
+ if len(cell_ids) == 1:
+ session.notify(
+ FocusCellNotification(cell_id=cell_ids[0]),
+ from_consumer_id=from_consumer_id,
+ )
diff --git a/marimo/_server/sessions/managers.py b/marimo/_server/sessions/managers.py
index b40bd799ba..df10528e0e 100644
--- a/marimo/_server/sessions/managers.py
+++ b/marimo/_server/sessions/managers.py
@@ -117,16 +117,16 @@ class QueueManagerImpl(QueueManager):
def put_control_request(self, request: commands.CommandMessage) -> None:
"""Put a control request in the control queue."""
+ # Completions are on their own queue
+ if isinstance(request, commands.CodeCompletionCommand):
+ self.completion_queue.put(request)
+ return
+
self.control_queue.put(request)
+ # Update UI elements are on both queues so they can be batched
if isinstance(request, commands.UpdateUIElementCommand):
self.set_ui_element_queue.put(request)
- def put_completion_request(
- self, request: commands.CodeCompletionCommand
- ) -> None:
- """Put a code completion request in the completion queue."""
- self.completion_queue.put(request)
-
def put_input(self, text: str) -> None:
"""Put an input request in the input queue."""
self.input_queue.put(text)
diff --git a/marimo/_server/sessions/session.py b/marimo/_server/sessions/session.py
index a3d6ba53a6..06925bedf9 100644
--- a/marimo/_server/sessions/session.py
+++ b/marimo/_server/sessions/session.py
@@ -13,9 +13,7 @@ from uuid import uuid4
from marimo import _loggers
from marimo._config.manager import MarimoConfigManager, ScriptConfigManager
from marimo._messaging.notification import (
- FocusCellNotification,
NotificationMessage,
- UpdateCellCodesNotification,
)
from marimo._messaging.serde import serialize_kernel_message
from marimo._messaging.types import KernelMessage
@@ -24,9 +22,7 @@ from marimo._runtime.commands import (
AppMetadata,
CreateNotebookCommand,
ExecuteCellCommand,
- ExecuteCellsCommand,
HTTPRequest,
- SyncGraphCommand,
UpdateUIElementCommand,
)
from marimo._server.consumer import SessionConsumer
@@ -40,6 +36,9 @@ from marimo._server.sessions.extensions.extensions import (
HeartbeatExtension,
LoggingExtension,
NotificationListenerExtension,
+ QueueExtension,
+ ReplayExtension,
+ SessionViewExtension,
)
from marimo._server.sessions.extensions.types import SessionExtension
from marimo._server.sessions.managers import (
@@ -50,7 +49,6 @@ from marimo._server.sessions.room import Room
from marimo._server.sessions.types import (
KernelManager,
KernelState,
- QueueManager,
Session,
)
from marimo._types.ids import ConsumerId
@@ -121,16 +119,14 @@ class SessionImpl(Session):
NotificationListenerExtension(
kernel_manager=kernel_manager, queue_manager=queue_manager
),
- # TODO: Refactor more into extensions
- # KernelExtension()
- # RoomBroadcastExtension()
- # SessionView()
+ QueueExtension(queue_manager=queue_manager),
+ ReplayExtension(),
+ SessionViewExtension(),
]
return cls(
initialization_id=initialization_id,
session_consumer=session_consumer,
- queue_manager=queue_manager,
kernel_manager=kernel_manager,
app_file_manager=app_file_manager,
config_manager=config_manager,
@@ -142,7 +138,6 @@ class SessionImpl(Session):
self,
initialization_id: str,
session_consumer: SessionConsumer,
- queue_manager: QueueManager,
kernel_manager: KernelManager,
app_file_manager: AppFileManager,
config_manager: MarimoConfigManager,
@@ -156,8 +151,7 @@ class SessionImpl(Session):
self.initialization_id = initialization_id
self.app_file_manager = app_file_manager
self.room = Room()
- self._queue_manager = queue_manager
- self.kernel_manager = kernel_manager
+ self._kernel_manager = kernel_manager
self.ttl_seconds = (
ttl_seconds if ttl_seconds is not None else _DEFAULT_TTL_SECONDS
)
@@ -165,7 +159,7 @@ class SessionImpl(Session):
self.config_manager = config_manager
self.extensions = extensions
- self.kernel_manager.start_kernel()
+ self._kernel_manager.start_kernel()
self._event_bus = SessionEventBus()
self._closed = False
@@ -224,19 +218,19 @@ class SessionImpl(Session):
def try_interrupt(self) -> None:
"""Try to interrupt the kernel."""
- self.kernel_manager.interrupt_kernel()
+ self._kernel_manager.interrupt_kernel()
def kernel_state(self) -> KernelState:
"""Get the state of the kernel."""
- if self.kernel_manager.kernel_task is None:
+ if self._kernel_manager.kernel_task is None:
return KernelState.NOT_STARTED
- if self.kernel_manager.kernel_task.is_alive():
+ if self._kernel_manager.kernel_task.is_alive():
return KernelState.RUNNING
return KernelState.STOPPED
def kernel_pid(self) -> int | None:
"""Get the PID of the kernel."""
- return self.kernel_manager.pid
+ return self._kernel_manager.pid
def put_control_request(
self,
@@ -244,44 +238,11 @@ class SessionImpl(Session):
from_consumer_id: Optional[ConsumerId],
) -> None:
"""Put a control request in the control queue."""
- self._queue_manager.put_control_request(request)
-
- # Propagate the control request to the room
- if isinstance(request, (ExecuteCellsCommand, SyncGraphCommand)):
- if isinstance(request, ExecuteCellsCommand):
- cell_ids = request.cell_ids
- codes = request.codes
- else:
- cell_ids = request.run_ids
- codes = [request.cells[cell_id] for cell_id in cell_ids]
- if cell_ids:
- self.notify(
- UpdateCellCodesNotification(
- cell_ids=cell_ids,
- codes=codes,
- # Not stale because we just ran the code
- code_is_stale=False,
- ),
- from_consumer_id=from_consumer_id,
- )
- if len(cell_ids) == 1:
- self.notify(
- FocusCellNotification(cell_id=cell_ids[0]),
- from_consumer_id=from_consumer_id,
- )
-
- self.session_view.add_control_request(request)
-
- def put_completion_request(
- self, request: commands.CodeCompletionCommand
- ) -> None:
- """Put a code completion request in the completion queue."""
- self._queue_manager.completion_queue.put(request)
+ self._event_bus.emit_received_command(self, request, from_consumer_id)
def put_input(self, text: str) -> None:
"""Put an input() request in the input queue."""
- self._queue_manager.put_input(text)
- self.session_view.add_stdin(text)
+ self._event_bus.emit_received_stdin(self, text)
def disconnect_consumer(self, session_consumer: SessionConsumer) -> None:
"""
@@ -341,7 +302,6 @@ class SessionImpl(Session):
else:
notification = serialize_kernel_message(operation)
self.room.broadcast(notification, except_consumer=from_consumer_id)
- self.session_view.add_raw_notification(notification)
self._event_bus.emit_notification_sent(self, notification)
def close(self) -> None:
@@ -359,7 +319,7 @@ class SessionImpl(Session):
self._detach_extensions()
# Close the room
self.room.close()
- self.kernel_manager.close_kernel()
+ self._kernel_manager.close_kernel()
def instantiate(
self,
diff --git a/marimo/_server/sessions/types.py b/marimo/_server/sessions/types.py
index f8c7e48444..50843e3b41 100644
--- a/marimo/_server/sessions/types.py
+++ b/marimo/_server/sessions/types.py
@@ -49,12 +49,6 @@ class QueueManager(Protocol):
"""Put a control request in the control queue."""
...
- def put_completion_request(
- self, request: commands.CodeCompletionCommand
- ) -> None:
- """Put a code completion request in the completion queue."""
- ...
-
def put_input(self, text: str) -> None:
"""Put an input() request in the input queue."""
...
@@ -148,12 +142,6 @@ class Session(Protocol):
"""Put a control request in the control queue."""
...
- def put_completion_request(
- self, request: commands.CodeCompletionCommand
- ) -> None:
- """Put a code completion request in the completion queue."""
- ...
-
def put_input(self, text: str) -> None:
"""Put an input() request in the input queue."""
...
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index df078a81d8..bca3b6c10b 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -2200,6 +2200,7 @@ components:
anyOf:
- $ref: '#/components/schemas/CreateNotebookCommand'
- $ref: '#/components/schemas/RenameNotebookCommand'
+ - $ref: '#/components/schemas/CodeCompletionCommand'
- $ref: '#/components/schemas/ExecuteCellsCommand'
- $ref: '#/components/schemas/ExecuteScratchpadCommand'
- $ref: '#/components/schemas/ExecuteStaleCellsCommand'
@@ -2225,6 +2226,7 @@ components:
discriminator:
mapping:
clear-cache: '#/components/schemas/ClearCacheCommand'
+ code-completion: '#/components/schemas/CodeCompletionCommand'
create-notebook: '#/components/schemas/CreateNotebookCommand'
debug-cell: '#/components/schemas/DebugCellCommand'
delete-cell: '#/components/schemas/DeleteCellCommand'
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 6be9945861..a9e32ab128 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -4054,6 +4054,7 @@ export interface components {
command:
| components["schemas"]["CreateNotebookCommand"]
| components["schemas"]["RenameNotebookCommand"]
+ | components["schemas"]["CodeCompletionCommand"]
| components["schemas"]["ExecuteCellsCommand"]
| components["schemas"]["ExecuteScratchpadCommand"]
| components["schemas"]["ExecuteStaleCellsCommand"]
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 9d8b562dc9..78ae3922f7 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -248,7 +248,7 @@ async def test_query_params(client: TestClient) -> None:
session = get_session_manager(client).get_session("123")
assert session
- assert session.kernel_manager.app_metadata.query_params == {
+ assert session._kernel_manager.app_metadata.query_params == {
"foo": "1",
"bar": ["2", "3"],
"baz": "4",
diff --git a/tests/_server/sessions/extensions/test_extensions.py b/tests/_server/sessions/extensions/test_extensions.py
index 15b219f8e6..0e528b5891 100644
--- a/tests/_server/sessions/extensions/test_extensions.py
+++ b/tests/_server/sessions/extensions/test_extensions.py
@@ -15,9 +15,12 @@ from marimo._server.sessions.extensions.extensions import (
HeartbeatExtension,
LoggingExtension,
NotificationListenerExtension,
+ QueueExtension,
+ ReplayExtension,
+ SessionViewExtension,
)
from marimo._server.sessions.types import KernelState
-from marimo._types.ids import SessionId
+from marimo._types.ids import CellId_t, RequestId, SessionId
@pytest.fixture
@@ -251,3 +254,207 @@ class TestLoggingExtension:
)
extension.on_detach()
+
+
+class TestSessionViewExtension:
+ """Tests for SessionViewExtension."""
+
+ def test_lifecycle(self, mock_session, event_bus) -> None:
+ """Test event subscription on attach/detach."""
+ extension = SessionViewExtension()
+
+ extension.on_attach(mock_session, event_bus)
+
+ assert extension in event_bus._listeners
+ assert extension.event_bus is not None
+
+ extension.on_detach()
+
+ assert extension not in event_bus._listeners
+ assert extension.event_bus is None
+
+ def test_command_added_to_view(self, mock_session, event_bus) -> None:
+ """Test that commands are added to session view."""
+ from marimo._runtime.commands import ExecuteCellsCommand
+
+ extension = SessionViewExtension()
+ extension.on_attach(mock_session, event_bus)
+
+ cmd = ExecuteCellsCommand(
+ cell_ids=[CellId_t("cell1")], codes=["x = 1"]
+ )
+ extension.on_received_command(mock_session, cmd, None)
+
+ mock_session.session_view.add_control_request.assert_called_once_with(
+ cmd
+ )
+ extension.on_detach()
+
+ def test_completion_not_added_to_view(
+ self, mock_session, event_bus
+ ) -> None:
+ """Test that code completion commands are not added to view."""
+ from marimo._runtime.commands import CodeCompletionCommand
+
+ extension = SessionViewExtension()
+ extension.on_attach(mock_session, event_bus)
+
+ cmd = CodeCompletionCommand(
+ id=RequestId("1"), document="", cell_id=CellId_t("cell1")
+ )
+ extension.on_received_command(mock_session, cmd, None)
+
+ mock_session.session_view.add_control_request.assert_not_called()
+ extension.on_detach()
+
+ def test_stdin_added_to_view(self, mock_session, event_bus) -> None:
+ """Test that stdin is added to session view."""
+ extension = SessionViewExtension()
+ extension.on_attach(mock_session, event_bus)
+
+ extension.on_received_stdin(mock_session, "test input")
+
+ mock_session.session_view.add_stdin.assert_called_once_with(
+ "test input"
+ )
+ extension.on_detach()
+
+ def test_notification_added_to_view(self, mock_session, event_bus) -> None:
+ """Test that notifications are added to session view."""
+ extension = SessionViewExtension()
+ extension.on_attach(mock_session, event_bus)
+
+ notification = Mock()
+ extension.on_notification_sent(mock_session, notification)
+
+ mock_session.session_view.add_raw_notification.assert_called_once_with(
+ notification
+ )
+ extension.on_detach()
+
+
+class TestQueueExtension:
+ """Tests for QueueExtension."""
+
+ @pytest.fixture
+ def queue_manager(self):
+ manager = Mock()
+ manager.put_control_request = Mock()
+ manager.put_input = Mock()
+ return manager
+
+ def test_lifecycle(self, mock_session, event_bus, queue_manager) -> None:
+ """Test event subscription on attach/detach."""
+ extension = QueueExtension(queue_manager)
+
+ extension.on_attach(mock_session, event_bus)
+
+ assert extension in event_bus._listeners
+ assert extension.event_bus is not None
+
+ extension.on_detach()
+
+ assert extension not in event_bus._listeners
+ assert extension.event_bus is None
+
+ def test_command_added_to_queue(
+ self, mock_session, event_bus, queue_manager
+ ) -> None:
+ """Test that commands are added to queue."""
+ from marimo._runtime.commands import ExecuteCellsCommand
+
+ extension = QueueExtension(queue_manager)
+ extension.on_attach(mock_session, event_bus)
+
+ cmd = ExecuteCellsCommand(
+ cell_ids=[CellId_t("cell1")], codes=["x = 1"]
+ )
+ extension.on_received_command(mock_session, cmd, None)
+
+ queue_manager.put_control_request.assert_called_once_with(cmd)
+ extension.on_detach()
+
+ def test_stdin_added_to_queue(
+ self, mock_session, event_bus, queue_manager
+ ) -> None:
+ """Test that stdin is added to queue."""
+ extension = QueueExtension(queue_manager)
+ extension.on_attach(mock_session, event_bus)
+
+ extension.on_received_stdin(mock_session, "test input")
+
+ queue_manager.put_input.assert_called_once_with("test input")
+ extension.on_detach()
+
+
+class TestReplayExtension:
+ """Tests for ReplayExtension."""
+
+ def test_lifecycle(self, mock_session, event_bus) -> None:
+ """Test event subscription on attach/detach."""
+ extension = ReplayExtension()
+
+ extension.on_attach(mock_session, event_bus)
+
+ assert extension in event_bus._listeners
+ assert extension.event_bus is not None
+
+ extension.on_detach()
+
+ assert extension not in event_bus._listeners
+ assert extension.event_bus is None
+
+ def test_execute_command_replayed(self, mock_session, event_bus) -> None:
+ """Test that ExecuteCellsCommand is replayed with notifications."""
+ from marimo._runtime.commands import ExecuteCellsCommand
+
+ mock_session.notify = Mock()
+ extension = ReplayExtension()
+ extension.on_attach(mock_session, event_bus)
+
+ cmd = ExecuteCellsCommand(
+ cell_ids=[CellId_t("cell1")], codes=["x = 1"]
+ )
+ extension.on_received_command(mock_session, cmd, None)
+
+ assert mock_session.notify.call_count == 2
+ extension.on_detach()
+
+ def test_sync_graph_command_replayed(
+ self, mock_session, event_bus
+ ) -> None:
+ """Test that SyncGraphCommand is replayed with notifications."""
+ from marimo._runtime.commands import SyncGraphCommand
+
+ mock_session.notify = Mock()
+ extension = ReplayExtension()
+ extension.on_attach(mock_session, event_bus)
+
+ cell_id = CellId_t("cell1")
+ cmd = SyncGraphCommand(
+ cells={cell_id: "x = 1"},
+ run_ids=[cell_id],
+ delete_ids=[],
+ )
+ extension.on_received_command(mock_session, cmd, None)
+
+ assert mock_session.notify.call_count == 2
+ extension.on_detach()
+
+ def test_other_commands_not_replayed(
+ self, mock_session, event_bus
+ ) -> None:
+ """Test that other commands are not replayed."""
+ from marimo._runtime.commands import CodeCompletionCommand
+
+ mock_session.notify = Mock()
+ extension = ReplayExtension()
+ extension.on_attach(mock_session, event_bus)
+
+ cmd = CodeCompletionCommand(
+ id=RequestId("1"), document="", cell_id=CellId_t("cell1")
+ )
+ extension.on_received_command(mock_session, cmd, None)
+
+ mock_session.notify.assert_not_called()
+ extension.on_detach()
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index 25ebf34ac9..f26c599b39 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -316,20 +316,18 @@ async def test_session() -> None:
# Instantiate a Session
session = SessionImpl(
- session_id,
- session_consumer,
- queue_manager,
- kernel_manager,
- AppFileManager.from_app(InternalApp(App())),
- get_default_config_manager(current_path=None),
+ initialization_id=session_id,
+ session_consumer=session_consumer,
+ kernel_manager=kernel_manager,
+ app_file_manager=AppFileManager.from_app(InternalApp(App())),
+ config_manager=get_default_config_manager(current_path=None),
ttl_seconds=None,
extensions=[],
)
# Assert startup
assert session.room.main_consumer == session_consumer
- assert session._queue_manager == queue_manager
- assert session.kernel_manager == kernel_manager
+ assert session._kernel_manager == kernel_manager
session_consumer.on_attach.assert_called_once()
assert session_consumer.on_detach.call_count == 0
assert session.connection_state() == ConnectionState.OPEN
@@ -366,7 +364,6 @@ def test_session_disconnect_reconnect() -> None:
session = SessionImpl(
initialization_id=session_id,
session_consumer=session_consumer,
- queue_manager=queue_manager,
kernel_manager=kernel_manager,
app_file_manager=AppFileManager.from_app(InternalApp(App())),
config_manager=get_default_config_manager(current_path=None),
@@ -425,7 +422,6 @@ def test_session_with_kiosk_consumers() -> None:
session = SessionImpl(
initialization_id=session_id,
session_consumer=session_consumer,
- queue_manager=queue_manager,
kernel_manager=kernel_manager,
app_file_manager=AppFileManager.from_app(InternalApp(App())),
config_manager=get_default_config_manager(current_path=None),
@@ -435,8 +431,7 @@ def test_session_with_kiosk_consumers() -> None:
# Assert startup
assert session.room.main_consumer == session_consumer
- assert session._queue_manager == queue_manager
- assert session.kernel_manager == kernel_manager
+ assert session._kernel_manager == kernel_manager
session_consumer.on_attach.assert_called_once()
assert session_consumer.on_detach.call_count == 0
assert session.connection_state() == ConnectionState.OPEN
@@ -746,7 +741,8 @@ async def test_watch_mode_with_watcher_on_save_autorun(tmp_path: Path) -> None:
file_key=str(tmp_file),
auto_instantiate=False,
)
- session.session_view = MagicMock(SessionView)
+ mock_session_view = MagicMock(spec=SessionView)
+ session.session_view = mock_session_view
# Wait for file watcher to be initialized by checking it exists
for _ in range(20): # noqa: B007
@@ -1062,7 +1058,7 @@ def test_session_with_script_config_overrides(
session.config_manager.get_config()["formatting"]["line_length"] == 999
)
assert (
- session.kernel_manager.config_manager.get_config()["formatting"][
+ session._kernel_manager.config_manager.get_config()["formatting"][
"line_length"
]
== 999