Files
advanced-camera-card/src/components-lib/timeline/source.ts
T
Dermot DuffyandClaude Opus 4.8 b701366762 feat: Align automations with Home Assistant triggers and conditions (#2527)
Split automations into HA-style `triggers`, ongoing `conditions`, and
`actions`, with compatibility migrations for existing Advanced Camera
Card configs.

## Summary

At a glance (details below):

- **Added** `triggers:` -- a required, HA-shaped block: stock `state` /
`numeric_state` / `template` plus card-specific triggers (`camera`,
`view`, `fullscreen`, ...).
- **Added** the HA-native `if` / `then` / `else` action.
- **Removed** `actions_not` (replaced by `if` / `then` / `else`).
- **Removed** the ambient `advanced_camera_card` template namespace (use
`acc` instead).
- **Changed** the trigger template surface to a top-level `trigger.*`
variable (as in HA); the nested `acc.trigger.*` paths are removed.
- **Changed** `conditions:` to ongoing gates only -- they no longer wake
an automation, and change-only forms (`config`, valueless `camera` /
`view` / `state`) become triggers, not conditions.
- **Changed** action templates to render per step, so a later action
sees state an earlier one changed.
- **Compatibility:** HA-shaped YAML is accepted (singular keys,
single-or-list, `and` / `or` / `not` shorthand, `entity` / `entity_id`).
- **Migration:** existing configs upgrade automatically; anything that
cannot be converted faithfully is recorded under `__UPGRADE_FAILURE__`
for manual fixup.

## Breaking Changes

### 1. Automations now require triggers

Before this PR, `automations[].conditions` served two roles:

- They decided whether the automation should run.
- They also acted as the thing that woke the automation up.

After this PR:

- `triggers` wake the automation.
- `conditions` only gate it at the instant a trigger fires.

Most existing automations are migrated automatically from `conditions:`
to `triggers:`.

### 2. `actions_not` is retired

Legacy `actions_not` is replaced by an HA-style `if` action with `then`
/ `else`.

Faithful conversions are automatic. Cases that cannot be faithfully
converted are recorded under `__UPGRADE_FAILURE__.automations` and must
be migrated manually.

### 3. Template surface aligned with Home Assistant

Two related template changes, both auto-migrated:

- **Top-level `trigger.*`.** Automation actions now receive a top-level
`trigger` template variable, like Home Assistant. Legacy nested paths
such as `acc.trigger.state.to` and
`advanced_camera_card.trigger.camera.to` are migrated automatically when
they appear inside template strings.
- **The ambient `advanced_camera_card` template namespace is removed.**
The long-form ambient namespace (`advanced_camera_card.camera`,
`advanced_camera_card.view`, `advanced_camera_card.config`) is retired
in favour of its shorter `acc` alias -- supported since v7.1.0, and the
only spelling the new trigger surface uses. Existing templates are
migrated automatically by rewriting the `advanced_camera_card.` prefix
to `acc.`.

### 4. Trigger-only condition forms are no longer valid conditions

Some legacy "conditions" were really change detectors. These are now
triggers only:

- `condition: config`
- valueless `camera`
- valueless `view`
- valueless `state` / picture-elements state condition with neither
`state` nor `state_not`

These are automatically promoted in automations and stripped from
overrides/elements where they would no longer be meaningful as ongoing
conditions.

### 5. Template truthiness now follows Home Assistant behavior

Template conditions and template triggers intentionally use different
truthiness rules, matching HA:

- A template condition passes only when the rendered value is `true`
(case-insensitive), matching HA's `condition.py`.
- A template trigger uses HA's broader `result_as_boolean` coercion: a
non-zero number, or `1` / `true` / `yes` / `on` / `enable`
(case-insensitive), counts as true.

### 6. Action templates render when each action executes

Action templates are now rendered per action step, not once for the
whole sequence. This means a later action can see card-local state
changed by an earlier action in the same sequence.

The `trigger` context is fixed for the automation run. HA entity state
updates still depend on the frontend receiving updated HASS state over
the websocket.

## Automatic Migrations

### Automation `conditions:` to `triggers:`

Simple legacy automation:

```yaml
# Before
automations:
  - conditions:
      - condition: fullscreen
        fullscreen: true
    actions:
      - action: custom:advanced-camera-card-action
        advanced_camera_card_action: substream_on
```

```yaml
# After, automatic
automations:
  - triggers:
      - trigger: fullscreen
        fullscreen: true
    actions:
      - action: custom:advanced-camera-card-action
        advanced_camera_card_action: substream_on
```

State conditions become HA-style state triggers:

```yaml
# Before
automations:
  - conditions:
      - condition: state
        entity_id: binary_sensor.front_door
        state: 'on'
    actions:
      - action: custom:advanced-camera-card-action
        advanced_camera_card_action: live
```

```yaml
# After, automatic
automations:
  - triggers:
      - trigger: state
        entity_id: binary_sensor.front_door
        to: 'on'
    actions:
      - action: custom:advanced-camera-card-action
        advanced_camera_card_action: live
```

Multiple conditions become both triggers and ongoing conditions:

```yaml
# Before
automations:
  - conditions:
      - condition: camera
        cameras: [front_door]
      - condition: fullscreen
        fullscreen: true
    actions:
      - action: custom:advanced-camera-card-action
        advanced_camera_card_action: substream_on
```

```yaml
# After, automatic
automations:
  - triggers:
      - trigger: camera
        cameras: [front_door]
      - trigger: fullscreen
        fullscreen: true
    conditions:
      - condition: camera
        cameras: [front_door]
      - condition: fullscreen
        fullscreen: true
    actions:
      - action: custom:advanced-camera-card-action
        advanced_camera_card_action: substream_on
```

The flattened trigger list is an implicit OR. The retained `conditions:`
list is an implicit AND checked when any trigger fires.

### Trigger-only legacy conditions

Legacy `config` conditions become `config` triggers:

```yaml
# Before
automations:
  - conditions:
      - condition: config
        paths: [menu.style]
    actions:
      - action: custom:advanced-camera-card-action
        advanced_camera_card_action: status_bar
```

```yaml
# After, automatic
automations:
  - triggers:
      - trigger: config
        paths: [menu.style]
    actions:
      - action: custom:advanced-camera-card-action
        advanced_camera_card_action: status_bar
```

Trigger-only leaves are removed from retained `conditions:` blocks
because they no longer describe an ongoing state.

### `actions_not` to `if` / `then` / `else`

```yaml
# Before
automations:
  - conditions:
      - condition: state
        entity_id: input_boolean.camera_alerts
        state: 'on'
    actions:
      - action: custom:advanced-camera-card-action
        advanced_camera_card_action: live
    actions_not:
      - action: none
```

```yaml
# After, automatic
automations:
  - triggers:
      - trigger: state
        entity_id: input_boolean.camera_alerts
    actions:
      - if:
          - condition: state
            entity_id: input_boolean.camera_alerts
            state: 'on'
        then:
          - action: custom:advanced-camera-card-action
            advanced_camera_card_action: live
        else:
          - action: none
```

If the legacy automation had no conditions, or only trigger-only
conditions, `actions_not` is dropped because the old `else` branch could
not be reproduced as an ongoing predicate.

### Trigger template paths

```yaml
# Before
message: 'Door is {{ acc.trigger.state.to }} from {{ acc.trigger.state.from }}'
```

```yaml
# After, automatic
message: 'Door is {{ trigger.to_state.state }} from {{ trigger.from_state.state }}'
```

Path rewrites performed automatically:

| Old path                   | New path                   |
| -------------------------- | -------------------------- |
| `acc.trigger.state.entity` | `trigger.entity_id`        |
| `acc.trigger.state.from`   | `trigger.from_state.state` |
| `acc.trigger.state.to`     | `trigger.to_state.state`   |
| `acc.trigger.camera.from`  | `trigger.from_acc.camera`  |
| `acc.trigger.camera.to`    | `trigger.to_acc.camera`    |
| `acc.trigger.view.from`    | `trigger.from_acc.view`    |
| `acc.trigger.view.to`      | `trigger.to_acc.view`      |
| `acc.trigger.config.from`  | `trigger.from_acc.config`  |
| `acc.trigger.config.to`    | `trigger.to_acc.config`    |

The same rewrites are applied for the older
`advanced_camera_card.trigger.*` namespace.

### Ambient template namespace

Any remaining long-form ambient `advanced_camera_card.*` references
(outside the trigger surface) are rewritten to the `acc.*` alias:

```yaml
# Before
title: 'Now viewing {{ advanced_camera_card.camera }}'
```

```yaml
# After, automatic
title: 'Now viewing {{ acc.camera }}'
```

## Manual Migration Cases

### `__UPGRADE_FAILURE__.automations`

If a legacy automation cannot be converted faithfully, the original
automation is recorded under:

```yaml
__UPGRADE_FAILURE__:
  automations:
    - ...
```

These entries require manual migration.

The main known case is legacy `actions_not` with a condition whose
trigger can only fire on a rising edge, such as:

- `condition: template`
- `condition: screen`
- `condition: numeric_state` without an entity-backed state to watch

Those conditions can start the `then` branch, but cannot reliably start
the `else` branch when they stop matching.

### Unsupported HA conditions and triggers

This PR aligns the card with HA where supported, but it is not a full HA
automation engine.

Unsupported HA condition families include:

- `time`
- `zone`
- `sun`
- `location`
- `device`
- `condition: trigger`

Unsupported HA trigger platforms include:

- `event`
- `time`
- `time_pattern`
- `sun`
- `zone`
- `calendar`
- `webhook`
- `tag`
- `device`
- `mqtt`

The card-specific camera `triggers:` feature (which auto-selects and
wakes the card on camera events such as motion) is a separate feature
from automation `triggers:`, despite the shared word.

### Trigger IDs and variables

HA keys such as `id`, `alias`, and `variables` are accepted so pasted HA
YAML validates, but they are ignored by the card. There is no
`trigger.id` support in this PR.

## New Compatibility Features

This PR also makes card config more forgiving for HA-style YAML:

- `trigger`, `condition`, and `action` singular keys are accepted and
normalized to `triggers`, `conditions`, and `actions`.
- Single trigger, condition, and action objects are accepted where lists
are expected.
- `if`, `then`, and `else` accept a single item or a list.
- Composite condition shorthand is accepted:
  - `{ and: [...] }`
  - `{ or: [...] }`
  - `{ not: [...] }`
  - `{ condition: [...] }` as an implicit AND
- State conditions resolve expected state values that name another
entity, matching HA/Lovelace behavior.
- Both `entity` and `entity_id` are accepted on state and numeric
conditions and triggers (a superset of HA's two dialects), so there is
no forced rename.
- `state_not` remains supported as a card/Lovelace-friendly extension.

## Trigger Payloads

Automation action templates receive a top-level `trigger` object.

For stock `state` and `numeric_state` triggers:

```yaml
trigger.platform
trigger.entity_id
trigger.entity
trigger.from_state
trigger.to_state
```

For template triggers:

```yaml
trigger.platform
```

For card-specific triggers:

```yaml
trigger.platform # "acc"
trigger.type
trigger.from_acc
trigger.to_acc
```

The card does not currently expose HA's `id`, `idx`, `for`, `attribute`,
`above`, `below`, or `alias` trigger fields.

BREAKING CHANGE: Automations now follow Home Assistant's `triggers:` /
`conditions:` / `actions:` model. Automations require a `triggers:`
block and `conditions:` no longer wake an automation; `actions_not` is
removed in favour of an `if` / `then` / `else` action; the nested
`acc.trigger.*` template paths and the ambient `advanced_camera_card`
template namespace are removed (use the top-level `trigger.*` surface
and the `acc` alias); trigger-only condition forms (`config`, valueless
`camera` / `view` / `state`) are no longer valid conditions; and
template-condition vs template-trigger truthiness now follow HA.
Existing configs are upgraded automatically where a faithful conversion
exists; anything that cannot be converted is recorded under
`__UPGRADE_FAILURE__` for manual migration.

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 17:45:13 -07:00

364 lines
12 KiB
TypeScript

import { add, sub } from 'date-fns';
import { DataSet } from 'vis-data';
import { IdType, TimelineItem, TimelineWindow } from 'vis-timeline/esnext';
import { CameraManager } from '../../camera-manager/manager';
import {
compressRanges,
ExpiringMemoryRangeSet,
MemoryRangeSet,
} from '../../camera-manager/range';
import { RecordingSegment } from '../../camera-manager/types';
import { capEndDate } from '../../camera-manager/utils/cap-end-date';
import { convertRangeToCacheFriendlyTimes } from '../../camera-manager/utils/range-to-cache-friendly';
import { FoldersManager } from '../../card-controller/folders/manager';
import { ConditionStateManagerReadonlyInterface } from '../../condition-trigger/conditions/types';
import { FolderConfig } from '../../config/schema/folders';
import { errorToConsole } from '../../utils/basic.js';
import { ViewItem, ViewMedia } from '../../view/item';
import { ViewItemClassifier } from '../../view/item-classifier';
import { UnifiedQuery } from '../../view/unified-query';
import { UnifiedQueryBuilder } from '../../view/unified-query-builder';
import { UnifiedQueryRunner } from '../../view/unified-query-runner';
import { UnifiedQueryTransformer } from '../../view/unified-query-transformer';
// Allow timeline freshness to be at least this number of seconds out of date
// (caching times in the data-engine may increase the effective delay).
const TIMELINE_FRESHNESS_TOLERANCE_SECONDS = 30;
// Number of seconds gap allowable in order to consider two recording segments
// to be consecutive. Some low performance cameras have trouble and without a
// generous allowance here the timeline may be littered with individual segments
// instead of clean recording blocks.
const TIMELINE_RECORDING_SEGMENT_CONSECUTIVE_TOLERANCE_SECONDS = 60;
export type AdvancedCameraCardTimelineItem = TimelineItem & {
// Use numbers to avoid significant volumes of Date object construction (for
// high-quantity recording segments).
start: number;
end?: number;
// DataSet requires string (not HTMLElement) content.
content: string;
// Severity is duplicated here (also available via media.getSeverity())
// because vis-timeline's dataAttributes option requires properties to exist
// directly on the item object to render them as data-* HTML attributes for
// CSS styling.
severity?: string;
} & ( // Ensure that if there's a media item there is a query it is associated with.
| {
media: ViewMedia;
query: UnifiedQuery;
}
| {
media?: never;
query?: never;
}
);
interface AdvancedCameraCardGroup {
id: string;
content: string;
}
export class TimelineDataSource {
private _cameraManager: CameraManager;
private _builder: UnifiedQueryBuilder;
private _runner: UnifiedQueryRunner;
private _dataset: DataSet<AdvancedCameraCardTimelineItem> = new DataSet();
private _groups: DataSet<AdvancedCameraCardGroup>;
// The ranges in which recordings have been calculated and added for.
// Calculating recordings is a very expensive process since it is based on
// segments (not just the fetch is expensive, but the JS to dedup and turn the
// high-N segments into a smaller number of consecutive recording blocks).
private _recordingRanges = new MemoryRangeSet();
// Cache for all query results in this source instance.
// Uses a single range set since shape determines content type.
private _cache = new ExpiringMemoryRangeSet();
private _showRecordings: boolean;
// The "shape" of the query, a UnifiedQuery without time ranges. Determines
// the groups/structure of the timeline.
private _shape: UnifiedQuery;
constructor(
cameraManager: CameraManager,
foldersManager: FoldersManager,
conditionStateManager: ConditionStateManagerReadonlyInterface,
shape: UnifiedQuery,
showRecordings: boolean,
) {
this._cameraManager = cameraManager;
this._builder = new UnifiedQueryBuilder(cameraManager, foldersManager);
this._runner = new UnifiedQueryRunner(
cameraManager,
foldersManager,
conditionStateManager,
);
this._shape = shape;
this._showRecordings = showRecordings;
this._groups = this._generateGroups();
}
get dataset(): DataSet<AdvancedCameraCardTimelineItem> {
return this._dataset;
}
get groups(): DataSet<AdvancedCameraCardGroup> {
return this._groups;
}
get shape(): UnifiedQuery {
return this._shape;
}
public areResultsFresh(resultsTimestamp: Date, query: UnifiedQuery): boolean {
return this._runner.areResultsFresh(resultsTimestamp, query);
}
private _getGroupIDForCamera(cameraID: string): string {
return `camera/${cameraID}`;
}
private _getGroupIDForFolder(folderConfig: FolderConfig): string {
return `folder/${folderConfig.id}`;
}
private _generateGroups(): DataSet<AdvancedCameraCardGroup> {
const groups: AdvancedCameraCardGroup[] = [];
// Add folder-based groups
const folderQueries = this._shape.getFolderQueries();
for (const folderQuery of folderQueries) {
const folderID = this._getGroupIDForFolder(folderQuery.folder);
groups.push({
id: folderID,
content: folderQuery.folder.title ?? folderID,
});
}
// Add camera-based groups
const cameraIDs = this._shape.getAllCameraIDs();
cameraIDs.forEach((cameraID) => {
const cameraMetadata = this._cameraManager.getCameraMetadata(cameraID);
groups.push({
id: this._getGroupIDForCamera(cameraID),
content: cameraMetadata?.title ?? cameraID,
});
});
return new DataSet(groups);
}
public rewriteEvent(id: IdType): void {
// Hack: For timeline uses of the event dataset clustering may not update
// unless the dataset changes, artifically update the dataset to ensure the
// newly selected item cannot be included in a cluster.
// Hack2: Cannot use `updateOnly` here, as vis-data loses the object
// prototype, see: https://github.com/visjs/vis-data/issues/997 . Instead,
// remove then add.
const item = this._dataset.get(id);
if (item) {
this._dataset.remove(id);
this._dataset.add(item);
}
}
public addMediaToDataset(query: UnifiedQuery, mediaArray?: ViewItem[] | null): void {
const data: AdvancedCameraCardTimelineItem[] = [];
for (const media of mediaArray ?? []) {
if (!ViewItemClassifier.isEvent(media) && !ViewItemClassifier.isReview(media)) {
continue;
}
const startTime = media.getStartTime();
const id = media.getID();
const folder = media.getFolder();
const cameraID = media.getCameraID();
const groupID = folder
? this._getGroupIDForFolder(folder)
: cameraID
? this._getGroupIDForCamera(cameraID)
: null;
if (id && startTime && groupID) {
data.push({
id: id,
group: groupID,
content: '',
media: media,
start: startTime.getTime(),
type: 'range',
end: media.getUsableEndTime()?.getTime(),
...(ViewItemClassifier.isReview(media) && {
severity: media.getSeverity() ?? undefined,
}),
query,
});
}
}
this._dataset.update(data);
}
public buildRecordingsWindowedQuery(window: TimelineWindow): UnifiedQuery | null {
return this._builder.buildRecordingsQuery(this._shape.getAllCameraIDs(), {
start: window.start,
end: window.end,
});
}
private async _refreshQuery(window: TimelineWindow): Promise<void> {
const cacheFriendlyWindow = convertRangeToCacheFriendlyTimes(window);
if (
this._cache.hasCoverage({
start: cacheFriendlyWindow.start,
end: sub(capEndDate(cacheFriendlyWindow.end), {
seconds: TIMELINE_FRESHNESS_TOLERANCE_SECONDS,
}),
})
) {
return;
}
const query = UnifiedQueryTransformer.rebuildQuery(this._shape, {
start: cacheFriendlyWindow.start,
end: cacheFriendlyWindow.end,
});
this.addMediaToDataset(query, await this._runner.execute(query));
this._cache.add({
...cacheFriendlyWindow,
expires: add(new Date(), { seconds: TIMELINE_FRESHNESS_TOLERANCE_SECONDS }),
});
}
public async refresh(window: TimelineWindow): Promise<void> {
try {
await Promise.all([
this._refreshQuery(window),
...(this._showRecordings ? [this._refreshRecordings(window)] : []),
]);
} catch (e) {
errorToConsole(e as Error);
}
}
private async _refreshRecordings(window: TimelineWindow): Promise<void> {
// Recordings only apply to camera-based shapes
const cameraIDs = this._shape.getAllCameraIDs();
if (!cameraIDs?.size) {
return;
}
type AdvancedCameraCardTimelineItemWithEnd = AdvancedCameraCardTimelineItem & {
end: number;
};
const convertSegmentToRecording = (
cameraID: string,
segment: RecordingSegment,
): AdvancedCameraCardTimelineItemWithEnd => {
return {
id: `recording-${cameraID}-${segment.id}`,
group: this._getGroupIDForCamera(cameraID),
start: segment.start_time * 1000,
end: segment.end_time * 1000,
content: '',
type: 'background',
};
};
const getExistingRecordingsForCameraID = (
cameraID: string,
): AdvancedCameraCardTimelineItemWithEnd[] => {
const groupID = this._getGroupIDForCamera(cameraID);
return this._dataset.get({
filter: (item) =>
item.type === 'background' && item.group === groupID && item.end !== undefined,
}) as AdvancedCameraCardTimelineItemWithEnd[];
};
const deleteRecordingsForCameraID = (cameraID: string): void => {
const groupID = this._getGroupIDForCamera(cameraID);
this._dataset.remove(
this._dataset.get({
filter: (item) => item.type === 'background' && item.group === groupID,
}),
);
};
const addRecordings = (
recordings: AdvancedCameraCardTimelineItemWithEnd[],
): void => {
this._dataset.add(recordings);
};
// Calculate an end date that's slightly short of the current time to allow
// for caching up to the freshness tolerance.
if (
this._recordingRanges.hasCoverage({
start: window.start,
end: sub(capEndDate(window.end), {
seconds: TIMELINE_FRESHNESS_TOLERANCE_SECONDS,
}),
})
) {
return;
}
const cacheFriendlyWindow = convertRangeToCacheFriendlyTimes(window);
const recordingQueries = this._cameraManager.generateDefaultRecordingSegmentsQueries(
cameraIDs,
{
start: cacheFriendlyWindow.start,
end: cacheFriendlyWindow.end,
},
);
if (!recordingQueries) {
return;
}
const results = await this._cameraManager.getRecordingSegments(recordingQueries);
const newSegments: Map<string, RecordingSegment[]> = new Map();
for (const [query, result] of results) {
for (const cameraID of query.cameraIDs) {
let destination: RecordingSegment[] | undefined = newSegments.get(cameraID);
if (!destination) {
destination = [];
newSegments.set(cameraID, destination);
}
result.segments.forEach((segment) => destination?.push(segment));
}
}
for (const [cameraID, segments] of newSegments.entries()) {
const existingRecordings = getExistingRecordingsForCameraID(cameraID);
const mergedRecordings = existingRecordings.concat(
segments.map((segment) => convertSegmentToRecording(cameraID, segment)),
);
const compressedRecordings = compressRanges(
mergedRecordings,
TIMELINE_RECORDING_SEGMENT_CONSECUTIVE_TOLERANCE_SECONDS,
) as AdvancedCameraCardTimelineItemWithEnd[];
deleteRecordingsForCameraID(cameraID);
addRecordings(compressedRecordings);
}
this._recordingRanges.add({
start: cacheFriendlyWindow.start,
end: cacheFriendlyWindow.end,
});
}
}