Add logbook websocket command to get action calls (#187344)

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Joost Lekkerkerker
2026-10-23 08:44:17 +00:00
committed by GitHub
co-authored by Claude
parent 22e419e946
commit 4cd7f184f7
5 changed files with 488 additions and 16 deletions
@@ -41,6 +41,8 @@ LOGBOOK_ENTRY_RUN_ID = "run_id"
LOGBOOK_ENTRY_SOURCE = "source"
LOGBOOK_ENTRY_MESSAGE = "message"
LOGBOOK_ENTRY_NAME = "name"
LOGBOOK_ENTRY_SERVICE = "service"
LOGBOOK_ENTRY_SERVICE_DATA = "service_data"
LOGBOOK_ENTRY_STATE = "state"
LOGBOOK_ENTRY_ATTRIBUTES = "attributes"
LOGBOOK_ENTRY_WHEN = "when"
+41 -13
View File
@@ -15,6 +15,7 @@ from sqlalchemy.orm import Session
from homeassistant.components.recorder import get_instance
from homeassistant.components.recorder.filters import Filters
from homeassistant.components.recorder.models import (
bytes_to_ulid_or_none,
bytes_to_uuid_hex_or_none,
decode_attributes_from_source,
extract_event_type_ids,
@@ -28,6 +29,7 @@ from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_NAME,
ATTR_SERVICE,
ATTR_SERVICE_DATA,
EVENT_CALL_SERVICE,
EVENT_LOGBOOK_ENTRY,
EntityStateAttribute,
@@ -54,11 +56,14 @@ from .const import (
DOMAIN,
EXPOSED_STATE_ATTRIBUTES,
LOGBOOK_ENTRY_ATTRIBUTES,
LOGBOOK_ENTRY_CONTEXT_ID,
LOGBOOK_ENTRY_DOMAIN,
LOGBOOK_ENTRY_ENTITY_ID,
LOGBOOK_ENTRY_ICON,
LOGBOOK_ENTRY_MESSAGE,
LOGBOOK_ENTRY_NAME,
LOGBOOK_ENTRY_SERVICE,
LOGBOOK_ENTRY_SERVICE_DATA,
LOGBOOK_ENTRY_SOURCE,
LOGBOOK_ENTRY_STATE,
LOGBOOK_ENTRY_WHEN,
@@ -83,6 +88,7 @@ from .models import (
async_event_to_row,
)
from .queries import statement_for_request
from .queries.action_calls import action_calls_stmt
from .queries.common import (
PSEUDO_EVENT_STATE_CHANGED,
select_context_user_ids_for_context_ids,
@@ -109,6 +115,8 @@ class LogbookRun:
entity_name_cache: EntityNameCache
include_entity_name: bool
timestamp: bool
# True to output action calls, which are otherwise only used to link contexts.
action_calls: bool = False
memoize_new_contexts: bool = True
# True when this run will switch to a live stream; gates population of
# context_user_ids (wasted work for one-shot REST/get_events callers).
@@ -133,17 +141,22 @@ class EventProcessor:
timestamp: bool = False,
include_entity_name: bool = True,
for_live_stream: bool = False,
action_calls: bool = False,
) -> None:
"""Init the event stream."""
assert not (context_id and (entity_ids or device_ids)), (
"can't pass in both context_id and (entity_ids or device_ids)"
)
assert not (action_calls and (context_id or entity_ids or device_ids)), (
"can't pass in both action_calls and (context_id or entity_ids or device_ids)"
)
self.hass = hass
self.ent_reg = er.async_get(hass)
self.event_types = event_types
self.entity_ids = entity_ids
self.device_ids = device_ids
self.context_id = context_id
self.action_calls = action_calls
logbook_config: LogbookConfig = hass.data[DOMAIN]
self.filters: Filters | None = logbook_config.sqlalchemy_filter
self.logbook_run = LogbookRun(
@@ -153,6 +166,7 @@ class EventProcessor:
entity_name_cache=EntityNameCache(self.hass),
include_entity_name=include_entity_name,
timestamp=timestamp,
action_calls=action_calls,
for_live_stream=for_live_stream,
)
self.context_augmenter = ContextAugmenter(self.logbook_run)
@@ -191,16 +205,21 @@ class EventProcessor:
instance.event_type_manager.get_many(self.event_types, session)
)
)
stmt = statement_for_request(
start_day,
end_day,
event_type_ids,
self.entity_ids,
metadata_ids,
self.device_ids,
self.filters,
self.context_id,
)
if self.action_calls:
stmt = action_calls_stmt(
start_day.timestamp(), end_day.timestamp(), event_type_ids
)
else:
stmt = statement_for_request(
start_day,
end_day,
event_type_ids,
self.entity_ids,
metadata_ids,
self.device_ids,
self.filters,
self.context_id,
)
rows = execute_stmt_lambda_element(session, stmt, orm_rows=False)
query_parent_user_ids: dict[bytes, bytes] | None = None
if self.entity_ids or self.device_ids:
@@ -293,7 +312,7 @@ def _exposed_state_attributes(
}
def _humanify(
def _humanify( # noqa: C901
hass: HomeAssistant,
rows: Generator[EventAsRow] | Sequence[Row] | Result,
ent_reg: er.EntityRegistry,
@@ -310,6 +329,7 @@ def _humanify(
entity_name_cache_get = logbook_run.entity_name_cache.get
include_entity_name = logbook_run.include_entity_name
timestamp = logbook_run.timestamp
action_calls = logbook_run.action_calls
memoize_new_contexts = logbook_run.memoize_new_contexts
get_context = context_augmenter.get_context
context_id_bin: bytes
@@ -336,9 +356,17 @@ def _humanify(
continue
event_type = row[EVENT_TYPE_POS]
if event_type == EVENT_CALL_SERVICE:
continue
if not action_calls:
continue
event_data = event_cache_get(row).data
data = {
LOGBOOK_ENTRY_DOMAIN: event_data.get(ATTR_DOMAIN),
LOGBOOK_ENTRY_SERVICE: event_data.get(ATTR_SERVICE),
LOGBOOK_ENTRY_SERVICE_DATA: event_data.get(ATTR_SERVICE_DATA, {}),
LOGBOOK_ENTRY_CONTEXT_ID: bytes_to_ulid_or_none(context_id_bin),
}
if event_type is PSEUDO_EVENT_STATE_CHANGED:
elif event_type is PSEUDO_EVENT_STATE_CHANGED:
entity_id = row[ENTITY_ID_POS]
if TYPE_CHECKING:
assert entity_id is not None
@@ -0,0 +1,91 @@
"""Action call queries for logbook."""
from sqlalchemy import lambda_stmt, select, union_all
from sqlalchemy.sql.lambdas import StatementLambdaElement
from sqlalchemy.sql.selectable import CTE, CompoundSelect, Select
from homeassistant.components.recorder.db_schema import (
EventData,
Events,
EventTypes,
States,
StatesMeta,
)
from .common import (
apply_events_context_hints,
apply_states_context_hints,
select_events_context_id_subquery,
select_events_context_only,
select_events_without_states,
select_states_context_only,
)
def _select_action_call_context_ids_sub_query(
start_day: float,
end_day: float,
event_type_ids: tuple[int, ...],
) -> Select:
"""Generate a subquery to find the context ids of the action calls and parents."""
union = union_all(
select_events_context_id_subquery(start_day, end_day, event_type_ids),
select(Events.context_parent_id_bin.label("context_id_bin"))
.where((Events.time_fired_ts > start_day) & (Events.time_fired_ts < end_day))
.where(Events.event_type_id.in_(event_type_ids))
.where(Events.context_parent_id_bin.is_not(None)),
).subquery()
return select(union.c.context_id_bin).group_by(union.c.context_id_bin)
def _apply_action_calls_context_union(
sel: Select,
start_day: float,
end_day: float,
event_type_ids: tuple[int, ...],
) -> CompoundSelect:
"""Generate a CTE to find the action call context ids and their linked rows.
The linked events and states are not limited to the time window, so the
origin of a context or its parent, like the automation run, action, or
state change that made the call, is found even when it was before the
window.
"""
action_calls_cte: CTE = _select_action_call_context_ids_sub_query(
start_day, end_day, event_type_ids
).cte()
return sel.union_all(
apply_events_context_hints(
select_events_context_only()
.select_from(action_calls_cte)
.outerjoin(
Events, action_calls_cte.c.context_id_bin == Events.context_id_bin
)
.outerjoin(EventTypes, (Events.event_type_id == EventTypes.event_type_id))
.outerjoin(EventData, (Events.data_id == EventData.data_id))
),
apply_states_context_hints(
select_states_context_only()
.select_from(action_calls_cte)
.outerjoin(
States, action_calls_cte.c.context_id_bin == States.context_id_bin
)
.outerjoin(StatesMeta, (States.metadata_id == StatesMeta.metadata_id))
),
)
def action_calls_stmt(
start_day: float,
end_day: float,
event_type_ids: tuple[int, ...],
) -> StatementLambdaElement:
"""Generate a logbook query for action calls."""
return lambda_stmt(
lambda: _apply_action_calls_context_union(
select_events_without_states(start_day, end_day, event_type_ids),
start_day,
end_day,
event_type_ids,
).order_by(Events.time_fired_ts)
)
@@ -54,6 +54,7 @@ def async_setup(hass: HomeAssistant) -> None:
"""Set up the logbook websocket API."""
websocket_api.async_register_command(hass, ws_get_events)
websocket_api.async_register_command(hass, ws_event_stream)
websocket_api.async_register_command(hass, ws_get_action_calls)
@callback
@@ -517,3 +518,59 @@ async def ws_get_events(
event_processor,
)
)
@websocket_api.require_admin
@websocket_api.websocket_command(
{
probatio.Required("type"): "logbook/get_action_calls",
probatio.Required("start_time"): str,
probatio.Optional("end_time"): str,
}
)
@websocket_api.async_response
async def ws_get_action_calls(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle logbook get action calls websocket command.
Admin only, since the action data can contain secrets like alarm codes.
"""
end_time_str = msg.get("end_time")
utc_now = dt_util.utcnow()
if start_time := dt_util.parse_datetime(msg["start_time"]):
start_time = dt_util.as_utc(start_time)
else:
connection.send_error(msg["id"], "invalid_start_time", "Invalid start_time")
return
if not end_time_str:
end_time = utc_now
elif parsed_end_time := dt_util.parse_datetime(end_time_str):
end_time = dt_util.as_utc(parsed_end_time)
else:
connection.send_error(msg["id"], "invalid_end_time", "Invalid end_time")
return
if start_time > utc_now:
connection.send_result(msg["id"], [])
return
event_processor = EventProcessor(
hass,
(EVENT_CALL_SERVICE,),
timestamp=True,
include_entity_name=False,
action_calls=True,
)
connection.send_message(
await get_instance(hass).async_add_executor_job(
_ws_formatted_get_events,
msg["id"],
start_time,
end_time,
event_processor,
)
)
+297 -3
View File
@@ -1,7 +1,7 @@
"""The tests for the logbook component."""
import asyncio
from collections.abc import Callable
from collections.abc import Awaitable, Callable
from datetime import timedelta
from typing import Any
from unittest.mock import ANY, patch
@@ -9,7 +9,12 @@ from unittest.mock import ANY, patch
import attr
from freezegun import freeze_time
import pytest
from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed
from pytest_homeassistant.common import (
MockConfigEntry,
MockUser,
async_fire_time_changed,
async_mock_service,
)
from pytest_homeassistant.components.recorder.common import (
async_block_recorder,
async_recorder_block_till_done,
@@ -45,7 +50,7 @@ from homeassistant.const import (
STATE_ON,
STATE_UNKNOWN,
)
from homeassistant.core import Event, HomeAssistant, State, callback
from homeassistant.core import Event, HomeAssistant, ServiceCall, State, callback
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entityfilter import CONF_ENTITY_GLOBS
from homeassistant.helpers.event import async_track_state_change_event
@@ -3823,3 +3828,292 @@ async def test_logbook_stream_live_parent_service_call_only(
assert len(heater_entries) == 1
assert heater_entries[0]["state"] == "on"
assert heater_entries[0]["context_user_id"] == user_id
async def test_get_action_calls(
recorder_mock: Recorder,
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_admin_user: MockUser,
) -> None:
"""Test logbook get_action_calls describes what made each call."""
now = dt_util.utcnow()
assert await async_setup_component(hass, "logbook", {})
assert await async_setup_component(
hass,
"automation",
{
"automation": {
"id": "caller",
"alias": "Caller",
"triggers": {"trigger": "event", "event_type": "test_event"},
"actions": {"action": "test.inner", "data": {"from": "automation"}},
}
},
)
async_mock_service(hass, "test", "inner")
async def _async_outer(call: ServiceCall) -> None:
await hass.services.async_call(
"test", "inner", {"from": "outer"}, blocking=True, context=call.context
)
hass.services.async_register("test", "outer", _async_outer)
await async_recorder_block_till_done(hass)
user_context = core.Context(user_id=hass_admin_user.id)
await hass.services.async_call(
"test",
"outer",
{ATTR_ENTITY_ID: "light.kitchen"},
blocking=True,
context=user_context,
)
# The automation runs in a child context of the event, without a user
hass.bus.async_fire("test_event", context=core.Context(user_id=hass_admin_user.id))
await hass.async_block_till_done()
await async_wait_recording_done(hass)
client = await hass_ws_client()
await client.send_json_auto_id(
{"type": "logbook/get_action_calls", "start_time": now.isoformat()}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == [
{
"when": ANY,
"domain": "test",
"service": "outer",
"service_data": {ATTR_ENTITY_ID: "light.kitchen"},
"context_id": user_context.id,
"context_user_id": hass_admin_user.id,
},
{
"when": ANY,
"domain": "test",
"service": "inner",
"service_data": {"from": "outer"},
"context_id": user_context.id,
"context_user_id": hass_admin_user.id,
"context_event_type": EVENT_CALL_SERVICE,
"context_domain": "test",
"context_service": "outer",
},
{
"when": ANY,
"domain": "test",
"service": "inner",
"service_data": {"from": "automation"},
"context_id": ANY,
"context_user_id": hass_admin_user.id,
"context_event_type": EVENT_AUTOMATION_TRIGGERED,
"context_domain": "automation",
"context_name": "Caller",
"context_entity_id": "automation.caller",
"context_message": "triggered by event 'test_event'",
"context_source": "event 'test_event'",
},
]
assert isinstance(response["result"][0]["when"], float)
await client.send_json_auto_id(
{
"type": "logbook/get_action_calls",
"start_time": now.isoformat(),
"end_time": now.isoformat(),
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == []
async def test_get_action_calls_context_older_than_start_time(
recorder_mock: Recorder, hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test an action call is described by a context that started before start_time."""
now = dt_util.utcnow()
assert await async_setup_component(hass, "logbook", {})
assert await async_setup_component(hass, "script", {})
async_mock_service(hass, "test", "inner")
await async_recorder_block_till_done(hass)
context = core.Context()
with freeze_time(now - timedelta(hours=1)):
hass.bus.async_fire(
EVENT_SCRIPT_STARTED,
{ATTR_NAME: "Mock script", ATTR_ENTITY_ID: "script.mock_script"},
context=context,
)
await hass.async_block_till_done()
await hass.services.async_call("test", "inner", blocking=True, context=context)
await async_wait_recording_done(hass)
client = await hass_ws_client()
await client.send_json_auto_id(
{
"type": "logbook/get_action_calls",
"start_time": (now - timedelta(minutes=30)).isoformat(),
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == [
{
"when": ANY,
"domain": "test",
"service": "inner",
"service_data": {},
"context_id": context.id,
"context_event_type": EVENT_SCRIPT_STARTED,
"context_domain": "script",
"context_name": "Mock script",
"context_entity_id": "script.mock_script",
"context_message": "started",
},
]
async def _async_call_parent_action(hass: HomeAssistant, context: core.Context) -> None:
"""Call an action in the parent context."""
await hass.services.async_call("test", "parent", blocking=True, context=context)
async def _async_set_parent_state(hass: HomeAssistant, context: core.Context) -> None:
"""Change a state in the parent context, like a sensor update."""
hass.states.async_set("sensor.temperature", "18", context=context)
@pytest.mark.parametrize(
("async_make_parent", "parent_origin"),
[
pytest.param(
_async_call_parent_action,
{
"context_event_type": EVENT_CALL_SERVICE,
"context_domain": "test",
"context_service": "parent",
},
id="action",
),
pytest.param(
_async_set_parent_state,
{"context_state": "18", "context_entity_id": "sensor.temperature"},
id="state",
),
],
)
async def test_get_action_calls_parent_context_older_than_start_time(
recorder_mock: Recorder,
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_admin_user: MockUser,
async_make_parent: Callable[[HomeAssistant, core.Context], Awaitable[None]],
parent_origin: dict[str, str],
) -> None:
"""Test an action call is described by a parent context from before start_time."""
now = dt_util.utcnow()
assert await async_setup_component(hass, "logbook", {})
async_mock_service(hass, "test", "parent")
async_mock_service(hass, "test", "child")
await async_recorder_block_till_done(hass)
parent_context = core.Context(user_id=hass_admin_user.id)
with freeze_time(now - timedelta(hours=1)):
await async_make_parent(hass, parent_context)
await hass.async_block_till_done()
# A child context, like a thermostat switching its heater
child_context = core.Context(parent_id=parent_context.id)
await hass.services.async_call(
"test", "child", blocking=True, context=child_context
)
await async_wait_recording_done(hass)
client = await hass_ws_client()
await client.send_json_auto_id(
{
"type": "logbook/get_action_calls",
"start_time": (now - timedelta(minutes=30)).isoformat(),
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == [
{
"when": ANY,
"domain": "test",
"service": "child",
"service_data": {},
"context_id": child_context.id,
"context_user_id": hass_admin_user.id,
**parent_origin,
},
]
async def test_get_action_calls_future_start_time(
recorder_mock: Recorder, hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test get_action_calls with a future start time."""
assert await async_setup_component(hass, "logbook", {})
await async_recorder_block_till_done(hass)
client = await hass_ws_client()
await client.send_json_auto_id(
{
"type": "logbook/get_action_calls",
"start_time": (dt_util.utcnow() + timedelta(hours=1)).isoformat(),
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == []
@pytest.mark.parametrize(
("time_range", "error_code"),
[
pytest.param({"start_time": "cats"}, "invalid_start_time", id="start_time"),
pytest.param(
{"start_time": "2026-01-01T00:00:00+00:00", "end_time": "cats"},
"invalid_end_time",
id="end_time",
),
],
)
async def test_get_action_calls_bad_time(
recorder_mock: Recorder,
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
time_range: dict[str, str],
error_code: str,
) -> None:
"""Test get_action_calls with an invalid time."""
assert await async_setup_component(hass, "logbook", {})
await async_recorder_block_till_done(hass)
client = await hass_ws_client()
await client.send_json_auto_id({"type": "logbook/get_action_calls", **time_range})
response = await client.receive_json()
assert not response["success"]
assert response["error"]["code"] == error_code
async def test_get_action_calls_requires_admin(
recorder_mock: Recorder,
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_read_only_access_token: str,
) -> None:
"""Test get_action_calls requires an admin, as action data can hold secrets."""
assert await async_setup_component(hass, "logbook", {})
await async_recorder_block_till_done(hass)
client = await hass_ws_client(hass, hass_read_only_access_token)
await client.send_json_auto_id(
{"type": "logbook/get_action_calls", "start_time": dt_util.utcnow().isoformat()}
)
response = await client.receive_json()
assert not response["success"]
assert response["error"]["code"] == "unauthorized"