Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/acp/task/supervisor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio
import inspect
import logging
from collections.abc import Awaitable, Callable
from typing import Any
Expand All @@ -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.

Expand Down Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions tests/test_observer_awaitables.py
Original file line number Diff line number Diff line change
@@ -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()
Loading