diff --git a/src/acp/task/supervisor.py b/src/acp/task/supervisor.py index 48765ad8..b4c8aa66 100644 --- a/src/acp/task/supervisor.py +++ b/src/acp/task/supervisor.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import inspect import logging from collections.abc import Awaitable, Callable from typing import Any @@ -10,6 +11,10 @@ ErrorHandler = Callable[[asyncio.Task[Any], BaseException], None] +async def _await_result(awaitable: Awaitable[Any]) -> Any: + return await awaitable + + class TaskSupervisor: """Track background tasks and provide graceful shutdown semantics. @@ -37,7 +42,7 @@ def create( if self._closed: msg = f"TaskSupervisor for {self._source} already closed" raise RuntimeError(msg) - task = asyncio.create_task(coroutine, name=name) + task = asyncio.create_task(coroutine if inspect.iscoroutine(coroutine) else _await_result(coroutine), name=name) self._tasks.add(task) task.add_done_callback(lambda t: self._on_done(t, on_error)) return task diff --git a/tests/test_observer_awaitables.py b/tests/test_observer_awaitables.py new file mode 100644 index 00000000..b5703c5c --- /dev/null +++ b/tests/test_observer_awaitables.py @@ -0,0 +1,38 @@ +"""A Future-returning observer must not interrupt notification delivery.""" + +from __future__ import annotations + +import asyncio + +import pytest + +from acp._transport import memory_transport_pair +from acp.connection import Connection + + +@pytest.mark.asyncio +async def test_future_returning_observer_preserves_delivery() -> None: + source, peer = memory_transport_pair() + future: asyncio.Future[None] = asyncio.get_running_loop().create_future() + observed = [] + + def observer(event): + observed.append(event.direction.value) + return future + + async def handler(method, params, notification): + return None + + connection = Connection(handler, source, observers=[observer], listening=False) + try: + await connection.send_notification("example", {"value": 1}) + message = await asyncio.wait_for(peer.receive(), 1) + assert message["method"] == "example" + assert observed == ["outgoing"] + future.set_result(None) + await asyncio.sleep(0) + finally: + await connection.close() + await peer.close() + if not future.done(): + future.cancel()