Repository: home-assistant/core
Pull request: Fix mobile_app cloudhook creation
<!--
  You are amazing! Thanks for contributing to our project!
  Please, DO NOT DELETE ANY TEXT from this template! (unless instructed).
-->
## Breaking change
<!--
  If your PR contains a breaking change for existing users, it is important
  to tell them what breaks, how to make it work again and why we did this.
  This piece of text is published with the release notes, so it helps if you
  write it towards our users, not us.
  Note: Remove this section if this PR is NOT a breaking change.
-->


## Proposed change
<!--
  Describe the big picture of your changes here to communicate to the
  maintainers why we should accept this pull request. If it fixes a bug
  or resolves a feature request, be sure to link to that issue in the
  additional information section.
-->
During a debug session with @ludeeus, we found that for some devices a cloudhook already exists but was not saved in the mobile_app config entry. We couldn't identify when they were created (at least on my instance) but they were created before HA 2024.1.
Other integrations like withings are always deleting the cloudhook before creating:
https://github.com/home-assistant/core/blob/896ca8ce83ff2c945b62e424028beb81e64b7c1d/homeassistant/components/withings/__init__.py#L334-L340

Deleting and then creating returns a different (new) cloudhook url. In the mobile app use case, we don't want to do that as maybe the cloud hook is used by the app even when it was not correctly stored in the config entry.

To reuse already created cloud hooks  `async_get_or_create_cloudhook` is added, which returns the cloudhook_url if a cloudhook for the passed webhook_id exists. Otherwise, a cloudhook is created.

We think that also other integrations like withings can benefit from the new function.


In addition we guard the cloudhook creation with a `asyncio.Lock` to prevent parallel execution.


## Type of change
<!--
  What type of change does your PR introduce to Home Assistant?
  NOTE: Please, check only 1! box!
  If your PR requires multiple boxes to be checked, you'll most likely need to
  split it into multiple PRs. This makes things easier and faster to code review.
-->

- [ ] Dependency upgrade
- [x] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [ ] New feature (which adds functionality to an existing integration)
- [ ] Deprecation (breaking change to happen in the future)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests

## Additional information
<!--
  Details are important, and help maintainers processing your PR.
  Please be sure to fill out additional details, if applicable.
-->

- This PR fixes or closes issue: fixes #107021
- This PR is related to issue: 
- Link to documentation pull request: 

## Checklist
<!--
  Put an `x` in the boxes that apply. You can also fill these out after
  creating the PR. If you're unsure about any of them, don't hesitate to ask.
  We're here to help! This is simply a reminder of what we are going to look
  for before merging your code.
-->

- [ ] The code change is tested and works locally.
- [ ] Local tests pass. **Your PR cannot be merged unless tests pass**
- [ ] There is no commented out code in this PR.
- [ ] I have followed the [development checklist][dev-checklist]
- [ ] I have followed the [perfect PR recommendations][perfect-pr]
- [ ] The code has been formatted using Ruff (`ruff format homeassistant tests`)
- [ ] Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

- [ ] Documentation added/updated for [www.home-assistant.io][docs-repository]

If the code communicates with devices, web services, or third-party tools:

- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.  
      Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.  
      Updated by running `python3 -m script.gen_requirements_all`.
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.
- [ ] Untested files have been added to `.coveragerc`.

<!--
  This project is very active and we have a high turnover of pull requests.

  Unfortunately, the number of incoming pull requests is higher than what our
  reviewers can review and merge so there is a long backlog of pull requests
  waiting for review. You can help here!
  
  By reviewing another pull request, you will help raise the code quality of
  that pull request and the final review will be faster. This way the general
  pace of pull request reviews will go up and your wait time will go down.
  
  When picking a pull request to review, try to choose one that hasn't yet
  been reviewed.

  Thanks for helping out!
-->

To help with the load of incoming pull requests:

- [x] I have reviewed two other [open pull requests][prs] in this repository.

[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure

<!--
  Thank you for contributing <3

  Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/development_checklist/
[manifest-docs]: https://developers.home-assistant.io/docs/creating_integration_manifest/
[quality-scale]: https://developers.home-assistant.io/docs/integration_quality_scale_index/
[docs-repository]: https://github.com/home-assistant/home-assistant.io
[perfect-pr]: https://developers.home-assistant.io/docs/review-process/#creating-the-perfect-pr


Problem statement:
Device Tracker on Mobile app stopped working with 2024.01
### The problem

The device tracker of one of my phones stopped working with the update 2024.01.
I have no access to the sensor data of the phone.

According to the log there seems to be a problem with the cloud hooks.
I already updated the home assistant app and did several restarts on the server and devices.


### What version of Home Assistant Core has the issue?

2024.01

### What was the last working version of Home Assistant Core?

2023.04

### What type of installation are you running?

Home Assistant OS

### Integration causing the issue

Device Tracker iPhone

### Link to integration documentation on our website

_No response_

### Diagnostics information

_No response_

### Example YAML snippet

_No response_

### Anything in the logs that might be useful for us?

```

Logger: homeassistant.config_entries
Source: config_entries.py:406
First occurred: 00:03:26 (1 occurrences)
Last logged: 00:03:26

Error setting up entry iPhoneAlex (14) for mobile_app
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 406, in async_setup
    result = await component.async_setup_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/mobile_app/__init__.py", line 125, in async_setup_entry
    await create_cloud_hook()
  File "/usr/src/homeassistant/homeassistant/components/mobile_app/__init__.py", line 108, in create_cloud_hook
    hook = await cloud.async_create_cloudhook(hass, webhook_id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/cloud/__init__.py", line 189, in async_create_cloudhook
    hook = await cloud.cloudhooks.async_create(webhook_id, True)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/hass_nabucasa/cloudhooks.py", line 40, in async_create
    raise ValueError("Hook is already enabled for the cloud.")
ValueError: Hook is already enabled for the cloud.

Logger: homeassistant.config_entries
Source: config_entries.py:406
First occurred: 00:04:31 (1 occurrences)
Last logged: 00:04:31

Error setting up entry iPhoneAlex (14) for mobile_app
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 406, in async_setup
    result = await component.async_setup_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/mobile_app/__init__.py", line 104, in async_setup_entry
    webhook_register(hass, DOMAIN, registration_name, webhook_id, handle_webhook)
  File "/usr/src/homeassistant/homeassistant/components/webhook/__init__.py", line 53, in async_register
    raise ValueError("Handler is already defined!")
ValueError: Handler is already defined!
```

### Additional information

_No response_

Hints from issue discussion:
Hey there @home-assistant/core, mind taking a look at this issue as it has been labeled with an integration (`mobile_app`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L798) for? Thanks!

<details>
<summary>Code owner commands</summary>


Code owners of `mobile_app` can trigger bot actions by commenting:

- `@home-assistant close` Closes the issue.
- `@home-assistant rename Awesome new title` Renames the issue.
- `@home-assistant reopen` Reopen the issue.
- `@home-assistant unassign mobile_app` Removes the current integration label and assignees on the issue, add the integration domain after the command.
- `@home-assistant add-label needs-more-information` Add a label (needs-more-information, problem in dependency, problem in custom component) to the issue.
- `@home-assistant remove-label needs-more-information` Remove a label (needs-more-information, problem in dependency, problem in custom component) on the issue.

</details>


<sub><sup>(message by CodeOwnersMention)</sup></sub>

---

[mobile_app documentation](https://www.home-assistant.io/integrations/mobile_app)
[mobile_app source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/mobile_app)
<sub><sup>(message by IssueLinks)</sup></sub>
Having same issue on Android for 3 devices. 
Same issue on Pixel 5a and 6a.
The mobile app integration isn't mobile phone brand specific so there's no need to comment with what brand of mobile phone you're using.

We'll ask for more information if we need it. Thank you!
me 3
Same here, stopped working on 2 out of 3 android phones directly when i updated to 2024.1
Everything is up to date.
The mobile app integration says that those two devices "Failed to set up"
Same problem for 2 android devices:

```
2024-01-04 08:37:15.303 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry Henri mobiel for mobile_app
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 406, in async_setup
    result = await component.async_setup_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/mobile_app/__init__.py", line 104, in async_setup_entry
    webhook_register(hass, DOMAIN, registration_name, webhook_id, handle_webhook)
  File "/usr/src/homeassistant/homeassistant/components/webhook/__init__.py", line 53, in async_register
    raise ValueError("Handler is already defined!")
ValueError: Handler is already defined!
2024-01-04 08:37:19.031 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry Mardy mobiel for mobile_app
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 406, in async_setup
    result = await component.async_setup_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/mobile_app/__init__.py", line 104, in async_setup_entry
    webhook_register(hass, DOMAIN, registration_name, webhook_id, handle_webhook)
  File "/usr/src/homeassistant/homeassistant/components/webhook/__init__.py", line 53, in async_register
    raise ValueError("Handler is already defined!")
ValueError: Handler is already defined!
```
Same problem here

```
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 406, in async_setup
    result = await component.async_setup_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/mobile_app/__init__.py", line 125, in async_setup_entry
    await create_cloud_hook()
  File "/usr/src/homeassistant/homeassistant/components/mobile_app/__init__.py", line 108, in create_cloud_hook
    hook = await cloud.async_create_cloudhook(hass, webhook_id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/cloud/__init__.py", line 189, in async_create_cloudhook
    hook = await cloud.cloudhooks.async_create(webhook_id, True)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/hass_nabucasa/cloudhooks.py", line 40, in async_create
    raise ValueError("Hook is already enabled for the cloud.")
ValueError: Hook is already enabled for the cloud.
```
It doesn't help to comment the same log entry as in the description again. We are analyzing the problem.
Also Martin has already written, that you don't need to comment each model.
Same problem... 
Xiaomi MI11 and xiaomi Mi10 lite...
Logger: homeassistant.config_entries
Source: config_entries.py:406
First occurred: 08:49:03 (2 occurrences)
Last logged: 08:49:03

Error setting up entry M2011K2G for mobile_app
Error setting up entry M2007J17G for mobile_app
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 406, in async_setup
    result = await component.async_setup_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/mobile_app/__init__.py", line 125, in async_setup_entry
    await create_cloud_hook()
  File "/usr/src/homeassistant/homeassistant/components/mobile_app/__init__.py", line 108, in create_cloud_hook
    hook = await cloud.async_create_cloudhook(hass, webhook_id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/cloud/__init__.py", line 189, in async_create_cloudhook
    hook = await cloud.cloudhooks.async_create(webhook_id, True)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/hass_nabucasa/cloudhooks.py", line 40, in async_create
    raise ValueError("Hook is already enabled for the cloud.")
ValueError: Hook is already enabled for the cloud.

Commit message: Fix import cycle

Patch to review:
diff --git a/homeassistant/components/cloud/__init__.py b/homeassistant/components/cloud/__init__.py
index d7d57835e3ade1..6e5cddd0f28764 100644
--- a/homeassistant/components/cloud/__init__.py
+++ b/homeassistant/components/cloud/__init__.py
@@ -5,6 +5,7 @@
 from collections.abc import Awaitable, Callable
 from datetime import datetime, timedelta
 from enum import Enum
+from typing import cast
 
 from hass_nabucasa import Cloud
 import voluptuous as vol
@@ -176,6 +177,22 @@ def async_active_subscription(hass: HomeAssistant) -> bool:
     return async_is_logged_in(hass) and not hass.data[DOMAIN].subscription_expired
 
 
+async def async_get_or_create_cloudhook(hass: HomeAssistant, webhook_id: str) -> str:
+    """Get or create a cloudhook."""
+    if not async_is_connected(hass):
+        raise CloudNotConnected
+
+    if not async_is_logged_in(hass):
+        raise CloudNotAvailable
+
+    cloud: Cloud[CloudClient] = hass.data[DOMAIN]
+    cloudhooks = cloud.client.cloudhooks
+    if hook := cloudhooks.get(webhook_id):
+        return cast(str, hook["cloudhook_url"])
+
+    return await async_create_cloudhook(hass, webhook_id)
+
+
 @bind_hass
 async def async_create_cloudhook(hass: HomeAssistant, webhook_id: str) -> str:
     """Create a cloudhook."""
diff --git a/homeassistant/components/mobile_app/__init__.py b/homeassistant/components/mobile_app/__init__.py
index cb5c0ae5c3ddd2..9350cf4bb042d8 100644
--- a/homeassistant/components/mobile_app/__init__.py
+++ b/homeassistant/components/mobile_app/__init__.py
@@ -36,6 +36,7 @@
 )
 from .helpers import savable_state
 from .http_api import RegistrationsView
+from .util import create_cloud_hook
 from .webhook import handle_webhook
 
 PLATFORMS = [Platform.SENSOR, Platform.BINARY_SENSOR, Platform.DEVICE_TRACKER]
@@ -103,26 +104,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
     registration_name = f"Mobile App: {registration[ATTR_DEVICE_NAME]}"
     webhook_register(hass, DOMAIN, registration_name, webhook_id, handle_webhook)
 
-    async def create_cloud_hook() -> None:
-        """Create a cloud hook."""
-        hook = await cloud.async_create_cloudhook(hass, webhook_id)
-        hass.config_entries.async_update_entry(
-            entry, data={**entry.data, CONF_CLOUDHOOK_URL: hook}
-        )
-
     async def manage_cloudhook(state: cloud.CloudConnectionState) -> None:
         if (
             state is cloud.CloudConnectionState.CLOUD_CONNECTED
             and CONF_CLOUDHOOK_URL not in entry.data
         ):
-            await create_cloud_hook()
+            await create_cloud_hook(hass, webhook_id, entry)
 
     if (
         CONF_CLOUDHOOK_URL not in entry.data
         and cloud.async_active_subscription(hass)
         and cloud.async_is_connected(hass)
     ):
-        await create_cloud_hook()
+        await create_cloud_hook(hass, webhook_id, entry)
+
     entry.async_on_unload(cloud.async_listen_connection_change(hass, manage_cloudhook))
 
     await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
diff --git a/homeassistant/components/mobile_app/http_api.py b/homeassistant/components/mobile_app/http_api.py
index 3c34a291df15e9..6d075ba54bbdd0 100644
--- a/homeassistant/components/mobile_app/http_api.py
+++ b/homeassistant/components/mobile_app/http_api.py
@@ -35,6 +35,7 @@
     SCHEMA_APP_DATA,
 )
 from .helpers import supports_encryption
+from .util import create_cloud_hook
 
 
 class RegistrationsView(HomeAssistantView):
@@ -69,9 +70,7 @@ async def post(self, request: Request, data: dict) -> Response:
         webhook_id = secrets.token_hex()
 
         if cloud.async_active_subscription(hass):
-            data[CONF_CLOUDHOOK_URL] = await cloud.async_create_cloudhook(
-                hass, webhook_id
-            )
+            data[CONF_CLOUDHOOK_URL] = await create_cloud_hook(hass, webhook_id, None)
 
         data[CONF_WEBHOOK_ID] = webhook_id
 
diff --git a/homeassistant/components/mobile_app/util.py b/homeassistant/components/mobile_app/util.py
index 45641861e5cd61..f8786da9040f4d 100644
--- a/homeassistant/components/mobile_app/util.py
+++ b/homeassistant/components/mobile_app/util.py
@@ -1,8 +1,11 @@
 """Mobile app utility functions."""
 from __future__ import annotations
 
+import asyncio
 from typing import TYPE_CHECKING
 
+from homeassistant.components import cloud
+from homeassistant.config_entries import ConfigEntry
 from homeassistant.core import HomeAssistant, callback
 
 from .const import (
@@ -10,6 +13,7 @@
     ATTR_PUSH_TOKEN,
     ATTR_PUSH_URL,
     ATTR_PUSH_WEBSOCKET_CHANNEL,
+    CONF_CLOUDHOOK_URL,
     DATA_CONFIG_ENTRIES,
     DATA_DEVICES,
     DATA_NOTIFY,
@@ -53,3 +57,20 @@ def get_notify_service(hass: HomeAssistant, webhook_id: str) -> str | None:
             return target_service
 
     return None
+
+
+_CLOUD_HOOK_LOCK = asyncio.Lock()
+
+
+@callback
+async def create_cloud_hook(
+    hass: HomeAssistant, webhook_id: str, entry: ConfigEntry | None
+) -> str:
+    """Create a cloud hook."""
+    async with _CLOUD_HOOK_LOCK:
+        hook = await cloud.async_get_or_create_cloudhook(hass, webhook_id)
+        if entry:
+            hass.config_entries.async_update_entry(
+                entry, data={**entry.data, CONF_CLOUDHOOK_URL: hook}
+            )
+        return hook
diff --git a/tests/components/cloud/test_init.py b/tests/components/cloud/test_init.py
index e12775d5a4a5f4..c12f9314bce52e 100644
--- a/tests/components/cloud/test_init.py
+++ b/tests/components/cloud/test_init.py
@@ -6,8 +6,9 @@
 import pytest
 
 from homeassistant.components import cloud
+from homeassistant.components.cloud.client import CloudClient
 from homeassistant.components.cloud.const import DOMAIN
-from homeassistant.components.cloud.prefs import STORAGE_KEY
+from homeassistant.components.cloud.prefs import STORAGE_KEY, CloudPreferences
 from homeassistant.const import EVENT_HOMEASSISTANT_STOP
 from homeassistant.core import Context, HomeAssistant
 from homeassistant.exceptions import Unauthorized
@@ -214,3 +215,49 @@ async def test_remote_ui_url(hass: HomeAssistant, mock_cloud_fixture) -> None:
         cl.client.prefs._prefs["remote_domain"] = "example.com"
 
         assert cloud.async_remote_ui_url(hass) == "https://example.com"
+
+
+async def test_async_get_or_create_cloudhook(
+    hass: HomeAssistant, mock_cloud_fixture: CloudPreferences
+) -> None:
+    """Test async_get_or_create_cloudhook."""
+    cl: Cloud[CloudClient] = hass.data[DOMAIN]
+    webhook_id = "mock-webhook-id"
+
+    # Not connected
+    with pytest.raises(cloud.CloudNotConnected):
+        await cloud.async_get_or_create_cloudhook(hass, webhook_id)
+
+    # Simulate connected
+    cl.iot.state = "connected"
+
+    # Not logged in
+    with pytest.raises(cloud.CloudNotAvailable):
+        await cloud.async_get_or_create_cloudhook(hass, webhook_id)
+
+    cloudhook_url = "https://cloudhook.nabu.casa/abcdefg"
+
+    with patch.object(cloud, "async_is_logged_in", return_value=True), patch.object(
+        cloud, "async_create_cloudhook", return_value=cloudhook_url
+    ) as async_create_cloudhook_mock:
+        # create cloudhook as it does not exist
+        assert (
+            await cloud.async_get_or_create_cloudhook(hass, webhook_id)
+        ) == cloudhook_url
+        async_create_cloudhook_mock.assert_called_once_with(hass, webhook_id)
+
+        mock_cloud_fixture._prefs[cloud.const.PREF_CLOUDHOOKS] = {
+            webhook_id: {
+                "webhook_id": webhook_id,
+                "cloudhook_id": "random-id",
+                "cloudhook_url": cloudhook_url,
+                "managed": True,
+            }
+        }
+        async_create_cloudhook_mock.reset_mock()
+
+        # get cloudhook as it exists
+        assert (
+            await cloud.async_get_or_create_cloudhook(hass, webhook_id) == cloudhook_url
+        )
+        async_create_cloudhook_mock.assert_not_called()
diff --git a/tests/components/mobile_app/test_init.py b/tests/components/mobile_app/test_init.py
index d504703c222339..6a365e84fb0f1f 100644
--- a/tests/components/mobile_app/test_init.py
+++ b/tests/components/mobile_app/test_init.py
@@ -88,15 +88,17 @@ async def _test_create_cloud_hook(
     ), patch(
         "homeassistant.components.cloud.async_is_connected", return_value=True
     ), patch(
-        "homeassistant.components.cloud.async_create_cloudhook", autospec=True
-    ) as mock_create_cloudhook:
+        "homeassistant.components.cloud.async_get_or_create_cloudhook", autospec=True
+    ) as mock_async_get_or_create_cloudhook:
         cloud_hook = "https://hook-url"
-        mock_create_cloudhook.return_value = cloud_hook
+        mock_async_get_or_create_cloudhook.return_value = cloud_hook
 
         assert await hass.config_entries.async_setup(config_entry.entry_id)
         await hass.async_block_till_done()
         assert config_entry.state is ConfigEntryState.LOADED
-        await additional_steps(config_entry, mock_create_cloudhook, cloud_hook)
+        await additional_steps(
+            config_entry, mock_async_get_or_create_cloudhook, cloud_hook
+        )
 
 
 async def test_create_cloud_hook_on_setup(


Code review comments:
diff_hunk: @@ -214,3 +215,49 @@ async def test_remote_ui_url(hass: HomeAssistant, mock_cloud_fixture) -> None:
         cl.client.prefs._prefs["remote_domain"] = "example.com"
 
         assert cloud.async_remote_ui_url(hass) == "https://example.com"
+
+
+async def test_async_get_or_create_cloudhook(
+    hass: HomeAssistant, mock_cloud_fixture: CloudPreferences
+) -> None:
+    """Test async_get_or_create_cloudhook."""
+    cl: Cloud[CloudClient] = hass.data[DOMAIN]
path: tests/components/cloud/test_init.py
text: @user1:
Can we use the `cloud` fixture instead?

diff_hunk: @@ -53,3 +57,20 @@ def get_notify_service(hass: HomeAssistant, webhook_id: str) -> str | None:
             return target_service
 
     return None
+
+
+_CLOUD_HOOK_LOCK = asyncio.Lock()
+
+
+@callback
+async def create_cloud_hook(
path: homeassistant/components/mobile_app/util.py
text: @user1:
Since this function is imported by other modules, I think we should prefix its name with `async_`
```suggestion
async def async_create_cloud_hook(
```