diff --git a/custom_components/pyscript/decorator.py b/custom_components/pyscript/decorator.py index 4af6b60..31a0694 100644 --- a/custom_components/pyscript/decorator.py +++ b/custom_components/pyscript/decorator.py @@ -217,7 +217,14 @@ async def handle_exception(self, exc: Exception) -> None: async def wait_until(self) -> dict[str, Any]: """Wait for dispatch and normalize the return payload.""" - data = await self._future + try: + data = await self._future + except asyncio.CancelledError: + # dispatch() and handle_exception() stop the decorators; a cancelled wait reaches + # neither, so stop them here unless a trigger fired just before the cancel + if self.status is DecoratorManagerStatus.RUNNING: + await self.stop() + raise if data.trigger == self.timeout_decorator: ret = {"trigger_type": "timeout"} else: diff --git a/tests/test_decorator_manager.py b/tests/test_decorator_manager.py index 32149f0..5e7ac43 100644 --- a/tests/test_decorator_manager.py +++ b/tests/test_decorator_manager.py @@ -632,6 +632,26 @@ async def test_wait_until_ignores_exception_after_completion(hass): assert await dm.wait_until() == {"value": 1} +@pytest.mark.asyncio +async def test_wait_until_stops_decorators_when_cancelled(hass): + """Cancelling the waiting task should stop the wait's decorators.""" + DecoratorManager.hass = hass + events: list[tuple[str, str]] = [] + dm = WaitUntilDecoratorManager(DummyAstCtx()) + dm.add(make_recording_decorator("trigger", events)) + await dm.validate() + await dm.start() + + waiter = asyncio.create_task(dm.wait_until()) + await asyncio.sleep(0) + waiter.cancel() + with pytest.raises(asyncio.CancelledError): + await waiter + + assert ("stop", "trigger") in events + assert dm.status is DecoratorManagerStatus.STOPPED + + @pytest.mark.asyncio async def test_function_decorator_manager_cancel_calls_result_handlers(hass): """Canceled calls should still notify result handlers with None."""