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 session extensions to use EventAwareExtension base class (#8678)

Myles Scolnick8f0ebe03617b
diff --git a/marimo/_internal/session/extensions.py b/marimo/_internal/session/extensions.py
index a40f3b96f9..5086aa6146 100644
--- a/marimo/_internal/session/extensions.py
+++ b/marimo/_internal/session/extensions.py
@@ -10,10 +10,16 @@ from marimo._session.extensions.extensions import (
ReplayExtension,
SessionViewExtension,
)
-from marimo._session.extensions.types import SessionExtension
+from marimo._session.extensions.types import (
+ EventAwareExtension,
+ ExtensionRegistry,
+ SessionExtension,
+)
__all__ = [
"CachingExtension",
+ "EventAwareExtension",
+ "ExtensionRegistry",
"HeartbeatExtension",
"LoggingExtension",
"NotificationListenerExtension",
diff --git a/marimo/_server/scratchpad.py b/marimo/_server/scratchpad.py
index e0c6758895..098b5e2287 100644
--- a/marimo/_server/scratchpad.py
+++ b/marimo/_server/scratchpad.py
@@ -18,7 +18,7 @@ from marimo._messaging.cell_output import CellChannel
from marimo._messaging.notification import CellNotification
from marimo._messaging.serde import deserialize_kernel_message
from marimo._runtime.scratch import SCRATCH_CELL_ID
-from marimo._session.events import SessionEventBus, SessionEventListener
+from marimo._session.extensions.types import EventAwareExtension
if TYPE_CHECKING:
from collections.abc import AsyncGenerator
@@ -73,7 +73,7 @@ def _format_sse(event: str, data: Any) -> str:
# -- Listeners ----------------------------------------------------------------
-class ScratchCellListener(SessionEventListener):
+class ScratchCellListener(EventAwareExtension):
"""Listens for scratch cell notifications via an asyncio.Queue.
Supports both SSE streaming (via ``stream()``) and simple blocking
@@ -82,19 +82,10 @@ class ScratchCellListener(SessionEventListener):
"""
def __init__(self) -> None:
+ super().__init__()
self._queue: asyncio.Queue[CellNotification | None] = asyncio.Queue()
self.timed_out = False
- def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:
- del session
- self._event_bus = event_bus
- event_bus.subscribe(self)
-
- def on_detach(self) -> None:
- if hasattr(self, "_event_bus"):
- self._event_bus.unsubscribe(self)
- del self._event_bus
-
def on_notification_sent(
self, session: Session, notification: KernelMessage
) -> None:
diff --git a/marimo/_server/session/listeners.py b/marimo/_server/session/listeners.py
index 5239cffad2..7846ce0903 100644
--- a/marimo/_server/session/listeners.py
+++ b/marimo/_server/session/listeners.py
@@ -8,16 +8,12 @@ tracking recent files, managing caches, etc.
from __future__ import annotations
from marimo._server.recents import RecentFilesManager
-from marimo._session.events import (
- SessionEventBus,
- SessionEventListener,
-)
-from marimo._session.extensions.types import SessionExtension
+from marimo._session.extensions.types import EventAwareExtension
from marimo._session.session import Session
from marimo._types.ids import SessionId
-class RecentsTrackerListener(SessionExtension, SessionEventListener):
+class RecentsTrackerListener(EventAwareExtension):
"""Event listener that tracks recently accessed files."""
def __init__(self, recents_manager: RecentFilesManager) -> None:
@@ -26,20 +22,8 @@ class RecentsTrackerListener(SessionExtension, SessionEventListener):
Args:
recents_manager: Manager for recent files
"""
+ super().__init__()
self._recents = recents_manager
- self._event_bus: SessionEventBus | None = None
-
- def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:
- """Attach the recents tracker listener to a session."""
- del session
- self._event_bus = event_bus
- self._event_bus.subscribe(self)
-
- def on_detach(self) -> None:
- """Detach the recents tracker listener from a session."""
- if self._event_bus:
- self._event_bus.unsubscribe(self)
- self._event_bus = None
async def on_session_created(self, session: Session) -> None:
"""Update recent files when a session is created."""
diff --git a/marimo/_session/events.py b/marimo/_session/events.py
index 51f10961ba..881354de4b 100644
--- a/marimo/_session/events.py
+++ b/marimo/_session/events.py
@@ -13,6 +13,8 @@ from marimo._messaging.types import KernelMessage
from marimo._types.ids import ConsumerId, SessionId
if TYPE_CHECKING:
+ from collections.abc import Awaitable, Callable
+
from marimo._runtime import commands
from marimo._session.session import Session
@@ -96,76 +98,84 @@ class SessionEventBus:
if listener in self._listeners:
self._listeners.remove(listener)
- async def emit_session_created(self, session: Session) -> None:
- """Emit a session created event."""
- for listener in self._listeners:
+ def _emit(
+ self,
+ event_name: str,
+ call: Callable[[SessionEventListener], None],
+ ) -> None:
+ """Dispatch a synchronous event to all listeners."""
+ for listener in list(self._listeners):
try:
- await listener.on_session_created(session)
+ call(listener)
except Exception as e:
LOGGER.error(
- "Error handling session created event for listener %s: %s",
+ "Error handling %s for listener %s: %s",
+ event_name,
listener,
e,
)
- continue
- async def emit_session_closed(self, session: Session) -> None:
- """Emit a session closed event."""
- for listener in self._listeners:
+ async def _emit_async(
+ self,
+ event_name: str,
+ call: Callable[[SessionEventListener], Awaitable[None]],
+ ) -> None:
+ """Dispatch an async event to all listeners."""
+ for listener in list(self._listeners):
try:
- await listener.on_session_closed(session)
+ await call(listener)
except Exception as e:
LOGGER.error(
- "Error handling session closed event for listener %s: %s",
+ "Error handling %s for listener %s: %s",
+ event_name,
listener,
e,
)
- continue
+
+ async def emit_session_created(self, session: Session) -> None:
+ """Emit a session created event."""
+ await self._emit_async(
+ "session_created",
+ lambda listener: listener.on_session_created(session),
+ )
+
+ async def emit_session_closed(self, session: Session) -> None:
+ """Emit a session closed event."""
+ await self._emit_async(
+ "session_closed",
+ lambda listener: listener.on_session_closed(session),
+ )
async def emit_session_resumed(
self, session: Session, old_id: SessionId
) -> None:
"""Emit a session resumed event."""
- for listener in self._listeners:
- try:
- await listener.on_session_resumed(session, old_id)
- except Exception as e:
- LOGGER.error(
- "Error handling session resumed event for listener %s: %s",
- listener,
- e,
- )
- continue
+ await self._emit_async(
+ "session_resumed",
+ lambda listener: listener.on_session_resumed(session, old_id),
+ )
async def emit_session_notebook_renamed(
self, session: Session, old_path: str | None
) -> None:
"""Emit a session renamed event."""
- for listener in self._listeners:
- try:
- await listener.on_session_notebook_renamed(session, old_path)
- except Exception as e:
- LOGGER.error(
- "Error handling session notebook renamed event for listener %s: %s",
- listener,
- e,
- )
- continue
+ await self._emit_async(
+ "session_notebook_renamed",
+ lambda listener: listener.on_session_notebook_renamed(
+ session, old_path
+ ),
+ )
def emit_notification_sent(
self, session: Session, notification: KernelMessage
) -> None:
"""Emit a notification sent event."""
- for listener in self._listeners:
- try:
- listener.on_notification_sent(session, notification)
- except Exception as e:
- LOGGER.error(
- "Error handling notification sent event for listener %s: %s",
- listener,
- e,
- )
- continue
+ self._emit(
+ "notification_sent",
+ lambda listener: listener.on_notification_sent(
+ session, notification
+ ),
+ )
def emit_received_command(
self,
@@ -174,28 +184,16 @@ class SessionEventBus:
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
+ self._emit(
+ "received_command",
+ lambda listener: listener.on_received_command(
+ session, request, from_consumer_id
+ ),
+ )
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
+ self._emit(
+ "received_stdin",
+ lambda listener: listener.on_received_stdin(session, stdin),
+ )
diff --git a/marimo/_session/extensions/extensions.py b/marimo/_session/extensions/extensions.py
index fdb5e1583e..f7994efdc8 100644
--- a/marimo/_session/extensions/extensions.py
+++ b/marimo/_session/extensions/extensions.py
@@ -22,8 +22,10 @@ from marimo._messaging.notification import (
from marimo._messaging.serde import try_deserialize_kernel_notification_name
from marimo._messaging.types import KernelMessage
from marimo._runtime import commands
-from marimo._session.events import SessionEventListener
-from marimo._session.extensions.types import SessionExtension
+from marimo._session.extensions.types import (
+ EventAwareExtension,
+ SessionExtension,
+)
from marimo._session.state.serialize import (
SessionCacheKey,
SessionCacheManager,
@@ -110,7 +112,7 @@ class HeartbeatExtension(SessionExtension):
self.heartbeat_task.cancel()
-class CachingExtension(SessionExtension, SessionEventListener):
+class CachingExtension(EventAwareExtension):
"""Extension for caching session state to disk.
Periodically writes session state to disk so it can be restored
@@ -133,20 +135,18 @@ class CachingExtension(SessionExtension, SessionEventListener):
interval: How often to write cache (in seconds)
mode: Whether to read cache only or read/write.
"""
+ super().__init__()
self.interval = interval
self.enabled = enabled
self.mode = mode
self.session_cache_manager: Optional[SessionCacheManager] = None
- self.event_bus: Optional[SessionEventBus] = None
def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:
"""Initialize cache manager when attached to session."""
if not self.enabled:
return
- # Subscribe to events (like rename)
- event_bus.subscribe(self)
- self.event_bus = event_bus
+ super().on_attach(session, event_bus)
from marimo._utils.inline_script_metadata import (
script_metadata_hash_from_filename,
@@ -188,9 +188,7 @@ class CachingExtension(SessionExtension, SessionEventListener):
def on_detach(self) -> None:
"""Stop cache manager when detached."""
self._stop()
- if self.event_bus:
- self.event_bus.unsubscribe(self)
- self.event_bus = None
+ super().on_detach()
async def on_session_notebook_renamed(
self, session: Session, old_path: str | None
@@ -282,25 +280,26 @@ class NotificationListenerExtension(SessionExtension):
self.distributor.stop()
self.distributor = None
+ def flush(self) -> None:
+ """Flush any pending messages from the distributor."""
+ if self.distributor is not None:
+ self.distributor.flush()
+
-class LoggingExtension(SessionExtension, SessionEventListener):
+class LoggingExtension(EventAwareExtension):
"""Extension for logging session events."""
def __init__(self, logger: Logger = LOGGER) -> None:
+ super().__init__()
self.logger = logger
- self.event_bus: Optional[SessionEventBus] = None
def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:
- del session
self.logger.debug("Attaching extensions")
- event_bus.subscribe(self)
- self.event_bus = event_bus
+ super().on_attach(session, event_bus)
def on_detach(self) -> None:
self.logger.debug("Detaching extensions")
- if self.event_bus:
- self.event_bus.unsubscribe(self)
- self.event_bus = None
+ super().on_detach()
async def on_session_created(self, session: Session) -> None:
self.logger.debug("Session created: %s", session.initialization_id)
@@ -327,24 +326,9 @@ class LoggingExtension(SessionExtension, SessionEventListener):
)
-class SessionViewExtension(SessionExtension, SessionEventListener):
+class SessionViewExtension(EventAwareExtension):
"""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,
@@ -368,24 +352,12 @@ class SessionViewExtension(SessionExtension, SessionEventListener):
session.session_view.add_raw_notification(notification)
-class QueueExtension(SessionExtension, SessionEventListener):
+class QueueExtension(EventAwareExtension):
"""Extension for handling queue operations."""
def __init__(self, queue_manager: QueueManager) -> None:
+ super().__init__()
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,
@@ -404,24 +376,9 @@ class QueueExtension(SessionExtension, SessionEventListener):
self.queue_manager.put_input(stdin)
-class ReplayExtension(SessionExtension, SessionEventListener):
+class ReplayExtension(EventAwareExtension):
"""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,
diff --git a/marimo/_session/extensions/types.py b/marimo/_session/extensions/types.py
index e5834528da..999df209d0 100644
--- a/marimo/_session/extensions/types.py
+++ b/marimo/_session/extensions/types.py
@@ -3,10 +3,23 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Protocol
+from marimo._session.events import SessionEventListener
+
if TYPE_CHECKING:
+ from collections.abc import Iterator
+ from typing import TypeVar
+
from marimo._session.events import SessionEventBus
from marimo._session.session import Session
+ _T = TypeVar("_T", bound="SessionExtension")
+
+__all__ = [
+ "EventAwareExtension",
+ "ExtensionRegistry",
+ "SessionExtension",
+]
+
class SessionExtension(Protocol):
"""Base class for session extensions.
@@ -27,3 +40,64 @@ class SessionExtension(Protocol):
def on_detach(self) -> None:
"""Called when extension is detached from session (cleanup)."""
...
+
+
+class EventAwareExtension(SessionEventListener):
+ """Base class for extensions that react to session events.
+
+ Auto-subscribes to the event bus on attach, auto-unsubscribes on detach.
+ Subclass this and override the event handlers you care about.
+ """
+
+ def __init__(self) -> None:
+ self._session: Session | None = None
+ self._event_bus: SessionEventBus | None = None
+
+ @property
+ def session(self) -> Session:
+ if self._session is None:
+ raise RuntimeError("Extension is not attached to a session")
+ return self._session
+
+ @property
+ def event_bus(self) -> SessionEventBus:
+ if self._event_bus is None:
+ raise RuntimeError("Extension is not attached to a session")
+ return self._event_bus
+
+ def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:
+ self._session = session
+ self._event_bus = event_bus
+ event_bus.subscribe(self)
+
+ def on_detach(self) -> None:
+ if self._event_bus:
+ self._event_bus.unsubscribe(self)
+ self._event_bus = None
+ self._session = None
+
+
+class ExtensionRegistry:
+ """Registry for session extensions with typed lookup."""
+
+ def __init__(self) -> None:
+ self._extensions: list[SessionExtension] = []
+
+ def add(self, *extensions: SessionExtension) -> None:
+ self._extensions.extend(extensions)
+
+ def remove(self, extension: SessionExtension) -> None:
+ if extension in self._extensions:
+ self._extensions.remove(extension)
+
+ def get(self, ext_type: type[_T]) -> _T | None:
+ for ext in self._extensions:
+ if isinstance(ext, ext_type):
+ return ext # type: ignore[return-value]
+ return None
+
+ def __iter__(self) -> Iterator[SessionExtension]:
+ return iter(list(self._extensions))
+
+ def __contains__(self, item: SessionExtension) -> bool:
+ return item in self._extensions
diff --git a/marimo/_session/file_watcher_integration.py b/marimo/_session/file_watcher_integration.py
index 917ec3678a..6e075eec5e 100644
--- a/marimo/_session/file_watcher_integration.py
+++ b/marimo/_session/file_watcher_integration.py
@@ -11,11 +11,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Callable
from marimo import _loggers
-from marimo._session.events import (
- SessionEventBus,
- SessionEventListener,
-)
-from marimo._session.extensions.types import SessionExtension
+from marimo._session.extensions.types import EventAwareExtension
from marimo._session.session import Session
from marimo._utils.file_watcher import FileWatcherManager
from marimo._utils.paths import normalize_path
@@ -25,8 +21,10 @@ LOGGER = _loggers.marimo_logger()
if TYPE_CHECKING:
from collections.abc import Awaitable
+ from marimo._session.events import SessionEventBus
-class SessionFileWatcherExtension(SessionExtension, SessionEventListener):
+
+class SessionFileWatcherExtension(EventAwareExtension):
"""Manages file watcher lifecycle for sessions."""
def __init__(
@@ -40,23 +38,21 @@ class SessionFileWatcherExtension(SessionExtension, SessionEventListener):
watcher_manager: The underlying file watcher manager
on_change_callback: The callback to invoke when a file changes
"""
+ super().__init__()
self._watcher_manager = watcher_manager
- self._event_bus: SessionEventBus | None = None
- self._session: Session | None = None
self._on_change_callback = on_change_callback
def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:
"""Attach the file watcher extension to a session."""
- self._event_bus = event_bus
- self._event_bus.subscribe(self)
- self._session = session
+ super().on_attach(session, event_bus)
if not session.app_file_manager.path:
return
# Register with the watcher manager
self._watcher_manager.add_callback(
- Path(session.app_file_manager.path), self._handle_file_change
+ self._canonicalize_path(session.app_file_manager.path),
+ self._handle_file_change,
)
LOGGER.info(
@@ -74,23 +70,20 @@ class SessionFileWatcherExtension(SessionExtension, SessionEventListener):
def on_detach(self) -> None:
"""Detach the file watcher extension from a session."""
- if not self._session:
- return
-
- if not self._session.app_file_manager.path:
- return
+ if self._session and self._session.app_file_manager.path:
+ # Remove from watcher manager
+ self._watcher_manager.remove_callback(
+ self._canonicalize_path(self._session.app_file_manager.path),
+ self._handle_file_change,
+ )
- # Remove from watcher manager
- self._watcher_manager.remove_callback(
- self._canonicalize_path(self._session.app_file_manager.path),
- self._handle_file_change,
- )
+ LOGGER.info(
+ "Detached file watcher for session %s from path %s",
+ self._session.initialization_id,
+ self._session.app_file_manager.path,
+ )
- LOGGER.info(
- "Detached file watcher for session %s from path %s",
- self._session.initialization_id,
- self._session.app_file_manager.path,
- )
+ super().on_detach()
def _canonicalize_path(self, path: str) -> Path:
"""Canonicalize a path without resolving symlinks."""
diff --git a/marimo/_session/session.py b/marimo/_session/session.py
index 432a5a047f..43b2b33c9a 100644
--- a/marimo/_session/session.py
+++ b/marimo/_session/session.py
@@ -41,7 +41,10 @@ from marimo._session.extensions.extensions import (
ReplayExtension,
SessionViewExtension,
)
-from marimo._session.extensions.types import SessionExtension
+from marimo._session.extensions.types import (
+ ExtensionRegistry,
+ SessionExtension,
+)
from marimo._session.managers import (
KernelManagerImpl,
QueueManagerImpl,
@@ -260,7 +263,8 @@ class SessionImpl(Session):
)
self.session_view = SessionView()
self.config_manager = config_manager
- self.extensions = extensions
+ self.extensions = ExtensionRegistry()
+ self.extensions.add(*extensions)
self.scratchpad_lock = asyncio.Lock()
self._kernel_manager.start_kernel()
@@ -306,7 +310,7 @@ class SessionImpl(Session):
extension: SessionExtension,
) -> Iterator[SessionExtension]:
"""Attach an extension for the duration of the context."""
- self.extensions.append(extension)
+ self.extensions.add(extension)
extension.on_attach(self, self._event_bus)
try:
yield extension
@@ -322,12 +326,9 @@ class SessionImpl(Session):
def flush_messages(self) -> None:
"""Flush any pending messages."""
- # HACK: Ideally we don't need to reach into this extension directly
- for extension in self.extensions:
- if isinstance(extension, NotificationListenerExtension):
- if extension.distributor is not None:
- extension.distributor.flush()
- return
+ ext = self.extensions.get(NotificationListenerExtension)
+ if ext is not None:
+ ext.flush()
async def rename_path(self, new_path: str) -> None:
"""Rename the path of the session."""
@@ -390,7 +391,7 @@ class SessionImpl(Session):
an exception is raised.
"""
# Consumers are also extensions, so we want to attach them to the session
- self.extensions.append(session_consumer)
+ self.extensions.add(session_consumer)
session_consumer.on_attach(self, self._event_bus)
self.room.add_consumer(
session_consumer,
diff --git a/tests/_internal/snapshots/internal_api.txt b/tests/_internal/snapshots/internal_api.txt
index c23a88f91c..e4a9b851cc 100644
--- a/tests/_internal/snapshots/internal_api.txt
+++ b/tests/_internal/snapshots/internal_api.txt
@@ -123,6 +123,8 @@ session
SessionView
extensions
CachingExtension
+ EventAwareExtension
+ ExtensionRegistry
HeartbeatExtension
LoggingExtension
NotificationListenerExtension
diff --git a/tests/_session/extensions/test_extensions.py b/tests/_session/extensions/test_extensions.py
index 56bd4ad751..3d0cc1a5d3 100644
--- a/tests/_session/extensions/test_extensions.py
+++ b/tests/_session/extensions/test_extensions.py
@@ -19,6 +19,10 @@ from marimo._session.extensions.extensions import (
ReplayExtension,
SessionViewExtension,
)
+from marimo._session.extensions.types import (
+ EventAwareExtension,
+ ExtensionRegistry,
+)
from marimo._session.model import ConnectionState, SessionMode
from marimo._session.types import KernelState
from marimo._types.ids import CellId_t, RequestId, SessionId
@@ -314,12 +318,12 @@ class TestSessionViewExtension:
extension.on_attach(mock_session, event_bus)
assert extension in event_bus._listeners
- assert extension.event_bus is not None
+ assert extension._event_bus is not None
extension.on_detach()
assert extension not in event_bus._listeners
- assert extension.event_bus is None
+ 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."""
@@ -398,12 +402,12 @@ class TestQueueExtension:
extension.on_attach(mock_session, event_bus)
assert extension in event_bus._listeners
- assert extension.event_bus is not None
+ assert extension._event_bus is not None
extension.on_detach()
assert extension not in event_bus._listeners
- assert extension.event_bus is None
+ assert extension._event_bus is None
def test_command_added_to_queue(
self, mock_session, event_bus, queue_manager
@@ -445,12 +449,12 @@ class TestReplayExtension:
extension.on_attach(mock_session, event_bus)
assert extension in event_bus._listeners
- assert extension.event_bus is not None
+ assert extension._event_bus is not None
extension.on_detach()
assert extension not in event_bus._listeners
- assert extension.event_bus is None
+ assert extension._event_bus is None
def test_execute_command_replayed(self, mock_session, event_bus) -> None:
"""Test that ExecuteCellsCommand is replayed with notifications."""
@@ -506,3 +510,120 @@ class TestReplayExtension:
mock_session.notify.assert_not_called()
extension.on_detach()
+
+
+class TestEventAwareExtension:
+ """Tests for EventAwareExtension base class."""
+
+ def test_attach_subscribes_and_sets_state(
+ self, mock_session, event_bus
+ ) -> None:
+ ext = EventAwareExtension()
+ ext.on_attach(mock_session, event_bus)
+
+ assert ext._session is mock_session
+ assert ext._event_bus is event_bus
+ assert ext in event_bus._listeners
+ # Properties work while attached
+ assert ext.session is mock_session
+ assert ext.event_bus is event_bus
+
+ def test_detach_unsubscribes_and_clears_state(
+ self, mock_session, event_bus
+ ) -> None:
+ ext = EventAwareExtension()
+ ext.on_attach(mock_session, event_bus)
+ ext.on_detach()
+
+ assert ext._session is None
+ assert ext._event_bus is None
+ assert ext not in event_bus._listeners
+
+ def test_properties_raise_when_detached(self) -> None:
+ ext = EventAwareExtension()
+ with pytest.raises(RuntimeError):
+ ext.session # noqa: B018
+ with pytest.raises(RuntimeError):
+ ext.event_bus # noqa: B018
+
+ def test_detach_without_attach_is_safe(self) -> None:
+ ext = EventAwareExtension()
+ ext.on_detach() # should not raise
+
+
+class TestNotificationListenerFlush:
+ """Tests for NotificationListenerExtension.flush()."""
+
+ def test_flush_delegates_to_distributor(self) -> None:
+ ext = NotificationListenerExtension(Mock(), Mock())
+ ext.distributor = Mock()
+ ext.flush()
+ ext.distributor.flush.assert_called_once()
+
+ def test_flush_noop_without_distributor(self) -> None:
+ ext = NotificationListenerExtension(Mock(), Mock())
+ ext.distributor = None
+ ext.flush() # should not raise
+
+
+class TestExtensionRegistry:
+ """Tests for ExtensionRegistry."""
+
+ def test_add_and_iterate(self) -> None:
+ reg = ExtensionRegistry()
+ a, b = Mock(), Mock()
+ reg.add(a, b)
+ assert list(reg) == [a, b]
+
+ def test_remove(self) -> None:
+ reg = ExtensionRegistry()
+ a = Mock()
+ reg.add(a)
+ reg.remove(a)
+ assert a not in reg
+
+ def test_remove_missing_is_safe(self) -> None:
+ reg = ExtensionRegistry()
+ reg.remove(Mock()) # should not raise
+
+ def test_get_by_type(self) -> None:
+ reg = ExtensionRegistry()
+ ext = LoggingExtension()
+ reg.add(ext)
+ assert reg.get(LoggingExtension) is ext
+ assert reg.get(HeartbeatExtension) is None
+
+ def test_iter_snapshots_list(self) -> None:
+ """Iteration uses a snapshot so mutations during iteration are safe."""
+ reg = ExtensionRegistry()
+ a, b = Mock(), Mock()
+ reg.add(a, b)
+ items = iter(reg) # snapshot taken here
+ reg.remove(b)
+ assert list(items) == [a, b] # snapshot still has b
+ assert b not in reg
+
+
+class TestEventBusEmitSafety:
+ """Tests that _emit snapshots the listener list."""
+
+ def test_unsubscribe_during_emit_is_safe(self) -> None:
+ bus = SessionEventBus()
+ calls: list[str] = []
+
+ listener_a = Mock()
+ listener_b = Mock()
+
+ listener_a.on_received_stdin = lambda _s, _t: (
+ calls.append("a"),
+ bus.unsubscribe(listener_a),
+ )
+ listener_b.on_received_stdin = lambda _s, _t: calls.append("b")
+
+ bus.subscribe(listener_a)
+ bus.subscribe(listener_b)
+ bus.emit_received_stdin(Mock(), "hi")
+
+ # Both were called even though a unsubscribed itself mid-emit
+ assert calls == ["a", "b"]
+ assert listener_a not in bus._listeners
diff --git a/tests/_session/test_file_watcher_integration.py b/tests/_session/test_file_watcher_integration.py
index 92ed94846f..9fd3b2db4d 100644
--- a/tests/_session/test_file_watcher_integration.py
+++ b/tests/_session/test_file_watcher_integration.py
@@ -60,7 +60,7 @@ def test_attach_session_with_path(
# Verify watcher was added
assert watcher_manager.add_callback.call_count == 1
call_args = watcher_manager.add_callback.call_args
- assert call_args[0][0] == Path("/path/to/file.py")
+ assert call_args[0][0] == Path("/path/to/file.py").absolute()
# Second arg is the callback function
assert callable(call_args[0][1])