Skip to content

Report a refused cast instead of hanging on it - #67

Closed
chsienki wants to merge 1 commit into
Mincka:mainfrom
chsienki:bugfix/cast-hangs-on-refusal
Closed

chsienki wants to merge 1 commit into
Mincka:mainfrom
chsienki:bugfix/cast-hangs-on-refusal

Conversation

@chsienki

Copy link
Copy Markdown

Description

A cold cast to a Chromecast can hang indefinitely. Home Assistant does not answer a service call until the service returns, so the caller waits with nothing to time out against. observed a spotcast.play call still unanswered after 150 seconds while the target device sat untouched, and the same device gave no useful error on the attempts that did return.

Four separate defects in chromecast/spotify_controller.py combine to produce that, and each is a problem on its own:

  1. launch_app waits on Chromecast.wait() twice with no timeout. When the socket client cannot reach the device it retries forever, so an unreachable device blocks the service call rather than failing it. This is the hang. The waits are now bounded by CONNECT_TIMEOUT and report what happened.

  2. The wait loop only ever checks is_launched. A device that had already replied refusing the credentials was polled over until max_attempts ran out, then reported as "Timeout when waiting for status response from Spotify app" -- a wait for an answer that had arrived and said no. The loop now also checks credential_error.

  3. _add_user_error_handler and _transfer_error_handler raise. They run on the socket client's message-routing thread, where the exception is logged as "Error doing job: AppLaunchError exception in shielded future" and discarded, so it never reaches the caller. They now record the failure and let the waiting thread raise it.

  4. Both handlers took *_, **__ and dropped the payload, which is the only account of why Spotify refused: status, statusString and spotifyError. A refusal is now reported as "Spotify refused the credentials for this device (status=108, statusString=ERROR-CANNOT-LOAD, spotifyError=409)" rather than a fixed string -- the difference between knowing to re-authorize and guessing.

No existing issue to link; happy to open one first if you would prefer that.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update

No public action, entity or WebSocket endpoint changes shape, so nothing under docs/ or the README.md tables needed updating. The externally visible change is that a failure now arrives as an AppLaunchError carrying the device's own words, where it previously arrived as a timeout or not at all.

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my code
  • I have commented on my code where necessary
  • I have added tests that are covering all code branches
  • New and existing unit tests pass locally with my changes

Additional Information

Verification

Full suite: 760 tests, OK (Python 3.14).
pylint --fail-under 9 custom_components: 9.99/10, with no messages against spotify_controller.py. The one added # pylint: disable=too-many-instance-attributes follows the existing convention in media_player/device_manager.py and spotify/account/__init__.py; recording the refusal needs an eighth attribute. Coverage of spotify_controller.py: 100% (125 statements, 10 branches, none missed).

The new tests were checked against unpatched main to confirm they actually catch the bugs rather than merely passing:

Test vs. main Catches
test_an_unreachable_device_does_not_block FAIL the untimed wait() hang (1)
test_credential_error_is_raised_to_the_caller FAIL refusal polled over until timeout (2)
8 error-handler tests ERROR in setUp the handlers raise (3)

The handler tests erroring rather than failing is itself the defect: against main, setUp cannot even construct the scenario because calling the handler throws.

Live result

Against a real Chromecast Audio that had been failing repeatedly, the same cast that had previously not answered at all returned in 9.5 seconds with playback started.

One caveat, stated plainly: deploying the patch required restarting Home Assistant, which would also clear a wedged pychromecast socket. So I cannot fully separate "the patch fixed it" from "the restart fixed it" on that one observation. The four defects above are each demonstrable from the code and are pinned by the tests independently of that run; defect 4 in particular is what produced the status=108 / ERROR-CANNOT-LOAD / spotifyError=409 values quoted above, which were previously discarded and are how the account-level refusal was identified at all.

Incidental

Fixed the typo "Credentials error. Laucnhgin spotify failed" while rewriting that message.

A cold cast to a Chromecast could hang indefinitely: Home Assistant does not
answer a service call until the service returns, so the caller waited with
nothing to time out against. Observed as a service call still unanswered after
150 seconds, while the device sat untouched.

Four things combined to produce that, and each is a problem on its own.

launch_app waited on Chromecast.wait() twice with no timeout. When the socket
client cannot reach the device it retries forever, so an unreachable device
blocked the call rather than failing it. The wait is now bounded and reports
what happened.

The wait loop only ever checked is_launched. A device that had already replied
refusing the credentials was polled over until max_attempts ran out, then
reported as "Timeout when waiting for status response from Spotify app" -- a
wait for an answer that had arrived and said no.

_add_user_error_handler and _transfer_error_handler raised. They run on the
socket client's message-routing thread, where the exception is logged as
"Error doing job: AppLaunchError exception in shielded future" and discarded,
so it never reached the caller. They now record the failure and let the
waiting thread raise it.

Both handlers took *_, **__ and dropped the payload, which is the only account
of why Spotify refused: status, statusString and spotifyError. A refusal is
now reported as "Spotify refused the credentials for this device (status=108,
statusString=ERROR-CANNOT-LOAD, spotifyError=409)" rather than a fixed string,
which is the difference between knowing to re-authorize and guessing.

Verified against a live device that had been failing: the same cast returned
in 9.5 seconds and started playback, where it had previously not answered at
all.
@chsienki
chsienki requested a review from Mincka as a code owner August 19, 2026 19:46

@Mincka Mincka left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, the diagnosis is good work and three of the four defects land cleanly. I verified the premise for defect 3 in the vendored source: pychromecast/socket_client.py:735 catches and logs any exception raised out of receive_message, so the old raise in both handlers really was discarded. Adding the credential_error check to the wait loop, and resetting both fields at the top of launch_app, are correct and fix a real "wait for an answer that already arrived" bug. I would take those as they are.

Defect 1, the one billed as the hang, needs rework. Three findings, then a patch.

1. Chromecast.wait(timeout=...) raises, so the friendly error is unreachable

pychromecast 14.0.10, pychromecast/__init__.py:487:

ready = self.status_event.wait(timeout=timeout)
if not ready:
    raise RequestTimeout("wait", cast(float, timeout))

In the exact scenario this PR targets, _wait_for_connection never reaches the is_connected check below. It propagates pychromecast.error.RequestTimeout, which derives from PyChromecastError, not HomeAssistantError. Home Assistant renders that as a generic unknown error plus a traceback rather than the crafted message, so the reporting half of the change does not happen. I confirmed it against your branch with the real exception injected:

RAISED: RequestTimeout | bases: [PyChromecastError, Exception, BaseException]
MSG: Execution of wait timed out after 20.0 s.

test_an_unreachable_device_does_not_block passes only because MagicMock(spec=Chromecast).wait returns a Mock instead of raising, so it asserts a path production never takes.

2. socket_client.is_connected does not mean reachable, and the second wait bounds nothing

SocketClient.is_connected is literally not self.connecting (socket_client.py:519), and connecting is set back to True on every reconnect attempt (socket_client.py:397), so the guard fires transiently on a client that is recovering.

Separately, status_event is set() once (pychromecast/__init__.py:440) and never cleared, there is no clear() anywhere in the module. So the second _wait_for_connection, after start_app, returns instantly no matter what, and CONNECT_TIMEOUT has no effect there. Combined, the second call could raise "Could not connect to X within 20s" after waiting zero seconds. That also means the worst case is about 30s (20 + 0 + 10), not 50.

I dropped the guard rather than repairing it. A device that already has a status but has since dropped will now fail in the poll loop with the existing timeout message, which is honest, where the guard claimed a wait that never happened.

3. The first unbounded wait is not in this file

media_player/utils.py:202:

await hass.async_add_executor_job(media_player.wait)

async_build_from_type builds a fresh Chromecast and waits on it unconditionally, before launch_app is ever called. For a cold cast to a powered-down device, which is the reported symptom, the caller blocks here forever and the two bounded waits inside launch_app are never reached. As it stands the PR does not close the path it describes.

4. Write ordering in both handlers (minor, but it costs you the diagnostic)

The waiting thread does not only wake on waiting.set(), it polls every second via self.waiting.wait(1). A poll landing between these two lines reads credential_error as True with launch_error still None, takes the or fallback, and discards exactly the status=108 / ERROR-CANNOT-LOAD / spotifyError=409 detail this PR exists to surface. Assigning launch_error first closes it.

Suggested patch

Small enough to fold into this PR rather than split it. Extracting wait_for_connection as a module function lets utils.py reuse it, which is what closes finding 3.

Source diff
diff --git a/custom_components/spotcast/chromecast/__init__.py b/custom_components/spotcast/chromecast/__init__.py
index 7517328..eb68868 100644
--- a/custom_components/spotcast/chromecast/__init__.py
+++ b/custom_components/spotcast/chromecast/__init__.py
@@ -1,9 +1,13 @@
 """Module for libraries working with the chromecast media system
 
 Classes:
     - SpotifyController
+
+Functions:
+    - wait_for_connection
 """
 
 from custom_components.spotcast.chromecast.spotify_controller import (
-    SpotifyController
+    SpotifyController,
+    wait_for_connection,
 )
diff --git a/custom_components/spotcast/chromecast/spotify_controller.py b/custom_components/spotcast/chromecast/spotify_controller.py
index 454122a..8576997 100644
--- a/custom_components/spotcast/chromecast/spotify_controller.py
+++ b/custom_components/spotcast/chromecast/spotify_controller.py
@@ -8,12 +8,13 @@ from logging import getLogger
 import threading
 import time
 import json
 
 from pychromecast.controllers import BaseController
 from pychromecast.controllers import CastMessage
+from pychromecast.error import RequestTimeout
 from requests import post, Response, HTTPError
 
 from custom_components.spotcast.spotify import SpotifyAccount
 from custom_components.spotcast.media_player.chromecast_player import (
     Chromecast
 )
@@ -26,27 +27,51 @@ LOGGER = getLogger(__name__)
 
 # A speaker group fans the app launch out to each of its members, so its
 # cast/zeroconf traffic needs a moment to settle before the group can answer
 # a `getInfo` request reliably. Single devices do not need this.
 GROUP_LAUNCH_DELAY = 3.0
 
-# `Chromecast.wait()` has no timeout of its own and retries forever, so an
-# unreachable device would block the caller rather than fail it.
+# `Chromecast.wait()` blocks forever when called without a timeout, which
+# is how an unreachable device used to block the caller instead of failing
+# it. Given a timeout it raises `RequestTimeout` instead of returning.
 CONNECT_TIMEOUT = 20.0
 
 
+def wait_for_connection(device: Chromecast):
+    """Waits for a device to be reachable, bounded by CONNECT_TIMEOUT
+
+    Args:
+        - device(Chromecast): the device to wait for
+
+    Raises:
+        - AppLaunchError: when the device is not reachable in time
+    """
+    try:
+        device.wait(timeout=CONNECT_TIMEOUT)
+    except RequestTimeout as exc:
+        raise AppLaunchError(
+            f"Could not connect to `{device.name}` within "
+            f"{CONNECT_TIMEOUT:.0f}s. The device may be powered down or "
+            "unreachable on the network."
+        ) from exc
+
+
 class SpotifyController(  # pylint: disable=too-many-instance-attributes
     BaseController
 ):
     """A Chromcast controller for interacting with Spotify
 
     Attributes:
         - account(SpotifyAccount): The spotify account in charge of the
             spotify controller
         - waiting(threading.Event): A threading Event loop manager
         - is_launched(bool): True if the app is currently launched
+        - credential_error(bool): True if the device refused the
+            credentials or the playback transfer
+        - launch_error(str): what the device said when it refused,
+            for the waiting thread to raise
 
     Constants:
         - APP_ID(str): the chromecast app code for spotify
         - APP_NAME(str): the chromecast namespace for spotify
         - APP_HOSTNAME(str): the hostname for the spotify API
         - TYPE_GET_INFO(str): mesage type to get info
@@ -135,18 +160,18 @@ class SpotifyController(  # pylint: disable=too-many-instance-attributes
                 "deviceID": device.id,
                 "deviceAPI_isGroup": device.is_group,
             }
         }
 
         LOGGER.debug("Waiting for `%s` to be ready", device.name)
-        self._wait_for_connection(device)
+        wait_for_connection(device)
 
         LOGGER.debug("Starting Spotify on `%s`", device.name)
         device.start_app(self.APP_ID)
         LOGGER.debug("Waiting for `%s` to be available", device.name)
-        self._wait_for_connection(device)
+        wait_for_connection(device)
 
         self.waiting.clear()
 
         LOGGER.debug("Requesting Spotify App to launch on `%s`", device.name)
         self.launch(callback_function=self._send_message_callback)
 
@@ -178,24 +203,12 @@ class SpotifyController(  # pylint: disable=too-many-instance-attributes
                 "Spotify App not yet launched on `%s`. Waiting Before retry",
                 device.name,
             )
             self.waiting.wait(1)
             counter += 1
 
-    def _wait_for_connection(self, device: Chromecast):
-        """Waits for the device to be reachable, bounded by CONNECT_TIMEOUT"""
-        device.wait(timeout=CONNECT_TIMEOUT)
-
-        socket_client = getattr(device, "socket_client", None)
-        if socket_client is not None and not socket_client.is_connected:
-            raise AppLaunchError(
-                f"Could not connect to `{device.name}` within "
-                f"{CONNECT_TIMEOUT:.0f}s. The device may be powered down or "
-                "unreachable on the network."
-            )
-
     def stop_app(self, device: Chromecast):
         """Stops the Spotify app on the device"""
         device.quit_app()
         self.is_launched = False
 
     def receive_message(self, _message: CastMessage, data: dict) -> bool:
@@ -286,30 +299,34 @@ class SpotifyController(  # pylint: disable=too-many-instance-attributes
 
     def _add_user_error_handler(
         self, _message: CastMessage, data: dict
     ) -> bool:
         """Handler for the add user error message"""
         self.current_device = None
-        self.credential_error = True
         self.launch_error = self._describe(
             "Spotify refused the credentials for this device", data
         )
+        # Set last: the waiting thread polls, so it can read this flag
+        # without waking on `waiting.set()`, and must not find it set
+        # while `launch_error` is still empty.
+        self.credential_error = True
         LOGGER.error("%s", self.launch_error)
         self.waiting.set()
 
         return True
 
     def _transfer_error_handler(
         self, _message: CastMessage, data: dict
     ) -> bool:
         """Handler for the transfer error message"""
         self.current_device = None
-        self.credential_error = True
         self.launch_error = self._describe(
             "Spotify refused to transfer playback to this device", data
         )
+        # Set last, see `_add_user_error_handler`.
+        self.credential_error = True
         LOGGER.error("%s", self.launch_error)
         self.waiting.set()
 
         return True
 
     @staticmethod
diff --git a/custom_components/spotcast/media_player/utils.py b/custom_components/spotcast/media_player/utils.py
index db5ef4f..0141beb 100644
--- a/custom_components/spotcast/media_player/utils.py
+++ b/custom_components/spotcast/media_player/utils.py
@@ -23,13 +23,16 @@ from custom_components.spotcast.media_player import (
     MediaPlayer,
     Chromecast,
     SpotifyDevice,
     SpotifyAccount,
 )
 
-from custom_components.spotcast.chromecast import SpotifyController
+from custom_components.spotcast.chromecast import (
+    SpotifyController,
+    wait_for_connection,
+)
 
 LOGGER = getLogger(__name__)
 
 PLAYER_TYPES = (
     Chromecast,
     SpotifyDevice,
@@ -196,13 +199,13 @@ async def async_build_from_type(
             # HA's cast integration keeps CastInfo private with no
             # public accessor.
             entity._cast_info.cast_info,  # pylint: disable=protected-access
             zconf=ChromeCastZeroconf.get_zeroconf()
         )
 
-        await hass.async_add_executor_job(media_player.wait)
+        await hass.async_add_executor_job(wait_for_connection, media_player)
 
         spotify_controller = SpotifyController(account)
         media_player.register_handler(spotify_controller)
         await account.async_playback_state()
 
         do_quit = need_to_quit_app(media_player, account)
Test diff
diff --git a/test/chromecast/spotify_controller/test_add_user_error_handler.py b/test/chromecast/spotify_controller/test_add_user_error_handler.py
index 238a456..efd65b0 100644
--- a/test/chromecast/spotify_controller/test_add_user_error_handler.py
+++ b/test/chromecast/spotify_controller/test_add_user_error_handler.py
@@ -4,13 +4,12 @@ from unittest import TestCase
 from unittest.mock import MagicMock, patch
 
 from custom_components.spotcast.chromecast.spotify_controller import (
     SpotifyController,
     SpotifyAccount,
     CastMessage,
-    AppLaunchError,
 )
 
 TEST_MODULE = "custom_components.spotcast.chromecast.spotify_controller"
 
 
 class TestAddUserErrorHandling(TestCase):
@@ -46,6 +45,38 @@ class TestAddUserErrorHandling(TestCase):
     def test_credentials_error_set(self):
         self.assertTrue(self.controller.credential_error)
 
     def test_records_what_the_device_said(self):
         self.assertIn("ERROR-CANNOT-LOAD", self.controller.launch_error)
         self.assertIn("409", self.controller.launch_error)
+
+
+class TestAddUserErrorRecordOrdering(TestCase):
+    """`launch_error` must be readable as soon as the flag is set
+
+    The waiting thread polls `credential_error` every second rather
+    than only waking on `waiting.set()`, so a poll landing between
+    the two assignments would report the generic message and drop
+    what the device actually said.
+    """
+
+    @patch(f"{TEST_MODULE}.threading.Event")
+    def test_detail_is_recorded_before_the_flag_is_raised(
+            self,
+            mock_event: MagicMock,  # pylint: disable=W0613
+    ):
+        controller = SpotifyController(MagicMock(spec=SpotifyAccount))
+        observed = []
+
+        with patch.object(
+                SpotifyController,
+                "_describe",
+                side_effect=lambda *_: observed.append(
+                    controller.credential_error
+                ) or "detail",
+        ):
+            controller._add_user_error_handler(
+                MagicMock(spec=CastMessage),
+                {},
+            )
+
+        self.assertEqual(observed, [False])
diff --git a/test/chromecast/spotify_controller/test_launch_app.py b/test/chromecast/spotify_controller/test_launch_app.py
index f241f90..27d8b87 100644
--- a/test/chromecast/spotify_controller/test_launch_app.py
+++ b/test/chromecast/spotify_controller/test_launch_app.py
@@ -1,17 +1,20 @@
 """Module to test the launch_app function"""
 
 from unittest import TestCase
 from unittest.mock import MagicMock, patch
 from threading import Event
 
+from pychromecast.error import RequestTimeout
+
 from custom_components.spotcast.chromecast.spotify_controller import (
     SpotifyController,
     SpotifyAccount,
     Chromecast,
     AppLaunchError,
+    CONNECT_TIMEOUT,
 )
 
 TEST_MODULE = "custom_components.spotcast.chromecast.spotify_controller."
 
 
 class TestAppLaunch(TestCase):
@@ -96,13 +99,16 @@ class TestAppFailLaunch(TestCase):
 
 
 class TestCredentialRefusal(TestCase):
     """A refusal reported by the device must reach the caller"""
 
     @patch.object(SpotifyController, "launch")
-    def test_credential_error_is_raised_to_the_caller(self, mock_launch: MagicMock):
+    def test_credential_error_is_raised_to_the_caller(
+            self,
+            mock_launch: MagicMock,
+    ):
         controller = SpotifyController(MagicMock(spec=SpotifyAccount))
 
         def refuse(*_, **__):
             controller._add_user_error_handler(
                 MagicMock(),
                 {"payload": {"statusString": "ERROR-CANNOT-LOAD",
@@ -114,19 +120,26 @@ class TestCredentialRefusal(TestCase):
         with self.assertRaises(AppLaunchError) as caught:
             controller.launch_app(MagicMock(spec=Chromecast), max_attempts=10)
 
         self.assertIn("ERROR-CANNOT-LOAD", str(caught.exception))
 
     @patch.object(SpotifyController, "launch")
-    def test_an_unreachable_device_does_not_block(self, mock_launch: MagicMock):
-        """An unreachable device fails the call rather than blocking it"""
+    def test_an_unreachable_device_does_not_block(
+            self,
+            mock_launch: MagicMock,
+    ):
+        """An unreachable device fails the call rather than blocking it
+
+        `Chromecast.wait(timeout=...)` raises `RequestTimeout` rather
+        than returning, so that is what the device does here.
+        """
         controller = SpotifyController(MagicMock(spec=SpotifyAccount))
 
         device = MagicMock(spec=Chromecast)
-        device.socket_client = MagicMock()
-        device.socket_client.is_connected = False
+        device.wait.side_effect = RequestTimeout("wait", CONNECT_TIMEOUT)
 
         with self.assertRaises(AppLaunchError) as caught:
             controller.launch_app(device, max_attempts=2)
 
         self.assertIn("Could not connect", str(caught.exception))
         mock_launch.assert_not_called()
+        device.wait.assert_called_once_with(timeout=CONNECT_TIMEOUT)
diff --git a/test/chromecast/spotify_controller/test_transfer_error_handler.py b/test/chromecast/spotify_controller/test_transfer_error_handler.py
index fb2e9c8..594a0c8 100644
--- a/test/chromecast/spotify_controller/test_transfer_error_handler.py
+++ b/test/chromecast/spotify_controller/test_transfer_error_handler.py
@@ -4,13 +4,12 @@ from unittest import TestCase
 from unittest.mock import MagicMock, patch
 
 from custom_components.spotcast.chromecast.spotify_controller import (
     SpotifyController,
     SpotifyAccount,
     CastMessage,
-    AppLaunchError,
 )
 
 TEST_MODULE = "custom_components.spotcast.chromecast.spotify_controller"
 
 
 class TestTransferErrorHandling(TestCase):
@@ -46,6 +45,38 @@ class TestTransferErrorHandling(TestCase):
     def test_credentials_error_set(self):
         self.assertTrue(self.controller.credential_error)
 
     def test_records_what_the_device_said(self):
         self.assertIn("ERROR-CANNOT-LOAD", self.controller.launch_error)
         self.assertIn("409", self.controller.launch_error)
+
+
+class TestTransferErrorRecordOrdering(TestCase):
+    """`launch_error` must be readable as soon as the flag is set
+
+    The waiting thread polls `credential_error` every second rather
+    than only waking on `waiting.set()`, so a poll landing between
+    the two assignments would report the generic message and drop
+    what the device actually said.
+    """
+
+    @patch(f"{TEST_MODULE}.threading.Event")
+    def test_detail_is_recorded_before_the_flag_is_raised(
+            self,
+            mock_event: MagicMock,  # pylint: disable=W0613
+    ):
+        controller = SpotifyController(MagicMock(spec=SpotifyAccount))
+        observed = []
+
+        with patch.object(
+                SpotifyController,
+                "_describe",
+                side_effect=lambda *_: observed.append(
+                    controller.credential_error
+                ) or "detail",
+        ):
+            controller._transfer_error_handler(
+                MagicMock(spec=CastMessage),
+                {},
+            )
+
+        self.assertEqual(observed, [False])
diff --git a/test/media_player/utils/test_async_build_from_type.py b/test/media_player/utils/test_async_build_from_type.py
index 5222d7d..5613435 100644
--- a/test/media_player/utils/test_async_build_from_type.py
+++ b/test/media_player/utils/test_async_build_from_type.py
@@ -9,12 +9,13 @@ from custom_components.spotcast.media_player.utils import (
     Chromecast,
     SpotifyDevice,
     UnknownIntegrationError,
     HomeAssistant,
     SpotifyAccount,
     SpotifyController,
+    wait_for_connection,
 )
 
 TEST_MODULE = "custom_components.spotcast.media_player.utils"
 
 
 class DummyDevice:
@@ -149,12 +150,21 @@ class TestCastDeviceRunningNonSpotifyApp(IsolatedAsyncioTestCase):
     def test_quit_app_not_run(self):
         try:
             self.mock_chromecast.quit_app.assert_called()
         except AssertionError:
             self.fail()
 
+    def test_initial_wait_is_bounded(self):
+        """The first wait must be the bounded one, not `Chromecast.wait`,
+        which blocks forever against an unreachable device.
+        """
+        self.mock_hass.async_add_executor_job.assert_any_call(
+            wait_for_connection,
+            self.mock_chromecast,
+        )
+
 
 class TestCastDeviceRunningSpotifyAppForOtherAccount(IsolatedAsyncioTestCase):
 
     @patch(f"{TEST_MODULE}.Chromecast", new_callable=MagicMock)
     async def asyncSetUp(self, mock_chromecast: MagicMock):
 

Verification

  • Full suite: 763 tests, OK (your 760 plus 3).
  • pylint --fail-under 9 custom_components: 10.00/10. The too-many-instance-attributes disable is still needed, the count is 8.
  • Each new or changed test checked to fail against the code it fixes, not merely to pass:
    • test_an_unreachable_device_does_not_block now injects RequestTimeout and errors out without the try/except.
    • the two test_detail_is_recorded_before_the_flag_is_raised tests fail with the original assignment order.
    • test_initial_wait_is_bounded pins the utils.py call so it cannot quietly revert to media_player.wait.

Notes on the patch: the second wait_for_connection in launch_app is kept for structural parity even though it is a no-op today, since it was equally a no-op before this PR and would start working if pychromecast ever clears status_event. Both handler test files also lose their now-unused AppLaunchError import, left over from the try/except you removed.

One thing I deliberately did not touch: nothing in the codebase ever calls disconnect() on a Chromecast it constructs, so a failed launch leaves a socket client retrying for the life of the process. That predates this PR, but the PR makes failures return in 20s instead of blocking, so retries against a dead device now accumulate faster. Worth its own issue rather than growing this one.

@Mincka

Mincka commented Aug 30, 2026

Copy link
Copy Markdown
Owner

Hi,
Do you plan to do the suggested edits for a merge?
Otherwise, I'll just close your PR and cherry pick the suggested fixes myself. Thank you.

Mincka added a commit that referenced this pull request Sep 7, 2026
* Report a refused cast instead of hanging on it

A cold cast to a Chromecast could hang indefinitely: Home Assistant does not
answer a service call until the service returns, so the caller waited with
nothing to time out against. Observed as a service call still unanswered after
150 seconds, while the device sat untouched.

Four things combined to produce that, and each is a problem on its own.

launch_app waited on Chromecast.wait() twice with no timeout. When the socket
client cannot reach the device it retries forever, so an unreachable device
blocked the call rather than failing it. The wait is now bounded and reports
what happened.

The wait loop only ever checked is_launched. A device that had already replied
refusing the credentials was polled over until max_attempts ran out, then
reported as "Timeout when waiting for status response from Spotify app" -- a
wait for an answer that had arrived and said no.

_add_user_error_handler and _transfer_error_handler raised. They run on the
socket client's message-routing thread, where the exception is logged as
"Error doing job: AppLaunchError exception in shielded future" and discarded,
so it never reached the caller. They now record the failure and let the
waiting thread raise it.

Both handlers took *_, **__ and dropped the payload, which is the only account
of why Spotify refused: status, statusString and spotifyError. A refusal is
now reported as "Spotify refused the credentials for this device (status=108,
statusString=ERROR-CANNOT-LOAD, spotifyError=409)" rather than a fixed string,
which is the difference between knowing to re-authorize and guessing.

Verified against a live device that had been failing: the same cast returned
in 9.5 seconds and started playback, where it had previously not answered at
all.

* Bound every Chromecast wait and surface a credential refusal to the caller

Follow-up to the cherry-picked fix from #67:

- `Chromecast.wait(timeout=...)` raises `RequestTimeout` rather than
  returning, so the bounded wait is wrapped in `wait_for_connection`
  and re-raised as `AppLaunchError`, which Home Assistant renders.
- The first unbounded wait was in `async_build_from_type`, before
  `launch_app` ever ran; it now uses the same bounded helper.
- Dropped the `socket_client.is_connected` guard, which only reflects
  `not connecting` and fires transiently during reconnects.
- Both error handlers record `launch_error` before setting
  `credential_error`, since the waiting thread polls the flag and
  would otherwise fall back to the generic message.
- CHANGELOG entry.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Track Home Assistant 2026.9.1 in the dev lock and drop the PyJWT override

Home Assistant pins PyJWT 2.13.0 itself from 2026.8.0, so the uv
override that forced it in the dev environment is no longer needed.
`uv lock --upgrade` moves the dev lock from HA 2026.7.2 to 2026.9.1
(pylint 4.0.8, coverage 7.16.0, RapidFuzz 3.14.6 and friends). A
pip-audit over the locked environment reports no known vulnerabilities.

Also applies the one pylint refactor hint left in `rate_limit.py`
(`max()` instead of an `if` block), which is behaviour-preserving.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
@Mincka

Mincka commented Sep 7, 2026

Copy link
Copy Markdown
Owner

Closing in favour of #71, which is now merged and ships in v6.6.2. Your commit is cherry-picked there as-is for credit, with the review's follow-ups applied on top (bounded wait that wraps RequestTimeout, the same bounded wait in async_build_from_type where the actual hang was, no is_connected guard, and launch_error written before credential_error). Thanks for the diagnosis, the three handler-side fixes landed exactly as you wrote them.

@Mincka Mincka mentioned this pull request Sep 7, 2026
1 task done
@Mincka Mincka closed this Sep 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants