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>
This commit is contained in:
Dermot Duffy
2026-06-30 17:45:13 -07:00
committed by dermotduffy
co-authored by Claude Opus 4.8
parent 209c873c58
commit b701366762
354 changed files with 11386 additions and 3020 deletions
@@ -17,7 +17,10 @@ import {
import type { CardController } from '../../../src/card-controller/controller';
import { TemplateRenderer } from '../../../src/card-controller/templates';
import { AdvancedCameraCardView } from '../../../src/config/schema/common/const';
import { createGeneralAction, createLogAction } from '../../../src/utils/action';
import {
createInternalCallbackAction,
createLogAction,
} from '../../../src/utils/action';
import { arrayify } from '../../../src/utils/basic';
import { createCardAPI, createConfig, createHASS, createView } from '../../test-utils';
@@ -347,7 +350,12 @@ describe('ActionsManager', () => {
const manager = new ActionsManager(api, templateRenderer);
const config = { entity: 'light.office' };
const triggerData = { view: { from: 'previous-view', to: 'view' } };
const triggerData = {
platform: 'acc',
type: 'view',
from_acc: { view: 'previous-view' },
to_acc: { view: 'view' },
};
vi.spyOn(global.console, 'info').mockReturnValue(undefined);
await manager.executeActions({ actions: action, config, triggerData });
@@ -358,26 +366,233 @@ describe('ActionsManager', () => {
});
});
it('should filter rendered actions through the lock manager', async () => {
const renderedAction = createGeneralAction('reload');
const allowedAction = createLogAction('Allowed');
it('should filter actions through the lock manager before rendering them', async () => {
const rawRan = vi.fn();
const allowedRan = vi.fn();
const rawAction = createInternalCallbackAction(async () => {
rawRan();
});
const allowedAction = createInternalCallbackAction(async () => {
allowedRan();
});
const templateRenderer = mock<TemplateRenderer>();
templateRenderer.renderRecursively.mockReturnValue(renderedAction);
templateRenderer.renderRecursively.mockReturnValue(allowedAction);
const api = createAPI();
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
vi.mocked(api.getLockManager().getAllowedActions).mockReturnValue([allowedAction]);
const manager = new ActionsManager(api, templateRenderer);
await manager.executeActions({ actions: rawAction });
// The lock manager sees the raw (unrendered) action; only the action it
// returns is rendered and run.
expect(api.getLockManager().getAllowedActions).toBeCalledWith(rawAction);
expect(allowedRan).toBeCalled();
expect(rawRan).not.toBeCalled();
});
it('should render each action against the state at its turn', async () => {
let camera = 'first';
const templateRenderer = mock<TemplateRenderer>();
// Identity render -- assert on the render *inputs*, not a swapped output.
templateRenderer.renderRecursively.mockImplementation((_hass, data) => data);
const api = createAPI();
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
vi.mocked(api.getConditionStateManager().getState).mockImplementation(() => ({
camera,
}));
const manager = new ActionsManager(api, templateRenderer);
await manager.executeActions({
actions: [
// The first action changes the camera...
createInternalCallbackAction(async () => {
camera = 'second';
}),
// ...the second is rendered afterwards.
{ action: 'none' },
],
});
// Each action renders with the state as it is at its turn: the second
// sees the camera the first action set.
expect(templateRenderer.renderRecursively).toHaveBeenNthCalledWith(
1,
expect.anything(),
expect.anything(),
expect.objectContaining({ conditionState: { camera: 'first' } }),
);
expect(templateRenderer.renderRecursively).toHaveBeenNthCalledWith(
2,
expect.anything(),
expect.anything(),
expect.objectContaining({ conditionState: { camera: 'second' } }),
);
});
it('should render against the hass available at each step', async () => {
const ran: string[] = [];
const templateRenderer = mock<TemplateRenderer>();
templateRenderer.renderRecursively.mockImplementation((_hass, data) => data);
const api = createAPI();
// No HASS for the first action's render; HASS thereafter.
vi.mocked(api.getHASSManager().getHASS)
.mockReturnValueOnce(null)
.mockReturnValue(createHASS());
const manager = new ActionsManager(api, templateRenderer);
await manager.executeActions({
actions: [
createInternalCallbackAction(async () => {
ran.push('one');
}),
createInternalCallbackAction(async () => {
ran.push('two');
}),
],
});
// Both actions ran; only the second was rendered -- the first saw no
// HASS, so HASS is read per action rather than captured once.
expect(ran).toEqual(['one', 'two']);
expect(templateRenderer.renderRecursively).toBeCalledTimes(1);
});
it('should abort the remaining actions when one fails to render', async () => {
const ran: string[] = [];
const templateRenderer = mock<TemplateRenderer>();
templateRenderer.renderRecursively
.mockImplementationOnce((_hass, data) => data)
.mockImplementationOnce(() => {
throw new Error('bad template');
});
const api = createAPI();
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
const manager = new ActionsManager(api, templateRenderer);
const warnSpy = vi.spyOn(global.console, 'warn').mockReturnValue(undefined);
await manager.executeActions({
actions: [
createInternalCallbackAction(async () => {
ran.push('first');
}),
createInternalCallbackAction(async () => {
ran.push('second');
}),
createInternalCallbackAction(async () => {
ran.push('third');
}),
],
});
// The first action ran; the second's render threw, aborting the rest. The
// error was caught by executeActions().
expect(ran).toEqual(['first']);
expect(warnSpy).toBeCalled();
});
it('should hand an if-action branch to the executor unrendered, with the trigger data', async () => {
const api = createAPI();
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({
fullscreen: true,
});
const manager = new ActionsManager(api, new TemplateRenderer());
const consoleSpy = vi.spyOn(global.console, 'info').mockReturnValue(undefined);
const thenAction = createLogAction('{{ trigger.entity_id }}');
await manager.executeActions({
actions: {
if: [{ condition: 'fullscreen', fullscreen: true }],
then: [thenAction],
else: [createLogAction('unused else')],
},
triggerData: { platform: 'state', entity_id: 'binary_sensor.door' },
});
// The branch is left raw (template intact) and forwarded with the trigger
// data, so the nested executor renders it per-step when it runs -- not
// frozen against the state at the `if` step.
expect(api.getActionsManager().executeActions).toBeCalledWith({
actions: [thenAction],
config: undefined,
triggerData: { platform: 'state', entity_id: 'binary_sensor.door' },
});
// The log action is handed to the (mocked) nested executor, not run here,
// so it must not actually log.
expect(consoleSpy).not.toBeCalled();
});
it('should render if-action branch actions per-step', async () => {
let camera = 'before';
const api = createAPI();
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
vi.mocked(api.getConditionStateManager().getState).mockImplementation(() => ({
camera,
fullscreen: true,
}));
const manager = new ActionsManager(api, new TemplateRenderer());
// The if-action's nested executor is the same (real) manager.
vi.mocked(api.getActionsManager).mockReturnValue(manager);
const consoleSpy = vi.spyOn(global.console, 'info').mockReturnValue(undefined);
await manager.executeActions({
actions: createLogAction('{{ action }}'),
actions: {
if: [{ condition: 'fullscreen', fullscreen: true }],
then: [
// The first branch action changes the camera...
createInternalCallbackAction(async () => {
camera = 'after';
}),
// ...the second logs `{{ acc.camera }}`, rendered at its own turn.
createLogAction('{{ acc.camera }}'),
],
},
});
expect(api.getLockManager().getAllowedActions).toBeCalledWith(renderedAction);
expect(consoleSpy).toBeCalledWith('Allowed');
// The log rendered against the camera the first branch action set, so it
// logs 'after' -- proving the branch renders per-step. Frozen-at-the-`if`
// rendering would log 'before'.
expect(consoleSpy).toHaveBeenCalledWith('after');
});
it('should drop an action whose templated discriminator cannot be classified', async () => {
const api = createAPI();
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
const manager = new ActionsManager(api, new TemplateRenderer());
const warnSpy = vi.spyOn(global.console, 'warn').mockReturnValue(undefined);
await manager.executeActions({
actions: {
action: 'fire-dom-event',
advanced_camera_card_action: '{{ acc.view }}',
},
});
// The discriminator is classified on the raw action (templates render
// only afterwards), so a templated `advanced_camera_card_action` matches
// no action type and is dropped with a warning rather than executed.
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('unknown card action'),
);
});
it('should not execute actions when the lock manager rejects them', async () => {
@@ -123,9 +123,9 @@ describe('should handle camera_select action', () => {
it('with triggered camera', async () => {
const api = createCardAPI();
vi.mocked(api.getViewManager().getView).mockReturnValue(createView());
vi.mocked(api.getTriggersManager().getMostRecentlyTriggeredCameraID).mockReturnValue(
'camera.office',
);
vi.mocked(
api.getCameraTriggersManager().getMostRecentlyTriggeredCameraID,
).mockReturnValue('camera.office');
const action = new CameraSelectAction(
{},
@@ -152,9 +152,9 @@ describe('should handle camera_select action', () => {
it('without camera or triggered camera', async () => {
const api = createCardAPI();
vi.mocked(api.getViewManager().getView).mockReturnValue(createView());
vi.mocked(api.getTriggersManager().getMostRecentlyTriggeredCameraID).mockReturnValue(
'camera.office',
);
vi.mocked(
api.getCameraTriggersManager().getMostRecentlyTriggeredCameraID,
).mockReturnValue('camera.office');
const action = new CameraSelectAction(
{},
@@ -0,0 +1,86 @@
import { describe, expect, it, vi } from 'vitest';
import { IfAction } from '../../../../src/card-controller/actions/actions/if';
import { ConditionStateManager } from '../../../../src/condition-trigger/conditions/state-manager';
import { createCardAPI } from '../../../test-utils';
const thenActions = [
{
action: 'fire-dom-event' as const,
advanced_camera_card_action: 'clips' as const,
},
];
const elseActions = [
{
action: 'fire-dom-event' as const,
advanced_camera_card_action: 'clip' as const,
},
];
describe('IfAction', () => {
it('should run the then branch when the conditions hold', async () => {
const api = createCardAPI();
const stateManager = new ConditionStateManager();
stateManager.setState({ fullscreen: true });
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const action = new IfAction(
{},
{
if: [{ condition: 'fullscreen', fullscreen: true }],
then: thenActions,
else: elseActions,
},
);
await action.execute(api);
expect(api.getActionsManager().executeActions).toBeCalledWith({
actions: thenActions,
config: undefined,
triggerData: undefined,
});
});
it('should run the else branch when the conditions do not hold', async () => {
const api = createCardAPI();
const stateManager = new ConditionStateManager();
stateManager.setState({ fullscreen: false });
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const action = new IfAction(
{},
{
if: [{ condition: 'fullscreen', fullscreen: true }],
then: thenActions,
else: elseActions,
},
);
await action.execute(api);
expect(api.getActionsManager().executeActions).toBeCalledWith({
actions: elseActions,
config: undefined,
triggerData: undefined,
});
});
it('should do nothing when the conditions do not hold and there is no else branch', async () => {
const api = createCardAPI();
const stateManager = new ConditionStateManager();
stateManager.setState({ fullscreen: false });
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const action = new IfAction(
{},
{
if: [{ condition: 'fullscreen', fullscreen: true }],
then: thenActions,
},
);
await action.execute(api);
expect(api.getActionsManager().executeActions).not.toBeCalled();
});
});
@@ -12,6 +12,7 @@ import { DownloadAction } from '../../../src/card-controller/actions/actions/dow
import { EffectAction } from '../../../src/card-controller/actions/actions/effect';
import { ExpandAction } from '../../../src/card-controller/actions/actions/expand';
import { FullscreenAction } from '../../../src/card-controller/actions/actions/fullscreen';
import { IfAction } from '../../../src/card-controller/actions/actions/if';
import { InfoAction } from '../../../src/card-controller/actions/actions/info';
import { InternalCallbackAction } from '../../../src/card-controller/actions/actions/internal-callback';
import { LogAction } from '../../../src/card-controller/actions/actions/log';
@@ -87,6 +88,11 @@ describe('ActionFactory', () => {
});
});
it('should create an if action', () => {
const factory = new ActionFactory();
expect(factory.createAction({}, { if: [], then: [] })).toBeInstanceOf(IfAction);
});
describe('custom actions', () => {
it.each([
[{ advanced_camera_card_action: 'call_answer' as const }, CallAnswerAction],
+122 -30
View File
@@ -1,8 +1,8 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { ActionsExecutionRequest } from '../../src/card-controller/actions/types.js';
import { AutomationsManager } from '../../src/card-controller/automations-manager.js';
import { ConditionStateManager } from '../../src/conditions/state-manager.js';
import { createCardAPI } from '../test-utils.js';
import { ConditionStateManager } from '../../src/condition-trigger/conditions/state-manager.js';
import { createCardAPI, flushPromises } from '../test-utils.js';
describe('AutomationsManager', () => {
const actions = [
@@ -11,15 +11,11 @@ describe('AutomationsManager', () => {
advanced_camera_card_action: 'clips',
},
];
const conditions = [{ condition: 'fullscreen' as const, fullscreen: true }];
const triggers = [{ trigger: 'fullscreen' as const, fullscreen: true }];
const automation = {
conditions: conditions,
triggers: triggers,
actions: actions,
};
const not_automation = {
conditions: conditions,
actions_not: actions,
};
afterEach(() => {
vi.clearAllMocks();
@@ -78,7 +74,7 @@ describe('AutomationsManager', () => {
});
});
it('should execute actions', () => {
it('should execute actions when triggered', () => {
const api = createCardAPI();
vi.mocked(api.getHASSManager().hasHASS).mockReturnValue(true);
vi.mocked(api.getInitializationManager().isInitializedMandatory).mockReturnValue(
@@ -94,8 +90,7 @@ describe('AutomationsManager', () => {
expect(api.getActionsManager().executeActions).toBeCalledTimes(1);
// Automation will not re-fire when condition continues to evaluate the
// same.
// It does not re-trigger while its source stays in the same state.
stateManager.setState({ fullscreen: true });
expect(api.getActionsManager().executeActions).toBeCalledTimes(1);
@@ -106,7 +101,7 @@ describe('AutomationsManager', () => {
expect(api.getActionsManager().executeActions).toBeCalledTimes(2);
});
it('should execute actions_not', () => {
it('should run actions when the ongoing conditions hold', () => {
const api = createCardAPI();
vi.mocked(api.getHASSManager().hasHASS).mockReturnValue(true);
vi.mocked(api.getInitializationManager().isInitializedMandatory).mockReturnValue(
@@ -116,13 +111,69 @@ describe('AutomationsManager', () => {
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const automationsManager = new AutomationsManager(api);
automationsManager.addAutomations([not_automation]);
automationsManager.addAutomations([
{
triggers: triggers,
conditions: [{ condition: 'expand' as const, expand: true }],
actions: actions,
},
]);
// The ongoing condition holds when triggered, so `actions` run.
stateManager.setState({ expand: true });
stateManager.setState({ fullscreen: true });
expect(api.getActionsManager().executeActions).toBeCalledWith({
actions: actions,
triggerData: { platform: 'acc', type: 'fullscreen' },
});
});
it('should do nothing when the ongoing conditions do not hold', () => {
const api = createCardAPI();
vi.mocked(api.getHASSManager().hasHASS).mockReturnValue(true);
vi.mocked(api.getInitializationManager().isInitializedMandatory).mockReturnValue(
true,
);
const stateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const automationsManager = new AutomationsManager(api);
automationsManager.addAutomations([
{
triggers: triggers,
conditions: [{ condition: 'expand' as const, expand: true }],
actions: actions,
},
]);
// The automation is triggered but the ongoing condition does not hold, so
// nothing runs.
stateManager.setState({ fullscreen: true });
expect(api.getActionsManager().executeActions).not.toBeCalled();
});
it('should do nothing when the actions are empty', () => {
const api = createCardAPI();
vi.mocked(api.getHASSManager().hasHASS).mockReturnValue(true);
vi.mocked(api.getInitializationManager().isInitializedMandatory).mockReturnValue(
true,
);
const stateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const automationsManager = new AutomationsManager(api);
automationsManager.addAutomations([
{
triggers: triggers,
actions: [],
},
]);
stateManager.setState({ fullscreen: true });
expect(api.getActionsManager().executeActions).not.toBeCalled();
stateManager.setState({ fullscreen: false });
expect(api.getActionsManager().executeActions).toBeCalled();
expect(api.getActionsManager().executeActions).not.toBeCalled();
});
it('should prevent automation loops', () => {
@@ -137,29 +188,27 @@ describe('AutomationsManager', () => {
const automationsManager = new AutomationsManager(api);
automationsManager.addAutomations([
{
conditions: [{ condition: 'fullscreen' as const, fullscreen: true }],
triggers: [{ trigger: 'camera' as const }],
actions: actions,
},
{
conditions: [{ condition: 'fullscreen' as const, fullscreen: false }],
actions_not: actions,
},
]);
// Create a setup where one automation action causes another...
let fullscreen = true;
// Create a setup where the automation's action re-triggers itself: the camera
// trigger responds to every camera change, and the action changes the camera,
// looping until the nested-execution guard trips.
let camera = 'one';
vi.mocked(api.getActionsManager().executeActions).mockImplementation(
async (
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_request: ActionsExecutionRequest,
): Promise<void> => {
fullscreen = !fullscreen;
stateManager.setState({ fullscreen: fullscreen });
camera = camera === 'one' ? 'two' : 'one';
stateManager.setState({ camera: camera });
},
);
stateManager.setState({ fullscreen: fullscreen });
stateManager.setState({ camera: camera });
expect(api.getNotificationManager().setNotification).toBeCalledWith({
heading: {
@@ -172,6 +221,49 @@ describe('AutomationsManager', () => {
expect(api.getActionsManager().executeActions).toBeCalledTimes(10);
});
it('should reset the nested-execution counter after an overflow', async () => {
const api = createCardAPI();
vi.mocked(api.getHASSManager().hasHASS).mockReturnValue(true);
vi.mocked(api.getInitializationManager().isInitializedMandatory).mockReturnValue(
true,
);
const stateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const automationsManager = new AutomationsManager(api);
automationsManager.addAutomations([
{
triggers: [{ trigger: 'camera' as const }],
actions: actions,
},
]);
// As in the loop test: the action changes the camera, re-triggering itself
// until the nested-execution guard trips.
let camera = 'one';
vi.mocked(api.getActionsManager().executeActions).mockImplementation(
async (): Promise<void> => {
camera = camera === 'one' ? 'two' : 'one';
stateManager.setState({ camera: camera });
},
);
stateManager.setState({ camera: camera });
expect(api.getActionsManager().executeActions).toBeCalledTimes(10);
// The counter is decremented on the microtasks that resume after each
// awaited execution, so let them drain before the next batch.
await flushPromises();
vi.mocked(api.getActionsManager().executeActions).mockClear();
// A second, independent change overflows afresh and reaches the full limit
// again -- only possible if the counter returned to zero. A leaked counter
// (overflow returning without decrementing) would cut this batch short.
stateManager.setState({ camera: 'three' });
expect(api.getActionsManager().executeActions).toBeCalledTimes(10);
});
it('should delete automations', () => {
const api = createCardAPI();
vi.mocked(api.getHASSManager().hasHASS).mockReturnValue(true);
@@ -184,11 +276,11 @@ describe('AutomationsManager', () => {
const automationsManager = new AutomationsManager(api);
automationsManager.addAutomations([
{
conditions: [{ condition: 'expand' as const, expand: true }],
triggers: [{ trigger: 'expand' as const, expand: true }],
actions: actions,
},
{
conditions: [{ condition: 'fullscreen' as const, fullscreen: true }],
triggers: [{ trigger: 'fullscreen' as const, fullscreen: true }],
actions: actions,
tag: 'fullscreen',
},
@@ -210,8 +302,8 @@ describe('AutomationsManager', () => {
// Delete all automations.
automationsManager.deleteAutomations();
stateManager.setState({ fullscreen: false });
stateManager.setState({ fullscreen: true });
stateManager.setState({ expand: false });
stateManager.setState({ expand: true });
expect(api.getActionsManager().executeActions).toBeCalledTimes(2);
});
});
+1 -1
View File
@@ -8,7 +8,7 @@ import { CallManager } from '../../../src/card-controller/call/manager';
import { Ringtone } from '../../../src/card-controller/call/ringtone';
import { CardController } from '../../../src/card-controller/controller';
import { SubstreamViewModifier } from '../../../src/card-controller/view/modifiers/substream';
import { ConditionStateChange } from '../../../src/conditions/types';
import { ConditionStateChange } from '../../../src/condition-trigger/conditions/types';
import { RingtoneConfig } from '../../../src/config/schema/live';
import { AdvancedCameraCardConfig } from '../../../src/config/schema/types';
import { View } from '../../../src/view/view';
@@ -2,7 +2,7 @@ import { add } from 'date-fns';
import { PartialDeep } from 'type-fest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { CardController } from '../../src/card-controller/controller';
import { TriggersManager } from '../../src/card-controller/triggers-manager';
import { CameraTriggersManager } from '../../src/card-controller/camera-triggers-manager';
import { AdvancedCameraCardView } from '../../src/config/schema/common/const';
import { TriggersOptions, triggersSchema } from '../../src/config/schema/view';
import {
@@ -85,7 +85,7 @@ const createTriggerAPI = (options?: {
};
// @vitest-environment jsdom
describe('TriggersManager', () => {
describe('CameraTriggersManager', () => {
const start = new Date('2023-10-01T17:14');
beforeEach(() => {
@@ -94,7 +94,7 @@ describe('TriggersManager', () => {
});
it('should not be triggered by default', () => {
const manager = new TriggersManager(createCardAPI());
const manager = new CameraTriggersManager(createCardAPI());
expect(manager.isTriggered()).toBeFalsy();
});
@@ -106,7 +106,7 @@ describe('TriggersManager', () => {
},
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -122,7 +122,7 @@ describe('TriggersManager', () => {
const api = createTriggerAPI();
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(null);
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -145,7 +145,7 @@ describe('TriggersManager', () => {
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -170,7 +170,7 @@ describe('TriggersManager', () => {
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -197,7 +197,7 @@ describe('TriggersManager', () => {
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -240,7 +240,7 @@ describe('TriggersManager', () => {
},
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -280,7 +280,7 @@ describe('TriggersManager', () => {
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -300,7 +300,7 @@ describe('TriggersManager', () => {
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -327,7 +327,7 @@ describe('TriggersManager', () => {
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -356,7 +356,7 @@ describe('TriggersManager', () => {
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
id: 'event-1',
@@ -390,7 +390,7 @@ describe('TriggersManager', () => {
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
id: 'event-1',
@@ -418,7 +418,7 @@ describe('TriggersManager', () => {
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
id: 'event-1',
@@ -445,7 +445,7 @@ describe('TriggersManager', () => {
it('should handle untrigger call with no state', async () => {
const api = createTriggerAPI();
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -458,7 +458,7 @@ describe('TriggersManager', () => {
it('should not untrigger if other sources are still active', async () => {
const api = createTriggerAPI();
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -501,7 +501,7 @@ describe('TriggersManager', () => {
it('should cancel untrigger timer if a new trigger starts', async () => {
const api = createTriggerAPI();
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -551,7 +551,7 @@ describe('TriggersManager', () => {
]),
);
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -604,7 +604,7 @@ describe('TriggersManager', () => {
untrigger_delay_seconds: 10,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// 1. Trigger the camera.
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'new' });
@@ -630,7 +630,7 @@ describe('TriggersManager', () => {
untrigger_delay_seconds: 10,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// Trigger then end to start the untrigger delay timer.
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'new' });
@@ -656,7 +656,7 @@ describe('TriggersManager', () => {
untrigger_force_seconds: 10,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// Trigger to start the force untrigger timer.
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'new' });
@@ -680,7 +680,7 @@ describe('TriggersManager', () => {
untrigger_delay_seconds: 0,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
id: 'event-1',
@@ -704,7 +704,7 @@ describe('TriggersManager', () => {
untrigger_force_seconds: 5,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -726,7 +726,7 @@ describe('TriggersManager', () => {
untrigger_force_seconds: 10,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -758,7 +758,7 @@ describe('TriggersManager', () => {
untrigger_force_seconds: 5,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -785,7 +785,7 @@ describe('TriggersManager', () => {
untrigger_force_seconds: 10,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -816,7 +816,7 @@ describe('TriggersManager', () => {
actions: { trigger: 'none', untrigger: 'default' },
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -842,7 +842,7 @@ describe('TriggersManager', () => {
actions: { trigger: 'none', untrigger: 'default' },
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -861,7 +861,7 @@ describe('TriggersManager', () => {
actions: { trigger: 'none', untrigger: 'default' },
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// Continuous source comes on first.
await manager.handleCameraEvent({
@@ -894,7 +894,7 @@ describe('TriggersManager', () => {
actions: { trigger: 'none', untrigger: 'default' },
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -924,7 +924,7 @@ describe('TriggersManager', () => {
actions: { trigger: 'none', untrigger: 'default' },
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -963,7 +963,7 @@ describe('TriggersManager', () => {
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -1007,7 +1007,7 @@ describe('TriggersManager', () => {
default: 'live',
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -1032,7 +1032,7 @@ describe('TriggersManager', () => {
default: 'clips',
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -1051,7 +1051,7 @@ describe('TriggersManager', () => {
// Interaction present.
interaction: true,
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
@@ -1089,7 +1089,7 @@ describe('TriggersManager', () => {
},
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
id: 'event-1',
@@ -1126,7 +1126,7 @@ describe('TriggersManager', () => {
},
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
id: 'event-1',
@@ -1179,7 +1179,7 @@ describe('TriggersManager', () => {
]),
);
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
expect(manager.isTriggered()).toBeFalsy();
expect(manager.getMostRecentlyTriggeredCameraID()).toBeNull();
@@ -1228,7 +1228,7 @@ describe('TriggersManager', () => {
filter_selected_camera: true,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
expect(manager.isTriggered()).toBeFalsy();
const otherCameraSelected = createView({
@@ -1288,7 +1288,7 @@ describe('TriggersManager', () => {
]),
);
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
const primaryCameraView = createView({
camera: 'camera_primary' as const,
@@ -1315,7 +1315,7 @@ describe('TriggersManager', () => {
actions: { trigger: 'none', untrigger: 'default' },
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// Trigger camera_1 normally, then end it -- starts the delay timer.
await manager.handleCameraEvent({
@@ -1372,7 +1372,7 @@ describe('TriggersManager', () => {
]),
);
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
const result = await manager.handleInitialCameraTriggers();
expect(result).toBeFalsy();
@@ -1404,7 +1404,7 @@ describe('TriggersManager', () => {
});
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
const result = await manager.handleInitialCameraTriggers();
expect(result).toBeFalsy();
@@ -1436,7 +1436,7 @@ describe('TriggersManager', () => {
});
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
const result = await manager.handleInitialCameraTriggers();
expect(result).toBeTruthy();
@@ -1468,7 +1468,7 @@ describe('TriggersManager', () => {
});
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
const result = await manager.handleInitialCameraTriggers();
expect(result).toBeTruthy();
@@ -1515,7 +1515,7 @@ describe('TriggersManager', () => {
});
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
const result = await manager.handleInitialCameraTriggers();
expect(result).toBeTruthy();
@@ -1555,7 +1555,7 @@ describe('TriggersManager', () => {
});
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
const result = await manager.handleInitialCameraTriggers();
// A trigger entity was active...
@@ -1580,7 +1580,7 @@ describe('TriggersManager', () => {
},
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({
cameraID: 'camera_1',
id: 'event-1',
@@ -1620,7 +1620,7 @@ describe('TriggersManager', () => {
},
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'new' });
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'end' });
@@ -1642,7 +1642,7 @@ describe('TriggersManager', () => {
untrigger_delay_seconds: 0,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// Trigger then end, but don't await the end event so we can check
// triggered IDs while the camera is in the map but no longer triggered.
@@ -1660,7 +1660,7 @@ describe('TriggersManager', () => {
it('should handle newly missing configuration', async () => {
const api = createTriggerAPI();
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// 1. Trigger the camera with valid config.
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'new' });
@@ -1688,7 +1688,7 @@ describe('TriggersManager', () => {
untrigger_force_seconds: 10,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// 1. Initial trigger.
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'new' });
@@ -1717,7 +1717,7 @@ describe('TriggersManager', () => {
untrigger_force_seconds: 10,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// 1. Trigger and force untrigger.
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'new' });
@@ -1747,7 +1747,7 @@ describe('TriggersManager', () => {
},
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// Simulate an update for a brand new ID (e.g. from an engine we just switched to).
// Even without a 'new' event, if it's not in our ignore list, it should be processed.
@@ -1768,7 +1768,7 @@ describe('TriggersManager', () => {
untrigger_force_seconds: 10,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// Force-ignore e1 on camera_1.
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'new' });
@@ -1794,7 +1794,7 @@ describe('TriggersManager', () => {
untrigger_force_seconds: 10,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// Force-ignore e1 and e2 on camera_1.
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'new' });
@@ -1825,7 +1825,7 @@ describe('TriggersManager', () => {
untrigger_delay_seconds: 0,
},
});
const manager = new TriggersManager(api);
const manager = new CameraTriggersManager(api);
// Call handleCameraEvent with an unknown camera ID to ensure guard behavior.
const result = await manager.handleCameraEvent({
@@ -5,9 +5,9 @@ import { ConfigManager } from '../../../src/card-controller/config/config-manage
import { setRemoteControlEntityFromConfig } from '../../../src/card-controller/config/load-control-entities';
import { setKeyboardShortcutsFromConfig } from '../../../src/card-controller/config/load-keyboard-shortcuts';
import { InitializationAspect } from '../../../src/card-controller/initialization-manager';
import { ConditionStateManager } from '../../../src/conditions/state-manager';
import { ConditionStateManager } from '../../../src/condition-trigger/conditions/state-manager';
import { Automation } from '../../../src/config/schema/automations';
import { AdvancedCameraCardCondition } from '../../../src/config/schema/conditions/types';
import { Trigger } from '../../../src/config/schema/condition-trigger/triggers/types';
import { advancedCameraCardConfigSchema } from '../../../src/config/schema/types';
import { createGeneralAction } from '../../../src/utils/action';
import { createCardAPI, createConfig, flushPromises } from '../../test-utils';
@@ -507,8 +507,8 @@ describe('ConfigManager', () => {
expect(addAutomationsSpy).toHaveBeenCalledWith(
expect.arrayContaining([
expect.objectContaining({
conditions: expect.arrayContaining([
expect.objectContaining({ condition: 'key', key: 'h' }),
triggers: expect.arrayContaining([
expect.objectContaining({ trigger: 'key', key: 'h' }),
]),
actions: expect.arrayContaining([
expect.objectContaining({
@@ -530,9 +530,8 @@ describe('ConfigManager', () => {
const addCalls = addAutomationsSpy.mock.calls;
const hasKeyboardShortcut = addCalls.some((call) =>
call[0].some((automation: Automation) =>
automation.conditions?.some(
(cond: AdvancedCameraCardCondition) =>
cond.condition === 'key' && cond.key === 'h',
automation.triggers.some(
(trig: Trigger) => trig.trigger === 'key' && trig.key === 'h',
),
),
);
@@ -610,7 +609,7 @@ describe('ConfigManager', () => {
);
const automation = {
conditions: [TEST_CONDITIONS.FULLSCREEN_OFF],
triggers: [{ trigger: 'fullscreen' as const, fullscreen: false }],
actions: [createGeneralAction('screenshot')],
};
const config = createConfig({
@@ -672,7 +671,7 @@ describe('ConfigManager', () => {
);
const automation = {
conditions: [TEST_CONDITIONS.FULLSCREEN_ON],
triggers: [{ trigger: 'fullscreen' as const, fullscreen: true }],
actions: [createGeneralAction('screenshot')],
};
const config = createConfig({
@@ -728,9 +727,9 @@ describe('ConfigManager', () => {
expect(addAutomationsSpy).toHaveBeenCalledWith(
expect.arrayContaining([
expect.objectContaining({
conditions: expect.arrayContaining([
triggers: expect.arrayContaining([
expect.objectContaining({
condition: 'config',
trigger: 'config',
paths: expect.arrayContaining(['remote_control.entities.camera']),
}),
]),
@@ -752,10 +751,10 @@ describe('ConfigManager', () => {
const addCalls = addAutomationsSpy.mock.calls;
const hasRemoteControl = addCalls.some((call) =>
call[0].some((automation: Automation) =>
automation.conditions?.some(
(cond: AdvancedCameraCardCondition) =>
cond.condition === 'config' &&
cond.paths?.includes('remote_control.entities.camera'),
automation.triggers.some(
(trig: Trigger) =>
trig.trigger === 'config' &&
trig.paths?.includes('remote_control.entities.camera'),
),
),
);
@@ -771,9 +770,9 @@ describe('ConfigManager', () => {
expect(addAutomationsSpy).toHaveBeenCalledWith(
expect.arrayContaining([
expect.objectContaining({
conditions: expect.arrayContaining([
triggers: expect.arrayContaining([
expect.objectContaining({
condition: 'config',
trigger: 'config',
paths: expect.arrayContaining(['remote_control.entities.camera']),
}),
]),
@@ -20,7 +20,7 @@ describe('setAutomationsFromConfig', () => {
advanced_camera_card_action: 'clips',
},
],
conditions: [{ condition: 'fullscreen' as const, fullscreen: true }],
triggers: [{ trigger: 'fullscreen' as const, fullscreen: true }],
},
];
const api = createCardAPI();
@@ -1,5 +1,8 @@
import { describe, expect, it, vi } from 'vitest';
import { assert, describe, expect, it, vi } from 'vitest';
import { AutomationsManager } from '../../../src/card-controller/automations-manager';
import { setRemoteControlEntityFromConfig } from '../../../src/card-controller/config/load-control-entities';
import { TemplateRenderer } from '../../../src/card-controller/templates/index';
import { ConditionStateManager } from '../../../src/condition-trigger/conditions/state-manager';
import {
INTERNAL_CALLBACK_ACTION,
InternalCallbackActionConfig,
@@ -48,9 +51,9 @@ describe('setRemoteControlEntityFromConfig', () => {
callback: expect.any(Function),
},
],
conditions: [
triggers: [
{
condition: 'config',
trigger: 'config',
paths: ['cameras', 'remote_control.entities.camera'],
},
],
@@ -64,9 +67,9 @@ describe('setRemoteControlEntityFromConfig', () => {
callback: expect.any(Function),
},
],
conditions: [
triggers: [
{
condition: 'camera',
trigger: 'camera',
},
],
tag: setRemoteControlEntityFromConfig,
@@ -79,9 +82,9 @@ describe('setRemoteControlEntityFromConfig', () => {
callback: expect.any(Function),
},
],
conditions: [
triggers: [
{
condition: 'initialized',
trigger: 'initialized',
},
],
tag: setRemoteControlEntityFromConfig,
@@ -91,13 +94,13 @@ describe('setRemoteControlEntityFromConfig', () => {
{
action: 'fire-dom-event',
advanced_camera_card_action: 'camera_select',
camera: '{{ advanced_camera_card.trigger.state.to }}',
camera: '{{ trigger.to_state.state }}',
},
],
conditions: [
triggers: [
{
condition: 'state',
entity: 'input_select.camera',
trigger: 'state',
entity_id: 'input_select.camera',
},
],
tag: setRemoteControlEntityFromConfig,
@@ -130,9 +133,9 @@ describe('setRemoteControlEntityFromConfig', () => {
callback: expect.any(Function),
},
],
conditions: [
triggers: [
{
condition: 'config',
trigger: 'config',
paths: ['cameras', 'remote_control.entities.camera'],
},
],
@@ -146,9 +149,9 @@ describe('setRemoteControlEntityFromConfig', () => {
callback: expect.any(Function),
},
],
conditions: [
triggers: [
{
condition: 'camera',
trigger: 'camera',
},
],
tag: setRemoteControlEntityFromConfig,
@@ -161,9 +164,9 @@ describe('setRemoteControlEntityFromConfig', () => {
camera: '{{ hass.states["input_select.camera"].state }}',
},
],
conditions: [
triggers: [
{
condition: 'initialized',
trigger: 'initialized',
},
],
tag: setRemoteControlEntityFromConfig,
@@ -173,13 +176,13 @@ describe('setRemoteControlEntityFromConfig', () => {
{
action: 'fire-dom-event',
advanced_camera_card_action: 'camera_select',
camera: '{{ advanced_camera_card.trigger.state.to }}',
camera: '{{ trigger.to_state.state }}',
},
],
conditions: [
triggers: [
{
condition: 'state',
entity: 'input_select.camera',
trigger: 'state',
entity_id: 'input_select.camera',
},
],
tag: setRemoteControlEntityFromConfig,
@@ -618,4 +621,64 @@ describe('setRemoteControlEntityFromConfig', () => {
);
});
});
describe('should render the firing trigger into the camera action', () => {
it('should resolve the new entity state through the trigger template', () => {
const api = createCardAPI();
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(
createConfig({
remote_control: {
entities: {
camera: 'input_select.camera',
camera_priority: 'card',
},
},
}),
);
// Capture the automations the loader registers, then drive them through a
// real AutomationsManager so the state trigger actually fires and its
// `{{ trigger.to_state.state }}` template is rendered end to end (the
// other tests only string-match the literal, so a context mis-wire would
// silently break remote control).
setRemoteControlEntityFromConfig(api);
const automations = vi.mocked(api.getAutomationsManager().addAutomations).mock
.calls[0][0];
vi.mocked(api.getHASSManager().hasHASS).mockReturnValue(true);
vi.mocked(api.getInitializationManager().isInitializedMandatory).mockReturnValue(
true,
);
const stateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
new AutomationsManager(api).addAutomations(automations);
stateManager.setState({
hass: createHASS({
'input_select.camera': createStateEntity({ state: 'camera.one' }),
}),
});
const hass = createHASS({
'input_select.camera': createStateEntity({ state: 'camera.two' }),
});
stateManager.setState({ hass });
const captured = vi
.mocked(api.getActionsManager().executeActions)
.mock.calls.at(-1)?.[0];
assert(captured);
const rendered = new TemplateRenderer().renderRecursively(hass, captured.actions, {
triggerData: captured.triggerData,
});
expect(rendered).toEqual([
{
action: 'fire-dom-event',
advanced_camera_card_action: 'camera_select',
camera: 'camera.two',
},
]);
});
});
});
@@ -78,10 +78,10 @@ describe('setKeyboardShortcutsFromConfig', () => {
ptz_phase: 'start',
},
],
conditions: [
triggers: [
{
alt: undefined,
condition: 'key',
trigger: 'key',
ctrl: undefined,
key: 'z',
meta: undefined,
@@ -100,9 +100,9 @@ describe('setKeyboardShortcutsFromConfig', () => {
ptz_phase: 'stop',
},
],
conditions: [
triggers: [
{
condition: 'key',
trigger: 'key',
key: 'z',
state: 'up',
},
@@ -130,10 +130,10 @@ describe('setKeyboardShortcutsFromConfig', () => {
advanced_camera_card_action: 'ptz_multi',
},
],
conditions: [
triggers: [
{
alt: undefined,
condition: 'key',
trigger: 'key',
ctrl: undefined,
key: 'h',
meta: undefined,
@@ -1,7 +1,7 @@
import { assert, describe, expect, it, vi } from 'vitest';
import { OverridesManager } from '../../../src/card-controller/config/overrides-manager';
import { ConditionStateManager } from '../../../src/condition-trigger/conditions/state-manager';
import { AdvancedCameraCardConfig } from '../../../src/config/schema/types';
import { ConditionStateManager } from '../../../src/conditions/state-manager';
import { AdvancedCameraCardError } from '../../../src/types';
import { createConfig } from '../../test-utils';
+7 -7
View File
@@ -3,6 +3,7 @@ import { CameraManager } from '../../src/camera-manager/manager';
import { ActionsManager } from '../../src/card-controller/actions/actions-manager';
import { AutomationsManager } from '../../src/card-controller/automations-manager';
import { CallManager } from '../../src/card-controller/call/manager';
import { CameraTriggersManager } from '../../src/card-controller/camera-triggers-manager';
import { CameraURLManager } from '../../src/card-controller/camera-url-manager';
import {
CardElementManager,
@@ -28,10 +29,9 @@ import { PIPManager } from '../../src/card-controller/pip-manager';
import { QueryStringManager } from '../../src/card-controller/query-string-manager';
import { StatusBarItemManager } from '../../src/card-controller/status-bar-item-manager';
import { StyleManager } from '../../src/card-controller/style-manager';
import { TriggersManager } from '../../src/card-controller/triggers-manager';
import { ViewItemManager } from '../../src/card-controller/view/item-manager';
import { ViewManager } from '../../src/card-controller/view/view-manager';
import { ConditionStateManager } from '../../src/conditions/state-manager';
import { ConditionStateManager } from '../../src/condition-trigger/conditions/state-manager';
import { AdvancedCameraCardEditor } from '../../src/editor';
import { DeviceRegistryManager } from '../../src/ha/registry/device';
import { EntityRegistryManagerLive } from '../../src/ha/registry/entity';
@@ -64,10 +64,10 @@ vi.mock('../../src/card-controller/issues/issue-manager');
vi.mock('../../src/card-controller/query-string-manager');
vi.mock('../../src/card-controller/status-bar-item-manager');
vi.mock('../../src/card-controller/style-manager');
vi.mock('../../src/card-controller/triggers-manager');
vi.mock('../../src/card-controller/camera-triggers-manager');
vi.mock('../../src/card-controller/view/item-manager');
vi.mock('../../src/card-controller/view/view-manager');
vi.mock('../../src/conditions/state-manager');
vi.mock('../../src/condition-trigger/conditions/state-manager');
vi.mock('../../src/ha/registry/device');
vi.mock('../../src/ha/registry/entity');
vi.mock('../../src/ha/resolved-media');
@@ -301,9 +301,9 @@ describe('CardController', () => {
);
});
it('should return getTriggersManager', () => {
expect(createController().getTriggersManager()).toBe(
vi.mocked(TriggersManager).mock.instances[0],
it('should return getCameraTriggersManager', () => {
expect(createController().getCameraTriggersManager()).toBe(
vi.mocked(CameraTriggersManager).mock.instances[0],
);
});
@@ -192,9 +192,9 @@ describe('DefaultManager', () => {
advanced_camera_card_action: 'default',
},
],
conditions: [
triggers: [
{
condition: 'interaction',
trigger: 'interaction',
interaction: false,
},
],
@@ -172,12 +172,6 @@ describe('MediaMatcher', () => {
is_folder: false,
},
},
advanced_camera_card: {
media: {
title,
is_folder: false,
},
},
},
);
});
@@ -208,12 +202,6 @@ describe('MediaMatcher', () => {
is_folder: false,
},
},
advanced_camera_card: {
media: {
title,
is_folder: false,
},
},
},
);
});
@@ -1,7 +1,7 @@
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { mock } from 'vitest-mock-extended';
import { WebkitFullScreenProvider } from '../../../../src/card-controller/fullscreen/webkit';
import { ConditionStateManager } from '../../../../src/conditions/state-manager';
import { ConditionStateManager } from '../../../../src/condition-trigger/conditions/state-manager';
import { MediaPlayerController, WebkitHTMLVideoElement } from '../../../../src/types';
import { createCardAPI, createMediaLoadedInfo } from '../../../test-utils';
@@ -5,7 +5,7 @@ import {
InitializationAspect,
InitializationManager,
} from '../../src/card-controller/initialization-manager';
import { ConditionStateManager } from '../../src/conditions/state-manager';
import { ConditionStateManager } from '../../src/condition-trigger/conditions/state-manager';
import { sideLoadHomeAssistantElements } from '../../src/ha/side-load-ha-elements.js';
import { loadLanguages } from '../../src/localize/localize';
import { Initializer } from '../../src/utils/initializer/initializer';
+2 -1
View File
@@ -2,7 +2,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createIssueManager } from '../../../src/card-controller/issues/factory';
import { IssueManager } from '../../../src/card-controller/issues/issue-manager';
import { ConditionStateManager } from '../../../src/conditions/state-manager';
import { ConditionStateManager } from '../../../src/condition-trigger/conditions/state-manager';
import { createCardAPI } from '../../test-utils';
describe('createIssueManager', () => {
@@ -27,6 +27,7 @@ describe('createIssueManager', () => {
const expectedKeys = [
'config_error',
'config_upgrade',
'config_upgrade_failure',
'connection',
'initialization',
'legacy_resource',
@@ -12,7 +12,7 @@ import {
IssueDescription,
IssueKey,
} from '../../../src/card-controller/issues/types';
import { ConditionStateManager } from '../../../src/conditions/state-manager';
import { ConditionStateManager } from '../../../src/condition-trigger/conditions/state-manager';
import { InteractionMode } from '../../../src/config/schema/view';
import {
createCardAPI,
@@ -0,0 +1,59 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ConfigUpgradeFailureIssue } from '../../../../src/card-controller/issues/issues/config-upgrade-failure';
import { hasConfigUpgradeFailures } from '../../../../src/config/management';
import { RawAdvancedCameraCardConfig } from '../../../../src/config/types';
import { createCardAPI } from '../../../test-utils';
vi.mock('../../../../src/config/management.js');
const createAPI = (rawConfig?: RawAdvancedCameraCardConfig) => {
const api = createCardAPI();
vi.mocked(api.getConfigManager().getRawConfig).mockReturnValue(rawConfig ?? null);
return api;
};
describe('ConfigUpgradeFailureIssue', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('should have correct key', () => {
const issue = new ConfigUpgradeFailureIssue(createAPI());
expect(issue.key).toBe('config_upgrade_failure');
});
it('should detect failures and return a description', async () => {
vi.mocked(hasConfigUpgradeFailures).mockReturnValue(true);
const rawConfig = { type: 'custom:advanced-camera-card' };
const issue = new ConfigUpgradeFailureIssue(createAPI(rawConfig));
await issue.detectStatic();
expect(issue.hasIssue()).toBe(true);
expect(hasConfigUpgradeFailures).toBeCalledWith(rawConfig);
expect(issue.getIssue()).toEqual(
expect.objectContaining({
icon: 'mdi:update',
severity: 'medium',
notification: expect.objectContaining({
heading: expect.objectContaining({
icon: 'mdi:update',
severity: 'medium',
}),
}),
}),
);
});
it('should report no failures and no description for a clean config', async () => {
vi.mocked(hasConfigUpgradeFailures).mockReturnValue(false);
const issue = new ConfigUpgradeFailureIssue(
createAPI({ type: 'custom:advanced-camera-card' }),
);
await issue.detectStatic();
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
});
+1 -1
View File
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { mock } from 'vitest-mock-extended';
import { CardController } from '../../src/card-controller/controller';
import { PIPManager } from '../../src/card-controller/pip-manager';
import { ConditionStateManager } from '../../src/conditions/state-manager';
import { ConditionStateManager } from '../../src/condition-trigger/conditions/state-manager';
import { MediaPlayerController } from '../../src/types';
import { createCardAPI, createMediaLoadedInfo, flushPromises } from '../test-utils';
+35 -6
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { TemplateRenderer } from '../../../src/card-controller/templates/index';
import { createHASS } from '../../test-utils';
import { createConfig, createHASS, createStateEntity } from '../../test-utils';
describe('TemplateRenderer', () => {
describe('renderRecursively', () => {
@@ -24,13 +24,13 @@ describe('TemplateRenderer', () => {
expect(result).toBe('View: live');
});
it('should render string templates with full advanced_camera_card context', () => {
it('should render string templates with the acc context', () => {
const renderer = new TemplateRenderer();
const hass = createHASS();
const result = renderer.renderRecursively(
hass,
'{{ advanced_camera_card.camera }} - {{ advanced_camera_card.view }}',
'{{ acc.camera }} - {{ acc.view }}',
{
conditionState: { camera: 'camera.front', view: 'clips' },
},
@@ -90,16 +90,45 @@ describe('TemplateRenderer', () => {
expect(renderer.renderRecursively(hass, 'hello world')).toBe('hello world');
});
it('should render with triggerData context', () => {
it('should render with a top-level stock trigger context', () => {
const renderer = new TemplateRenderer();
const hass = createHASS();
const result = renderer.renderRecursively(hass, '{{ acc.trigger.camera.to }}', {
triggerData: { camera: { from: 'camera.front', to: 'camera.backyard' } },
const result = renderer.renderRecursively(hass, '{{ trigger.to_state.state }}', {
triggerData: {
platform: 'state',
entity_id: 'binary_sensor.door',
to_state: createStateEntity({ state: 'on' }),
},
});
expect(result).toBe('on');
});
it('should render with a top-level card trigger context', () => {
const renderer = new TemplateRenderer();
const hass = createHASS();
const result = renderer.renderRecursively(hass, '{{ trigger.to_acc.camera }}', {
triggerData: {
platform: 'acc',
type: 'camera',
from_acc: { camera: 'camera.front' },
to_acc: { camera: 'camera.backyard' },
},
});
expect(result).toBe('camera.backyard');
});
it('should render with config context', () => {
const renderer = new TemplateRenderer();
const hass = createHASS();
const result = renderer.renderRecursively(hass, '{{ acc.config.view.default }}', {
conditionState: { config: createConfig({ view: { default: 'clips' } }) },
});
expect(result).toBe('clips');
});
it('should render with mediaData context', () => {
const renderer = new TemplateRenderer();
const hass = createHASS();