feat: Add hardened error handling and retries (#2451)

- Closes #1830
 - Closes #2099
This commit is contained in:
Dermot Duffy
2026-06-30 17:45:12 -07:00
committed by dermotduffy
parent 4bc787e2b7
commit 47bcce93d3
182 changed files with 7877 additions and 4043 deletions
@@ -0,0 +1,91 @@
// @vitest-environment jsdom
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 { createCardAPI } from '../../test-utils';
describe('createIssueManager', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('should return a IssueManager instance', () => {
const manager = createIssueManager(createCardAPI());
expect(manager).toBeInstanceOf(IssueManager);
});
it('should register all expected issues', () => {
const manager = createIssueManager(createCardAPI()).getStateManager();
expect(manager.getIssueDescriptions()).toHaveLength(0);
const expectedKeys = [
'config_error',
'config_upgrade',
'connection',
'initialization',
'legacy_resource',
'media_query',
'media_load',
'view_incompatible',
] as const;
for (const key of expectedKeys) {
expect(() => manager.getNotification(key)).not.toThrow();
}
});
it('should register issues in an order that determines priority', () => {
// Lock the registration order. The relative order of these issues
// governs full-card display priority (getFullCardIssue returns the
// first active full-card issue) and retry-loop priority. Alphabetizing
// the list in factory.ts would silently change both. Triggering in a
// scrambled order proves getIssueDescriptions reflects registration
// order, not trigger order.
const api = createCardAPI();
const stateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const manager = createIssueManager(api);
manager.trigger('media_query', { error: new Error('x') });
manager.trigger('initialization', { error: new Error('x') });
manager.trigger('config_error', { error: new Error('x') });
manager.trigger('view_incompatible', { error: new Error('x') });
const keys = manager
.getStateManager()
.getIssueDescriptions()
.map((d) => d.key);
expect(keys).toEqual([
'config_error',
'view_incompatible',
'initialization',
'media_query',
]);
});
it('should wire changeCallback so timer-based issues activate via evaluate', () => {
const api = createCardAPI();
const stateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const manager = createIssueManager(api);
// Setting view starts the media_load timer (via the condition state
// listener → evaluate → detectDynamic).
stateManager.setState({ targetID: 'camera-1', view: 'live' });
expect(manager.getStateManager().getIssuePresence().has('media_load')).toBe(false);
// After the timeout, the changeCallback fires evaluate which
// updates the card element.
vi.advanceTimersByTime(10000);
expect(manager.getStateManager().getIssuePresence().has('media_load')).toBe(true);
});
});
@@ -0,0 +1,884 @@
// @vitest-environment jsdom
import { afterEach, assert, beforeEach, describe, expect, it, vi } from 'vitest';
import { mock } from 'vitest-mock-extended';
import { CardController } from '../../../src/card-controller/controller';
import {
IssueManager,
RETRY_EXPONENTIAL_BASE_SECONDS,
RETRY_EXPONENTIAL_MAX_SECONDS,
} from '../../../src/card-controller/issues/issue-manager';
import {
Issue,
IssueDescription,
IssueKey,
} from '../../../src/card-controller/issues/types';
import { ConditionStateManager } from '../../../src/conditions/state-manager';
import { InteractionMode } from '../../../src/config/schema/view';
import {
createCardAPI,
createConfig,
createHASS,
flushPromises,
} from '../../test-utils';
const DEFAULT_RETRY_SECONDS = 1;
const createIssue = (key: IssueKey, overrides?: Partial<Issue>): Issue =>
mock({
key,
hasIssue: vi.fn().mockReturnValue(false),
getIssue: vi.fn().mockReturnValue(null),
needsRetry: vi.fn().mockReturnValue(false),
...overrides,
});
const createIssueDescription = (
overrides?: Partial<IssueDescription>,
): IssueDescription => ({
icon: 'mdi:alert',
severity: 'high',
notification: { body: { text: 'test' } },
...overrides,
});
const createRetriableSetup = (options?: {
retrySeconds?: 'auto' | number;
interactionMode?: InteractionMode;
hasInteraction?: boolean;
}): {
api: CardController;
manager: IssueManager;
issue: Issue;
} => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
if (options?.hasInteraction !== undefined) {
vi.mocked(api.getInteractionManager().hasInteraction).mockReturnValue(
options.hasInteraction,
);
}
const config = createConfig();
vi.mocked(api.getConfigManager().getConfig).mockReturnValue({
...config,
view: {
...config.view,
issues: {
interaction_mode: options?.interactionMode ?? 'inactive',
retry_seconds: options?.retrySeconds ?? DEFAULT_RETRY_SECONDS,
},
},
});
const manager = new IssueManager(api);
const issue = createIssue('media_load', {
hasIssue: vi.fn().mockReturnValueOnce(false).mockReturnValue(true),
needsRetry: vi.fn().mockReturnValue(true),
retry: vi.fn().mockReturnValue(false),
});
manager.addIssue(issue);
return { api, manager, issue };
};
describe('IssueManager', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it('should register a listener on the condition state manager on construction', () => {
const api = createCardAPI();
const stateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const manager = new IssueManager(api);
const issue = createIssue('config_error', {
detectDynamic: vi.fn(),
});
manager.addIssue(issue);
stateManager.setState({ view: 'live' });
expect(issue.detectDynamic).toBeCalled();
});
describe('addIssue / getStateManager', () => {
it('should make added issues accessible via getManager', () => {
const manager = new IssueManager(createCardAPI());
const issue = createIssue('config_error');
manager.addIssue(issue);
expect(manager.getStateManager().getIssuePresence().has('config_error')).toBe(
false,
);
});
});
describe('static detection via condition-state listener', () => {
it('should run static detection when mandatory init completes', async () => {
const api = createCardAPI();
const conditionStateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(conditionStateManager);
const manager = new IssueManager(api);
const detectStatic = vi.fn().mockResolvedValue(undefined);
const issue = createIssue('legacy_resource', { detectStatic });
manager.addIssue(issue);
const hass = createHASS();
conditionStateManager.setState({ hass });
conditionStateManager.setState({ initialized: true });
await flushPromises();
expect(detectStatic).toBeCalledWith(hass);
});
it('should not run static detection when hass is unset', () => {
const api = createCardAPI();
const conditionStateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(conditionStateManager);
const manager = new IssueManager(api);
const detectStatic = vi.fn().mockResolvedValue(undefined);
const issue = createIssue('legacy_resource', { detectStatic });
manager.addIssue(issue);
conditionStateManager.setState({ initialized: true });
expect(detectStatic).not.toBeCalled();
});
it('should not run static detection on unrelated state changes', () => {
const api = createCardAPI();
const conditionStateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(conditionStateManager);
const manager = new IssueManager(api);
const detectStatic = vi.fn().mockResolvedValue(undefined);
const issue = createIssue('legacy_resource', { detectStatic });
manager.addIssue(issue);
const hass = createHASS();
conditionStateManager.setState({ hass });
conditionStateManager.setState({ view: 'live' });
expect(detectStatic).not.toBeCalled();
});
});
describe('trigger', () => {
it('should trigger the issue and call evaluate', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
const manager = new IssueManager(api);
const issue = createIssue('config_error', {
trigger: vi.fn(),
});
manager.addIssue(issue);
manager.trigger('config_error', { error: new Error('cfg') });
expect(issue.trigger).toBeCalledWith({ error: expect.any(Error) });
});
it('should update presence even when state was mutated before detectDynamic', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
vi.mocked(api.getConditionStateManager().setState).mockReturnValue(true);
const manager = new IssueManager(api);
// hasIssue returns true from the start — simulates trigger() having
// already mutated state before detectDynamic snapshots. The
// before/after check inside detectDynamic sees true→true (no
// transition), but the presence comparison against ConditionState
// must still detect the change.
const description = createIssueDescription();
const issue = createIssue('config_error', {
hasIssue: vi.fn().mockReturnValue(true),
getIssue: vi.fn().mockReturnValue(description),
trigger: vi.fn(),
});
manager.addIssue(issue);
manager.trigger('config_error', { error: new Error('cfg') });
expect(api.getConditionStateManager().setState).toBeCalledWith({
issues: new Map([['config_error', description]]),
});
expect(api.getCardElementManager().update).toBeCalled();
});
it('should never auto-popup on trigger — non-full-card issues surface via the status-bar icon; user clicks to open', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
const manager = new IssueManager(api);
const issue = createIssue('view_incompatible', {
hasIssue: vi.fn().mockReturnValue(true),
isFullCardIssue: vi.fn().mockReturnValue(false),
getIssue: vi.fn().mockReturnValue(createIssueDescription()),
getNotification: vi.fn().mockReturnValue({ body: { text: 'noop' } }),
trigger: vi.fn(),
});
manager.addIssue(issue);
manager.trigger('view_incompatible', { error: new Error('mismatch') });
expect(api.getNotificationManager().setNotification).not.toBeCalled();
});
});
describe('retry', () => {
it('should call retry on the manager and reset the timer', () => {
const { manager, issue } = createRetriableSetup();
// Start the timer via evaluate, then immediately retry.
manager.evaluate();
manager.retry('media_load');
expect(issue.retry).toBeCalled();
// Timer should have been reset — advancing less than retrySeconds
// should not fire it again.
assert(issue.retry);
vi.mocked(issue.retry).mockClear();
vi.advanceTimersByTime(500);
expect(issue.retry).not.toBeCalled();
});
it('should force retry even when needsRetry is false', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
const manager = new IssueManager(api);
const issue = createIssue('media_load', {
retry: vi.fn().mockReturnValue(false),
});
manager.addIssue(issue);
manager.retry('media_load', true);
expect(issue.retry).toBeCalled();
});
});
describe('evaluate', () => {
it('should update condition state and card when presence differs from state', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
vi.mocked(api.getConditionStateManager().setState).mockReturnValue(true);
const manager = new IssueManager(api);
const description = createIssueDescription();
const issue = createIssue('config_error', {
hasIssue: vi.fn().mockReturnValue(true),
getIssue: vi.fn().mockReturnValue(description),
});
manager.addIssue(issue);
manager.evaluate();
expect(api.getConditionStateManager().setState).toBeCalledWith({
issues: new Map([['config_error', description]]),
});
expect(api.getCardElementManager().update).toBeCalled();
});
it('should sync presence to condition state without update when unchanged', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
const manager = new IssueManager(api);
const issue = createIssue('config_error');
manager.addIssue(issue);
manager.evaluate();
expect(api.getConditionStateManager().setState).toBeCalledWith({
issues: new Map(),
});
expect(api.getCardElementManager().update).not.toBeCalled();
});
it('should call update when an active issue swaps sub-states without changing the key set', () => {
// Simulates ConnectionIssue going from 'lost' to 'starting': the
// presence key set ({connection}) is identical, but the description
// value differs. Because IssuePresence is a Map<key, description>,
// the condition state diff sees the value-level change and fires
// listeners — the IssueManager's own listener calls update().
const api = createCardAPI();
// Real ConditionStateManager so its isEqual-based diff actually runs.
const stateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const manager = new IssueManager(api);
const getIssue = vi
.fn()
.mockReturnValue(
createIssueDescription({ notification: { body: { text: 'lost' } } }),
);
const issue = createIssue('connection', {
hasIssue: vi.fn().mockReturnValue(true),
getIssue,
});
manager.addIssue(issue);
manager.evaluate();
vi.mocked(api.getCardElementManager().update).mockClear();
// Same key set ({connection}), different description value.
getIssue.mockReturnValue(
createIssueDescription({ notification: { body: { text: 'starting' } } }),
);
manager.evaluate();
expect(api.getCardElementManager().update).toBeCalled();
});
it('should not call update when content is identical across evaluations', () => {
const api = createCardAPI();
const stateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const manager = new IssueManager(api);
const issue = createIssue('connection', {
hasIssue: vi.fn().mockReturnValue(true),
getIssue: vi.fn().mockReturnValue(createIssueDescription()),
});
manager.addIssue(issue);
manager.evaluate();
vi.mocked(api.getCardElementManager().update).mockClear();
// Re-evaluate without any change.
manager.evaluate();
expect(api.getCardElementManager().update).not.toBeCalled();
});
it('should trigger evaluate from listener on condition state manager', () => {
const api = createCardAPI();
const stateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const manager = new IssueManager(api);
const issue = createIssue('config_error', {
hasIssue: vi.fn().mockReturnValue(true),
detectDynamic: vi.fn(),
});
manager.addIssue(issue);
stateManager.setState({ view: 'live' });
expect(issue.detectDynamic).toBeCalled();
});
it('should not re-enter evaluate when setState triggers listener', () => {
const api = createCardAPI();
const stateManager = new ConditionStateManager();
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
const manager = new IssueManager(api);
const issue = createIssue('config_error', {
hasIssue: vi.fn().mockReturnValue(true),
detectDynamic: vi.fn(),
});
manager.addIssue(issue);
// Calling evaluate() will call setState() on the real
// ConditionStateManager, which fires listeners synchronously. The
// reentrancy guard must prevent detectDynamic from running twice.
manager.evaluate();
expect(issue.detectDynamic).toBeCalledTimes(1);
});
});
describe('showNotification', () => {
it('should call setNotification when a notification is available', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
const manager = new IssueManager(api);
const notification = { body: { text: 'test notification' } };
const issue = createIssue('media_query', {
getNotification: vi.fn().mockReturnValue(notification),
});
manager.addIssue(issue);
manager.showNotification('media_query');
expect(api.getNotificationManager().setNotification).toBeCalledWith(notification);
});
it('should not call setNotification when no notification exists for key', () => {
const manager = new IssueManager(createCardAPI());
manager.showNotification('initialization');
expect(createCardAPI().getNotificationManager().setNotification).not.toBeCalled();
});
});
describe('scheduled retries', () => {
it('should not schedule a retry when no issue wants retry', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(createConfig());
const manager = new IssueManager(api);
const issue = createIssue('config_error');
manager.addIssue(issue);
manager.evaluate();
vi.runAllTimers();
expect(api.getViewManager().setViewWithMergedContext).not.toBeCalled();
});
it('should not schedule a retry when config is null', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(null);
const manager = new IssueManager(api);
const issue = createIssue('media_load', {
hasIssue: vi.fn().mockReturnValueOnce(false).mockReturnValue(true),
needsRetry: vi.fn().mockReturnValue(true),
retry: vi.fn().mockReturnValue(false),
});
manager.addIssue(issue);
manager.evaluate();
vi.runAllTimers();
expect(issue.retry).not.toBeCalled();
});
it('should not schedule a retry when retry_seconds is 0', () => {
const { manager, issue } = createRetriableSetup({ retrySeconds: 0 });
manager.evaluate();
vi.runAllTimers();
expect(issue.retry).not.toBeCalled();
});
it('should schedule a retry when an issue wants retry and retry_seconds > 0', () => {
const { manager, issue } = createRetriableSetup({ retrySeconds: 5 });
manager.evaluate();
vi.advanceTimersByTime(5000);
expect(issue.retry).toBeCalled();
});
it('should call retry on the issue when the timer fires', () => {
const { manager, issue } = createRetriableSetup();
manager.evaluate();
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
expect(issue.retry).toBeCalled();
});
it('should not schedule a second timer if one is already running', () => {
const { manager, issue } = createRetriableSetup({ retrySeconds: 10 });
manager.evaluate();
manager.evaluate();
vi.advanceTimersByTime(10000);
expect(issue.retry).toBeCalledTimes(1);
});
it('should stop repeated timer when needsRetry becomes false', () => {
const { manager, issue } = createRetriableSetup();
manager.evaluate();
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
expect(issue.retry).toBeCalledTimes(1);
assert(issue.needsRetry);
vi.mocked(issue.needsRetry).mockReturnValue(false);
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
expect(issue.retry).toBeCalledTimes(1);
vi.advanceTimersByTime(5000);
expect(issue.retry).toBeCalledTimes(1);
});
it('should skip scheduled retry when user is interacting and mode is inactive', () => {
const { manager, issue } = createRetriableSetup({
hasInteraction: true,
});
manager.evaluate();
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
expect(issue.retry).not.toBeCalled();
});
it('should allow scheduled retry when user is not interacting and mode is inactive', () => {
const { manager, issue } = createRetriableSetup({
hasInteraction: false,
});
manager.evaluate();
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
expect(issue.retry).toBeCalled();
});
it('should allow scheduled retry when mode is all regardless of interaction', () => {
const { manager, issue } = createRetriableSetup({
interactionMode: 'all',
hasInteraction: true,
});
manager.evaluate();
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
expect(issue.retry).toBeCalled();
});
it('should retry on next interval after interaction ends', () => {
const { api, manager, issue } = createRetriableSetup({
hasInteraction: true,
});
manager.evaluate();
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
expect(issue.retry).not.toBeCalled();
vi.mocked(api.getInteractionManager().hasInteraction).mockReturnValue(false);
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
expect(issue.retry).toBeCalled();
});
});
describe('auto retry (exponential backoff)', () => {
it('should schedule the first retry within the 15s–30s jitter range', () => {
// Math.random returns 0 → jitter = 0.5 → delay = base * 0.5 = 15s.
vi.spyOn(Math, 'random').mockReturnValue(0);
const { manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
manager.evaluate();
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.5 * 1000 - 1);
expect(issue.retry).not.toBeCalled();
vi.advanceTimersByTime(1);
expect(issue.retry).toBeCalledTimes(1);
});
it('should schedule the first retry at the upper bound when jitter is max', () => {
// Math.random returns 1 → jitter = 1.0 → delay = base * 1.0 = 30s.
vi.spyOn(Math, 'random').mockReturnValue(1);
const { manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
manager.evaluate();
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 1.0 * 1000 - 1);
expect(issue.retry).not.toBeCalled();
vi.advanceTimersByTime(1);
expect(issue.retry).toBeCalledTimes(1);
});
it('should double the base delay on each successive attempt', () => {
// Math.random returns 0.5 → jitter = 0.75 → delays: 22.5, 45, 90 seconds.
vi.spyOn(Math, 'random').mockReturnValue(0.5);
const { manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
manager.evaluate();
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
expect(issue.retry).toBeCalledTimes(1);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 2 * 0.75 * 1000);
expect(issue.retry).toBeCalledTimes(2);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 4 * 0.75 * 1000);
expect(issue.retry).toBeCalledTimes(3);
});
it('should cap the backoff at the max delay', () => {
// Drive 5 pre-cap attempts (30, 60, 120, 240, 480 seconds), then assert
// the 6th attempt clamps to MAX instead of the would-be 960.
vi.spyOn(Math, 'random').mockReturnValue(1);
const { manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
manager.evaluate();
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 1 * 1000);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 2 * 1000);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 4 * 1000);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 8 * 1000);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 16 * 1000);
expect(issue.retry).toBeCalledTimes(5);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_MAX_SECONDS * 1000);
expect(issue.retry).toBeCalledTimes(6);
});
it('should reset the attempt counter when the issue clears', () => {
vi.spyOn(Math, 'random').mockReturnValue(0.5);
const { manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
manager.evaluate();
// Run two retries — second delay should be 2x the first.
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 2 * 0.75 * 1000);
expect(issue.retry).toBeCalledTimes(2);
// Clear the issue: needsRetry returns false. The next timer fire sees
// it cleared and resets the attempt counter.
assert(issue.needsRetry);
vi.mocked(issue.needsRetry).mockReturnValue(false);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 4 * 0.75 * 1000);
expect(issue.retry).toBeCalledTimes(2);
// Re-arm: needsRetry returns true again, evaluate to re-schedule.
vi.mocked(issue.needsRetry).mockReturnValue(true);
manager.evaluate();
// Next delay should be back at the base (attempt 0), not continuing
// from where we left off.
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
expect(issue.retry).toBeCalledTimes(3);
});
it('should not grow the delay while retries are gated by user interaction', () => {
// Auto mode + interaction gating: when the timer fires while the user
// is interacting, the retry is skipped (not counted as an attempt) and
// the timer re-arms at the *same* delay, not the next exponential step.
vi.spyOn(Math, 'random').mockReturnValue(0.5);
const { api, manager, issue } = createRetriableSetup({
retrySeconds: 'auto',
hasInteraction: true,
});
manager.evaluate();
// Three gated firings — each at the base delay (22.5s with 0.75 jitter).
// If the counter were incrementing on gated fires, the second would be
// at 45s and we'd never reach it after only 22.5s.
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
expect(issue.retry).not.toBeCalled();
// Clear the interaction. The next firing — still at the base delay —
// is now allowed and the retry runs.
vi.mocked(api.getInteractionManager().hasInteraction).mockReturnValue(false);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
expect(issue.retry).toBeCalledTimes(1);
});
it('should reset the attempt counter when retries are disabled and re-enabled', () => {
// Drive auto-mode retries to push _retryAttempt > 0, then disable
// retries (retry_seconds=0) and re-enable. The next retry must fire at
// the base delay, not at the inflated delay the prior counter implies.
vi.spyOn(Math, 'random').mockReturnValue(0.5);
const { api, manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
manager.evaluate();
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 2 * 0.75 * 1000);
expect(issue.retry).toBeCalledTimes(2);
// Disable retries via config.
const config = createConfig();
vi.mocked(api.getConfigManager().getConfig).mockReturnValue({
...config,
view: {
...config.view,
issues: { interaction_mode: 'inactive', retry_seconds: 0 },
},
});
// Let the pending timer fire. The retry runs (#3), then evaluate sees
// retry_seconds=0 and resets _retryAttempt.
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 4 * 0.75 * 1000);
expect(issue.retry).toBeCalledTimes(3);
// Re-enable.
vi.mocked(api.getConfigManager().getConfig).mockReturnValue({
...config,
view: {
...config.view,
issues: { interaction_mode: 'inactive', retry_seconds: 'auto' },
},
});
manager.evaluate();
// Without the reset, _retryAttempt would be 3 here, making the next
// delay BASE * 8 * 0.75 = 180s. With the reset, it's BASE * 0.75 = 22.5s,
// so advancing only the base interval triggers the next retry.
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
expect(issue.retry).toBeCalledTimes(4);
});
});
describe('reset', () => {
it('should reset a specific issue and re-evaluate', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
const manager = new IssueManager(api);
const issue = createIssue('config_error', {
hasIssue: vi.fn().mockReturnValue(true),
getIssue: vi.fn().mockReturnValue(createIssueDescription()),
reset: vi.fn(),
});
manager.addIssue(issue);
manager.reset('config_error');
expect(issue.reset).toBeCalled();
});
it('should skip reset when targeted key has no active issue', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
const manager = new IssueManager(api);
const issue = createIssue('config_error', {
hasIssue: vi.fn().mockReturnValue(false),
detectDynamic: vi.fn(),
reset: vi.fn(),
});
manager.addIssue(issue);
manager.reset('config_error');
expect(issue.reset).not.toBeCalled();
expect(issue.detectDynamic).not.toBeCalled();
});
});
describe('suspend / resume', () => {
it('should stop the retry timer on suspend', () => {
const { manager, issue } = createRetriableSetup({ retrySeconds: 5 });
manager.evaluate();
manager.suspend();
vi.advanceTimersByTime(5000);
expect(issue.retry).not.toBeCalled();
});
it('should gate evaluate while suspended', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
const manager = new IssueManager(api);
const issue = createIssue('config_error', {
hasIssue: vi.fn().mockReturnValue(true),
detectDynamic: vi.fn(),
});
manager.addIssue(issue);
manager.suspend();
manager.evaluate();
expect(issue.detectDynamic).not.toBeCalled();
});
it('should preserve issue state across suspend', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
const manager = new IssueManager(api);
const issue = createIssue('config_error', {
hasIssue: vi.fn().mockReturnValue(true),
getIssue: vi.fn().mockReturnValue(createIssueDescription()),
});
manager.addIssue(issue);
manager.suspend();
expect(manager.getStateManager().getIssuePresence().has('config_error')).toBe(
true,
);
});
it('should resume evaluation on resume', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
vi.mocked(api.getConditionStateManager().setState).mockReturnValue(true);
const manager = new IssueManager(api);
const issue = createIssue('config_error', {
hasIssue: vi.fn().mockReturnValue(true),
detectDynamic: vi.fn(),
});
manager.addIssue(issue);
manager.suspend();
manager.resume();
expect(issue.detectDynamic).toBeCalled();
expect(api.getCardElementManager().update).toBeCalled();
});
it('should invoke Issue.suspend on timer-backed issues when suspended', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
const manager = new IssueManager(api);
const issue = createIssue('media_load', { suspend: vi.fn() });
manager.addIssue(issue);
manager.suspend();
expect(issue.suspend).toBeCalled();
});
it('should tolerate issues without a suspend hook', () => {
const api = createCardAPI();
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
const manager = new IssueManager(api);
// Plain Issue implementation — no optional methods installed.
const issue: Issue = {
key: 'config_error',
hasIssue: () => false,
getIssue: () => null,
};
manager.addIssue(issue);
// Must not throw.
manager.suspend();
});
});
describe('destroy', () => {
it('should stop the retry timer and destroy the manager', () => {
const { manager, issue } = createRetriableSetup({ retrySeconds: 5 });
assert(issue.reset);
manager.evaluate();
manager.destroy();
vi.advanceTimersByTime(5000);
expect(issue.retry).not.toBeCalled();
expect(issue.reset).toBeCalled();
});
});
});
@@ -0,0 +1,71 @@
import { describe, expect, it } from 'vitest';
import { ConfigErrorIssue } from '../../../../src/card-controller/issues/issues/config-error';
describe('ConfigErrorIssue', () => {
it('should have correct key', () => {
const issue = new ConfigErrorIssue();
expect(issue.key).toBe('config_error');
});
it('should report no issue when untriggered', () => {
const issue = new ConfigErrorIssue();
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
it('should report an issue after trigger with an error', () => {
const issue = new ConfigErrorIssue();
issue.trigger({ error: new Error('bad config') });
expect(issue.hasIssue()).toBe(true);
});
it('should report an issue after trigger with a string error', () => {
const issue = new ConfigErrorIssue();
issue.trigger({ error: 'string error' });
expect(issue.hasIssue()).toBe(true);
});
it('should treat a triggered null/undefined error as no issue', () => {
const issue = new ConfigErrorIssue();
issue.trigger({ error: undefined });
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
it('isFullCardIssue should return true', () => {
const issue = new ConfigErrorIssue();
expect(issue.isFullCardIssue()).toBe(true);
});
it('getIssue should return a IssueDescription with expected shape', () => {
const issue = new ConfigErrorIssue();
issue.trigger({ error: new Error('config is invalid') });
const result = issue.getIssue();
expect(result).toEqual(
expect.objectContaining({
icon: 'mdi:alert',
severity: 'high',
notification: expect.objectContaining({
body: expect.objectContaining({
text: 'config is invalid',
}),
}),
}),
);
});
it('should clear the issue after reset', () => {
const issue = new ConfigErrorIssue();
issue.trigger({ error: new Error('oops') });
expect(issue.hasIssue()).toBe(true);
issue.reset();
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
});
@@ -0,0 +1,71 @@
import { describe, expect, it, vi } from 'vitest';
import { ConfigUpgradeIssue } from '../../../../src/card-controller/issues/issues/config-upgrade';
import { isConfigUpgradeable } 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('ConfigUpgradeIssue', () => {
it('should have correct key', () => {
const issue = new ConfigUpgradeIssue(createAPI());
expect(issue.key).toBe('config_upgrade');
});
it('should detect upgradeable config', async () => {
vi.mocked(isConfigUpgradeable).mockReturnValue(true);
const rawConfig = { type: 'custom:frigate-card' };
const issue = new ConfigUpgradeIssue(createAPI(rawConfig));
await issue.detectStatic();
expect(issue.hasIssue()).toBe(true);
expect(isConfigUpgradeable).toBeCalledWith(rawConfig);
});
it('should detect non-upgradeable config', async () => {
vi.mocked(isConfigUpgradeable).mockReturnValue(false);
const rawConfig = { type: 'custom:advanced-camera-card' };
const issue = new ConfigUpgradeIssue(createAPI(rawConfig));
await issue.detectStatic();
expect(issue.hasIssue()).toBe(false);
});
it('should handle null raw config', async () => {
const issue = new ConfigUpgradeIssue(createAPI());
await issue.detectStatic();
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
it('should return result when upgradeable', async () => {
vi.mocked(isConfigUpgradeable).mockReturnValue(true);
const issue = new ConfigUpgradeIssue(createAPI({ type: 'custom:frigate-card' }));
await issue.detectStatic();
const result = issue.getIssue();
expect(result).toEqual(
expect.objectContaining({
icon: 'mdi:update',
severity: 'medium',
notification: expect.objectContaining({
heading: expect.objectContaining({
icon: 'mdi:update',
severity: 'medium',
}),
}),
}),
);
});
});
@@ -0,0 +1,127 @@
import { STATE_RUNNING, STATE_STARTING } from 'home-assistant-js-websocket';
import { describe, expect, it } from 'vitest';
import { ConnectionIssue } from '../../../../src/card-controller/issues/issues/connection';
import { createHASS } from '../../../test-utils';
describe('ConnectionIssue', () => {
it('should have correct key', () => {
const issue = new ConnectionIssue();
expect(issue.key).toBe('connection');
});
it('should report no issue when hass has never been set', () => {
const issue = new ConnectionIssue();
issue.detectDynamic({});
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
it('should report a lost issue when hass is disconnected', () => {
const issue = new ConnectionIssue();
const hass = createHASS();
hass.connected = false;
issue.detectDynamic({ hass });
expect(issue.hasIssue()).toBe(true);
expect(issue.getIssue()).toEqual(
expect.objectContaining({
icon: 'mdi:lan-disconnect',
severity: 'high',
notification: expect.objectContaining({
in_progress: true,
heading: expect.objectContaining({
text: 'Connection lost',
icon: 'mdi:lan-disconnect',
severity: 'high',
}),
body: expect.objectContaining({
text: 'Connection to Home Assistant lost',
}),
}),
}),
);
});
it('should report a starting issue when hass is connected but not running', () => {
const issue = new ConnectionIssue();
const hass = createHASS();
hass.connected = true;
hass.config.state = STATE_STARTING;
issue.detectDynamic({ hass });
expect(issue.hasIssue()).toBe(true);
expect(issue.getIssue()).toEqual(
expect.objectContaining({
icon: 'mdi:home-assistant',
severity: 'medium',
notification: expect.objectContaining({
in_progress: true,
heading: expect.objectContaining({
text: 'Home Assistant is starting',
icon: 'mdi:home-assistant',
severity: 'medium',
}),
body: expect.objectContaining({
text: 'Waiting for Home Assistant startup to complete',
}),
}),
}),
);
});
it('should not report an issue when hass is connected and running', () => {
const issue = new ConnectionIssue();
const hass = createHASS();
hass.connected = true;
hass.config.state = STATE_RUNNING;
issue.detectDynamic({ hass });
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
it('should clear when hass transitions lost → starting → ready', () => {
const issue = new ConnectionIssue();
const hass = createHASS();
hass.connected = false;
issue.detectDynamic({ hass });
expect(issue.hasIssue()).toBe(true);
expect(issue.getIssue()?.notification.heading?.text).toBe('Connection lost');
hass.connected = true;
hass.config.state = STATE_STARTING;
issue.detectDynamic({ hass });
expect(issue.hasIssue()).toBe(true);
expect(issue.getIssue()?.notification.heading?.text).toBe(
'Home Assistant is starting',
);
hass.config.state = STATE_RUNNING;
issue.detectDynamic({ hass });
expect(issue.hasIssue()).toBe(false);
});
it('should return true for isFullCardIssue', () => {
const issue = new ConnectionIssue();
expect(issue.isFullCardIssue()).toBe(true);
});
it('should clear the issue after reset', () => {
const issue = new ConnectionIssue();
const hass = createHASS();
hass.connected = false;
issue.detectDynamic({ hass });
expect(issue.hasIssue()).toBe(true);
issue.reset();
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
});
@@ -0,0 +1,153 @@
import { assert, describe, expect, it, vi } from 'vitest';
import { CardController } from '../../../../src/card-controller/controller';
import { InitializationIssue } from '../../../../src/card-controller/issues/issues/initialization';
import { InternalCallbackActionConfig } from '../../../../src/config/schema/actions/custom/internal';
import { createCardAPI } from '../../../test-utils';
describe('InitializationIssue', () => {
const createAPI = (isInitializedMandatory = false): CardController => {
const api = createCardAPI();
vi.mocked(api.getInitializationManager().isInitializedMandatory).mockReturnValue(
isInitializedMandatory,
);
return api;
};
it('should have correct key', () => {
const issue = new InitializationIssue(createAPI());
expect(issue.key).toBe('initialization');
});
it('should report no issue when untriggered', () => {
const issue = new InitializationIssue(createAPI());
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
it('should report an issue after trigger', () => {
const issue = new InitializationIssue(createAPI());
issue.trigger({ error: new Error('init failed') });
expect(issue.hasIssue()).toBe(true);
});
it('should treat a triggered null/undefined error as no issue', () => {
const issue = new InitializationIssue(createAPI());
issue.trigger({ error: undefined });
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
expect(issue.needsRetry()).toBe(false);
});
it('should return true for isFullCardIssue', () => {
const issue = new InitializationIssue(createAPI());
expect(issue.isFullCardIssue()).toBe(true);
});
it('should return notification from error via getIssue', () => {
const issue = new InitializationIssue(createAPI());
issue.trigger({ error: new Error('init failed') });
const result = issue.getIssue();
expect(result).toEqual(
expect.objectContaining({
icon: 'mdi:alert',
severity: 'high',
notification: expect.objectContaining({
heading: expect.objectContaining({ text: 'Initialization failed' }),
body: expect.objectContaining({ text: 'init failed' }),
controls: expect.arrayContaining([
expect.objectContaining({ icon: 'mdi:refresh', dismiss: true }),
]),
}),
}),
);
expect(result?.notification.in_progress).toBeUndefined();
});
it('should call manager.retry with the issue key from getIssue retry control callback', async () => {
const api = createCardAPI();
const issue = new InitializationIssue(api);
issue.trigger({ error: new Error('init failed') });
const control = issue.getIssue()?.notification.controls?.[0];
assert(control);
const tapAction = control.actions?.tap_action as InternalCallbackActionConfig;
await tapAction.callback(api);
expect(api.getIssueManager().retry).toBeCalledWith('initialization', true);
});
describe('detectDynamic', () => {
it('should clear the issue when initialization is now mandatory', () => {
const issue = new InitializationIssue(createAPI(true));
issue.trigger({ error: new Error('init failed') });
expect(issue.hasIssue()).toBe(true);
issue.detectDynamic();
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
it('should keep the issue when initialization is still not mandatory', () => {
const issue = new InitializationIssue(createAPI(false));
issue.trigger({ error: new Error('init failed') });
issue.detectDynamic();
expect(issue.hasIssue()).toBe(true);
});
it('should do nothing when not failed', () => {
const api = createAPI(false);
const issue = new InitializationIssue(api);
issue.detectDynamic();
expect(issue.hasIssue()).toBe(false);
expect(api.getInitializationManager().isInitializedMandatory).not.toBeCalled();
});
});
describe('needsRetry', () => {
it('should return true when failed', () => {
const issue = new InitializationIssue(createAPI());
issue.trigger({ error: new Error('init failed') });
expect(issue.needsRetry()).toBe(true);
});
it('should return false when not failed', () => {
const issue = new InitializationIssue(createAPI());
expect(issue.needsRetry()).toBe(false);
});
});
describe('retry', () => {
it('should uninitialize mandatory initialization and destroy camera manager', () => {
const api = createAPI();
const issue = new InitializationIssue(api);
issue.trigger({ error: new Error('init failed') });
const result = issue.retry();
expect(result).toBe(false);
expect(issue.hasIssue()).toBe(false);
expect(issue.needsRetry()).toBe(false);
expect(api.getInitializationManager().uninitializeMandatory).toBeCalled();
expect(api.getCameraManager().destroy).toBeCalled();
});
});
it('should clear the issue after reset', () => {
const issue = new InitializationIssue(createAPI());
issue.trigger({ error: new Error('oops') });
expect(issue.hasIssue()).toBe(true);
issue.reset();
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
});
@@ -0,0 +1,474 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { LegacyResourceIssue } from '../../../../src/card-controller/issues/issues/legacy-resource';
import { HomeAssistant } from '../../../../src/ha/types';
import { createCardAPI, createHASS, createUser } from '../../../test-utils';
const setupHASSResources = (
hass: HomeAssistant,
resources: { id: string; type: string; url: string }[],
): void => {
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
vi.mocked(hass.callWS).mockResolvedValue(resources);
};
describe('LegacyResourceIssue', () => {
beforeEach(() => {
vi.resetAllMocks();
});
it('should have correct key', () => {
const issue = new LegacyResourceIssue();
expect(issue.key).toBe('legacy_resource');
});
describe('detectStatic', () => {
it('should skip non-admin users', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: false }));
await issue.detectStatic(hass);
expect(issue.hasIssue()).toBe(false);
});
it('should detect legacy resource regardless of directory', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
setupHASSResources(hass, [
{
id: '1',
type: 'module',
url: '/some/arbitrary/path/frigate-hass-card.js?v=1',
},
]);
await issue.detectStatic(hass);
expect(issue.hasIssue()).toBe(true);
});
it('should not detect when only advanced-camera-card exists', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
setupHASSResources(hass, [
{
id: '1',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
await issue.detectStatic(hass);
expect(issue.hasIssue()).toBe(false);
});
it('should handle invalid resource data', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
vi.mocked(hass.callWS).mockResolvedValue('not-an-array');
await issue.detectStatic(hass);
expect(issue.hasIssue()).toBe(false);
});
it('should handle websocket failure', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
vi.mocked(hass.callWS).mockRejectedValue(new Error('connection lost'));
await issue.detectStatic(hass);
expect(issue.hasIssue()).toBe(false);
});
it('should handle missing user', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS();
Object.defineProperty(hass, 'user', { value: undefined });
await issue.detectStatic(hass);
expect(issue.hasIssue()).toBe(false);
});
});
describe('getIssue', () => {
it('should return controls and link when both resources exist', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
setupHASSResources(hass, [
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
await issue.detectStatic(hass);
const result = issue.getIssue();
expect(result).not.toBeNull();
expect(result?.notification.controls).toHaveLength(1);
expect(result?.notification.link).toBeDefined();
});
it('should return link without controls when only legacy exists', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
setupHASSResources(hass, [
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
]);
await issue.detectStatic(hass);
const result = issue.getIssue();
expect(result).not.toBeNull();
expect(result?.notification.link).toBeDefined();
expect(result?.notification.controls).toBeUndefined();
});
it('should return null when no result', () => {
const issue = new LegacyResourceIssue();
expect(issue.getIssue()).toBeNull();
});
});
describe('fix', () => {
it('should remove legacy resources when correct resource exists', async () => {
const onChange = vi.fn();
const issue = new LegacyResourceIssue(onChange);
const hass = createHASS(undefined, createUser({ is_admin: true }));
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
vi.mocked(hass.callWS).mockResolvedValueOnce([
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
await issue.detectStatic(hass);
vi.mocked(hass.callWS)
.mockResolvedValueOnce(undefined)
.mockResolvedValueOnce([
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
const result = await issue.fix(hass);
expect(result).toBe(true);
expect(hass.callWS).toBeCalledWith(
expect.objectContaining({
type: 'lovelace/resources/delete',
resource_id: '1',
}),
);
expect(issue.hasIssue()).toBe(false);
expect(onChange).toBeCalled();
});
it('should not fix when only legacy resource exists', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
setupHASSResources(hass, [
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
]);
await issue.detectStatic(hass);
const result = await issue.fix(hass);
expect(result).toBe(false);
});
it('should not fix for non-admin', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: false }));
const result = await issue.fix(hass);
expect(result).toBe(false);
});
it('should return false on websocket failure during fix', async () => {
const onChange = vi.fn();
const issue = new LegacyResourceIssue(onChange);
const hass = createHASS(undefined, createUser({ is_admin: true }));
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
vi.mocked(hass.callWS).mockResolvedValueOnce([
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
await issue.detectStatic(hass);
vi.mocked(hass.callWS).mockRejectedValue(new Error('connection lost'));
const result = await issue.fix(hass);
expect(result).toBe(false);
expect(onChange).not.toBeCalled();
});
it('should return false when the verification fetch silently fails after a successful delete', async () => {
const onChange = vi.fn();
const issue = new LegacyResourceIssue(onChange);
const hass = createHASS(undefined, createUser({ is_admin: true }));
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
// Initial detection: finds one legacy resource + one correct resource.
vi.mocked(hass.callWS).mockResolvedValueOnce([
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
await issue.detectStatic(hass);
// Delete succeeds; verification fetch fails. detectStatic silently
// swallows the WS error, so the fix path must not interpret the
// absence of a positive signal as success.
vi.mocked(hass.callWS)
.mockResolvedValueOnce(undefined)
.mockRejectedValueOnce(new Error('connection lost'));
const result = await issue.fix(hass);
expect(result).toBe(false);
expect(onChange).not.toBeCalled();
});
it('should return false when re-detection still finds legacy resource', async () => {
const onChange = vi.fn();
const issue = new LegacyResourceIssue(onChange);
const hass = createHASS(undefined, createUser({ is_admin: true }));
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
vi.mocked(hass.callWS).mockResolvedValueOnce([
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
await issue.detectStatic(hass);
// Delete succeeds, but re-detection still finds the legacy resource.
vi.mocked(hass.callWS)
.mockResolvedValueOnce(undefined)
.mockResolvedValueOnce([
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
const result = await issue.fix(hass);
expect(result).toBe(false);
expect(onChange).not.toBeCalled();
});
it('should fix multiple legacy resources', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
vi.mocked(hass.callWS).mockResolvedValueOnce([
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
{ id: '3', type: 'module', url: '/local/frigate-hass-card.js' },
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
await issue.detectStatic(hass);
vi.mocked(hass.callWS)
.mockResolvedValueOnce(undefined)
.mockResolvedValueOnce(undefined)
.mockResolvedValueOnce([
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
expect(await issue.fix(hass)).toBe(true);
});
});
describe('getResourcePath fallback', () => {
it('should handle invalid URLs by stripping query string', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
vi.mocked(hass.hassUrl).mockReturnValue('not-a-valid-url');
vi.mocked(hass.callWS).mockResolvedValue([
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js?v=1',
},
]);
await issue.detectStatic(hass);
expect(issue.hasIssue()).toBe(true);
});
it('should handle invalid URLs without query string', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
vi.mocked(hass.hassUrl).mockReturnValue('not-a-valid-url');
vi.mocked(hass.callWS).mockResolvedValue([
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
]);
await issue.detectStatic(hass);
expect(issue.hasIssue()).toBe(true);
});
});
describe('callback action', () => {
const getCallback = (
issue: LegacyResourceIssue,
): ((api: unknown) => Promise<void>) | null => {
const result = issue.getIssue();
const action = result?.notification.controls?.[0]?.actions?.tap_action;
if (action && 'callback' in action) {
return (action as { callback: (api: unknown) => Promise<void> }).callback;
}
return null;
};
it('should call fix via the notification control action', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
vi.mocked(hass.callWS).mockResolvedValueOnce([
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
await issue.detectStatic(hass);
const callback = getCallback(issue);
expect(callback).toBeDefined();
const api = createCardAPI();
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
vi.mocked(hass.callWS)
.mockResolvedValueOnce(undefined)
.mockResolvedValueOnce([
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
await callback?.(api);
expect(hass.callWS).toBeCalledWith(
expect.objectContaining({
type: 'lovelace/resources/delete',
}),
);
});
it('should handle missing hass in callback', async () => {
const issue = new LegacyResourceIssue();
const hass = createHASS(undefined, createUser({ is_admin: true }));
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
vi.mocked(hass.callWS).mockResolvedValueOnce([
{
id: '1',
type: 'module',
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
},
{
id: '2',
type: 'module',
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
},
]);
await issue.detectStatic(hass);
const callback = getCallback(issue);
expect(callback).toBeDefined();
const api = createCardAPI();
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(null);
await callback?.(api);
});
});
});
@@ -0,0 +1,623 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mock } from 'vitest-mock-extended';
import { MediaLoadIssue } from '../../../../src/card-controller/issues/issues/media-load';
import { InternalCallbackActionConfig } from '../../../../src/config/schema/actions/custom/internal';
import { View } from '../../../../src/view/view';
import { createCardAPI, createMediaLoadedInfo } from '../../../test-utils';
import { IMAGE_VIEW_TARGET_ID_SENTINEL } from '../../../../src/view/target-id';
const createAPI = () => createCardAPI();
// @vitest-environment jsdom
describe('MediaLoadIssue', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('should have correct key', () => {
const issue = new MediaLoadIssue(createAPI());
expect(issue.key).toBe('media_load');
});
describe('detectDynamic', () => {
it.each([
['live' as const],
['clip' as const],
['folder' as const],
['media' as const],
['snapshot' as const],
['recording' as const],
['review' as const],
])('should start timer when view is %s and not loaded', (view) => {
const onChange = vi.fn();
const issue = new MediaLoadIssue(createAPI(), onChange);
issue.detectDynamic({ targetID: 'target-1', view });
expect(issue.hasIssue()).toBe(false);
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(true);
expect(onChange).toBeCalled();
});
it('should not start timer when targetID is null (no provider rendering)', () => {
const issue = new MediaLoadIssue(createAPI());
// Media view but no targetID, e.g. viewer showing "No media to display"
// instead of mounting a provider.
issue.detectDynamic({ view: 'media' });
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(false);
});
it('should deactivate when targetID becomes null', () => {
const issue = new MediaLoadIssue(createAPI());
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(true);
// Target cleared (e.g. switched to a view with no media provider).
issue.detectDynamic({ view: 'live' });
expect(issue.hasIssue()).toBe(false);
});
it('should not start timer when view is not a media view', () => {
const issue = new MediaLoadIssue(createAPI());
issue.detectDynamic({ view: 'timeline' });
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(false);
});
it('should not start timer when view is undefined', () => {
const issue = new MediaLoadIssue(createAPI());
issue.detectDynamic({});
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(false);
});
it('should not start timer when media is loaded', () => {
const issue = new MediaLoadIssue(createAPI());
issue.detectDynamic({ view: 'live', mediaLoadedInfo: createMediaLoadedInfo() });
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(false);
});
it('should clear timeout when media loads', () => {
const issue = new MediaLoadIssue(createAPI());
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(5000);
issue.detectDynamic({ view: 'live', mediaLoadedInfo: createMediaLoadedInfo() });
vi.advanceTimersByTime(5000);
expect(issue.hasIssue()).toBe(false);
});
it('should clear timeout when view changes to a non-media view', () => {
const issue = new MediaLoadIssue(createAPI());
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(5000);
issue.detectDynamic({ view: 'timeline' });
vi.advanceTimersByTime(5000);
expect(issue.hasIssue()).toBe(false);
});
it('should remain active across media views for the same target', () => {
const issue = new MediaLoadIssue(createAPI());
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(true);
// Same target, different media view — issue stays active.
issue.detectDynamic({ targetID: 'camera-1', view: 'clip' });
expect(issue.hasIssue()).toBe(true);
});
it('should deactivate when target changes to non-errored target', () => {
const issue = new MediaLoadIssue(createAPI());
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(true);
// Switch to camera-2 which has no error — should deactivate and start
// a fresh timer for the new target.
issue.detectDynamic({ targetID: 'camera-2', view: 'live' });
expect(issue.hasIssue()).toBe(false);
// camera-2 gets its own timeout window.
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(true);
});
it('should stay active when target changes to errored target', () => {
const issue = new MediaLoadIssue(createAPI());
issue.trigger({ targetID: 'camera-1' });
issue.trigger({ targetID: 'camera-2' });
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
expect(issue.hasIssue()).toBe(true);
// Switch to camera-2 which also has an error — should stay active.
issue.detectDynamic({ targetID: 'camera-2', view: 'live' });
expect(issue.hasIssue()).toBe(true);
});
it('should clear timed-out state when media loads', () => {
const issue = new MediaLoadIssue(createAPI());
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(true);
issue.detectDynamic({ view: 'live', mediaLoadedInfo: createMediaLoadedInfo() });
expect(issue.hasIssue()).toBe(false);
});
it('should restart timer when target changes', () => {
const onChange = vi.fn();
const issue = new MediaLoadIssue(createAPI(), onChange);
issue.detectDynamic({
targetID: 'camera-1',
view: 'live',
});
vi.advanceTimersByTime(5000);
// Switch to camera-2: timer restarts from 0 for the new target.
issue.detectDynamic({
targetID: 'camera-2',
view: 'live',
});
// 5 more seconds is not enough for the new 10s timer.
vi.advanceTimersByTime(5000);
expect(issue.hasIssue()).toBe(false);
// Full 10s from camera-2's timer start.
vi.advanceTimersByTime(5000);
expect(issue.hasIssue()).toBe(true);
expect(onChange).toBeCalledTimes(1);
});
it('should not restart timer for same target while running', () => {
const onChange = vi.fn();
const issue = new MediaLoadIssue(createAPI(), onChange);
issue.detectDynamic({
targetID: 'camera-1',
view: 'live',
});
vi.advanceTimersByTime(5000);
// Same target again: timer should continue, not restart.
issue.detectDynamic({
targetID: 'camera-1',
view: 'live',
});
// 5 more seconds completes the original 10s timer.
vi.advanceTimersByTime(5000);
expect(issue.hasIssue()).toBe(true);
expect(onChange).toBeCalledTimes(1);
});
it('should not restart timer when targetID is undefined and matches', () => {
const onChange = vi.fn();
const issue = new MediaLoadIssue(createAPI(), onChange);
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(5000);
// Same undefined target: timer should continue.
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(5000);
expect(issue.hasIssue()).toBe(true);
expect(onChange).toBeCalledTimes(1);
});
it('should not restart timer if already timed out', () => {
const onChange = vi.fn();
const issue = new MediaLoadIssue(createAPI(), onChange);
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(10000);
expect(onChange).toBeCalledTimes(1);
// Calling detectDynamic again should not restart timer.
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(10000);
expect(onChange).toBeCalledTimes(1);
});
});
describe('trigger', () => {
it('should activate immediately when target has error and view is a media view', () => {
const issue = new MediaLoadIssue(createAPI());
issue.trigger({ targetID: 'camera-1' });
issue.detectDynamic({
targetID: 'camera-1',
view: 'live',
});
expect(issue.hasIssue()).toBe(true);
});
it('should not activate with only a trigger', () => {
const issue = new MediaLoadIssue(createAPI());
issue.trigger({ targetID: 'camera-1' });
expect(issue.hasIssue()).toBe(false);
});
it('should clear target error when media loads', () => {
const issue = new MediaLoadIssue(createAPI());
issue.trigger({ targetID: 'camera-1' });
issue.detectDynamic({
targetID: 'camera-1',
view: 'live',
});
expect(issue.hasIssue()).toBe(true);
// Media loaded clears the error for this target.
issue.detectDynamic({
targetID: 'camera-1',
view: 'live',
mediaLoadedInfo: createMediaLoadedInfo(),
});
// Target error was cleared by the successful load, so this unloaded state
// falls back to the timer (issue would not activate until after the
// timer is reached).
issue.detectDynamic({
targetID: 'camera-1',
view: 'live',
});
expect(issue.hasIssue()).toBe(false);
});
it('should not activate for a different target', () => {
const issue = new MediaLoadIssue(createAPI());
issue.trigger({ targetID: 'camera-1' });
issue.detectDynamic({
targetID: 'camera-2',
view: 'live',
});
// camera-2 has no error, so it falls back to timeout behavior.
expect(issue.hasIssue()).toBe(false);
});
});
describe('getNotification', () => {
it('should return notification regardless of active state', () => {
const issue = new MediaLoadIssue(createAPI());
const notification = issue.getNotification();
expect(notification).toEqual(
expect.objectContaining({
heading: expect.objectContaining({
text: expect.any(String),
}),
link: expect.objectContaining({
url: expect.any(String),
}),
}),
);
});
it('should include metadata for errored targets', () => {
const issue = new MediaLoadIssue(createAPI());
issue.trigger({ targetID: 'camera.office' });
const notification = issue.getNotification();
expect(notification.metadata).toEqual([
expect.objectContaining({ text: 'camera.office', icon: 'mdi:cctv' }),
]);
});
it('should include the pending timer target in metadata', () => {
const issue = new MediaLoadIssue(createAPI());
// Start a load timer (no explicit error yet, just slow-loading).
issue.detectDynamic({ targetID: 'camera.garden', view: 'live' });
const notification = issue.getNotification();
expect(notification.metadata).toEqual([
expect.objectContaining({ text: 'camera.garden', icon: 'mdi:cctv' }),
]);
});
it('should use camera title when available', () => {
const api = createAPI();
vi.mocked(api.getCameraManager().getCameraMetadata).mockReturnValue({
title: 'Office',
icon: { icon: 'mdi:cctv' },
});
const issue = new MediaLoadIssue(api);
issue.trigger({ targetID: 'camera.office' });
const notification = issue.getNotification();
expect(notification.metadata).toEqual([
expect.objectContaining({ text: 'Office' }),
]);
});
it('should use localized label and image icon for the image-view sentinel', () => {
const issue = new MediaLoadIssue(createAPI());
issue.trigger({ targetID: IMAGE_VIEW_TARGET_ID_SENTINEL });
const notification = issue.getNotification();
expect(notification.metadata).toEqual([
expect.objectContaining({ text: 'Image', icon: 'mdi:image' }),
]);
});
it('should include a retry control with wired callback', async () => {
const api = createCardAPI();
const issue = new MediaLoadIssue(api);
const control = issue.getNotification().controls?.[0];
expect(control).toMatchObject({ icon: 'mdi:refresh', dismiss: true });
const tapAction = control?.actions?.tap_action as InternalCallbackActionConfig;
await tapAction.callback(api);
expect(api.getIssueManager().retry).toBeCalledWith('media_load', true);
});
});
describe('getIssue', () => {
it('should return result when timed out', () => {
const issue = new MediaLoadIssue(createAPI());
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(10000);
const result = issue.getIssue();
expect(result).toEqual(
expect.objectContaining({
icon: 'mdi:cctv-off',
severity: 'high',
notification: expect.objectContaining({
link: expect.objectContaining({
url: expect.any(String),
}),
}),
}),
);
});
it('should return null when not timed out', () => {
const issue = new MediaLoadIssue(createAPI());
expect(issue.getIssue()).toBeNull();
});
});
describe('needsRetry', () => {
it('should return true when issue is active', () => {
const issue = new MediaLoadIssue(createAPI());
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(10000);
expect(issue.needsRetry()).toBe(true);
});
it('should return false when issue is not active', () => {
const issue = new MediaLoadIssue(createAPI());
expect(issue.needsRetry()).toBe(false);
});
});
describe('retry', () => {
it('should keep issue active after retry so error stays visible', () => {
const onChange = vi.fn();
const issue = new MediaLoadIssue(createAPI(), onChange);
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(true);
issue.retry();
// Issue remains active — no new 10s grace period. The error stays
// visible while the provider re-attempts loading underneath.
expect(issue.hasIssue()).toBe(true);
});
it('should return false when no targets have errors', () => {
const api = createAPI();
const issue = new MediaLoadIssue(api);
expect(issue.retry()).toBe(false);
});
it('should bump mediaEpoch for targets with errors and call setViewWithMergedContext', () => {
const api = createAPI();
vi.mocked(api.getViewManager().getView).mockReturnValue(mock<View>());
const issue = new MediaLoadIssue(api);
issue.trigger({ targetID: 'camera-1' });
issue.trigger({ targetID: 'media-1' });
const result = issue.retry();
expect(result).toEqual(false);
expect(api.getViewManager().setViewWithMergedContext).toBeCalledWith({
mediaEpoch: { 'camera-1': 1, 'media-1': 1 },
});
});
it('should bump mediaEpoch for the image-view sentinel', () => {
const api = createAPI();
vi.mocked(api.getViewManager().getView).mockReturnValue(mock<View>());
const issue = new MediaLoadIssue(api);
issue.trigger({ targetID: IMAGE_VIEW_TARGET_ID_SENTINEL });
const result = issue.retry();
expect(result).toEqual(false);
expect(api.getViewManager().setViewWithMergedContext).toBeCalledWith({
mediaEpoch: { [IMAGE_VIEW_TARGET_ID_SENTINEL]: 1 },
});
});
it('should increment existing epoch values from current view context', () => {
const api = createAPI();
vi.mocked(api.getViewManager().getView).mockReturnValue(
mock<View>({ context: { mediaEpoch: { 'camera-1': 5, 'camera-2': 3 } } }),
);
const issue = new MediaLoadIssue(api);
issue.trigger({ targetID: 'camera-1' });
const result = issue.retry();
expect(result).toEqual(false);
expect(api.getViewManager().setViewWithMergedContext).toBeCalledWith({
mediaEpoch: { 'camera-1': 6, 'camera-2': 3 },
});
});
it('should include pending timer target in retry', () => {
const api = createAPI();
vi.mocked(api.getViewManager().getView).mockReturnValue(mock<View>());
const issue = new MediaLoadIssue(api);
// Start the timer for camera-1 (not yet timed out).
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
issue.retry();
expect(api.getViewManager().setViewWithMergedContext).toBeCalledWith({
mediaEpoch: { 'camera-1': 1 },
});
});
it('should keep errored targets and issue state after retry', () => {
const api = createAPI();
vi.mocked(api.getViewManager().getView).mockReturnValue(mock<View>());
const issue = new MediaLoadIssue(api);
issue.trigger({ targetID: 'camera-1' });
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
expect(issue.hasIssue()).toBe(true);
issue.retry();
// After retry, the issue stays active and the errored target is
// preserved — no new 10s grace period. If media:loaded fires, the
// existing _handleMediaLoaded path will clear everything.
expect(issue.hasIssue()).toBe(true);
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
expect(issue.hasIssue()).toBe(true);
});
});
describe('reset', () => {
it('should stop timer', () => {
const onChange = vi.fn();
const issue = new MediaLoadIssue(createAPI(), onChange);
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
issue.reset();
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(false);
expect(onChange).not.toBeCalled();
});
});
describe('suspend', () => {
it('should stop the pending-load timer so it cannot mature offscreen', () => {
const onChange = vi.fn();
const issue = new MediaLoadIssue(createAPI(), onChange);
// Enter loading state. Timer arms but has not yet fired.
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(5000);
expect(issue.hasIssue()).toBe(false);
// Card detaches: timer must stop.
issue.suspend();
// Full 10s later (plus margin) the timer has NOT matured — the user
// was offscreen and that time does not count against them.
vi.advanceTimersByTime(20000);
expect(issue.hasIssue()).toBe(false);
expect(onChange).not.toBeCalled();
});
it('should preserve an already-active issue across suspend', () => {
const issue = new MediaLoadIssue(createAPI());
// Issue activates (timeout fires).
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(10000);
expect(issue.hasIssue()).toBe(true);
// Card detaches — issue must remain visible on reattach.
issue.suspend();
expect(issue.hasIssue()).toBe(true);
});
it('should rearm a fresh timer window on resume via detectDynamic', () => {
const onChange = vi.fn();
const issue = new MediaLoadIssue(createAPI(), onChange);
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(5000);
issue.suspend();
// Reattach: the manager's resume() triggers evaluate() → detectDynamic.
// The target is still loading, so the timer arms with a fresh 10s
// window — not whatever was left when we suspended.
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
vi.advanceTimersByTime(9999);
expect(issue.hasIssue()).toBe(false);
vi.advanceTimersByTime(1);
expect(issue.hasIssue()).toBe(true);
expect(onChange).toBeCalled();
});
});
});
@@ -0,0 +1,150 @@
import { describe, expect, it } from 'vitest';
import { CardController } from '../../../../src/card-controller/controller';
import { MediaQueryIssue } from '../../../../src/card-controller/issues/issues/media-query';
import { InternalCallbackActionConfig } from '../../../../src/config/schema/actions/custom/internal';
import { createCardAPI } from '../../../test-utils';
const createIssue = (): {
issue: MediaQueryIssue;
api: CardController;
} => {
const api = createCardAPI();
const issue = new MediaQueryIssue(api);
return { issue, api };
};
describe('MediaQueryIssue', () => {
it('should have correct key', () => {
const { issue } = createIssue();
expect(issue.key).toBe('media_query');
});
it('should report no issue when untriggered', () => {
const { issue } = createIssue();
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
it('should report an issue after trigger with an error', () => {
const { issue } = createIssue();
issue.trigger({ error: new Error('query failed') });
expect(issue.hasIssue()).toBe(true);
});
it('should treat a triggered null/undefined error as no issue', () => {
const { issue } = createIssue();
issue.trigger({ error: undefined });
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
expect(issue.needsRetry()).toBe(false);
});
it('should return expected shape from getIssue when triggered with an error', () => {
const { issue } = createIssue();
issue.trigger({ error: new Error('media query failed') });
const result = issue.getIssue();
expect(result).toEqual(
expect.objectContaining({
icon: 'mdi:alert',
severity: 'high',
notification: expect.objectContaining({
body: expect.objectContaining({
text: 'media query failed',
}),
}),
}),
);
});
describe('getNotification', () => {
it('should return null when no error is set', () => {
const { issue } = createIssue();
expect(issue.getNotification()).toBeNull();
});
it('should return notification with retry control when triggered with an error', () => {
const { issue } = createIssue();
issue.trigger({ error: new Error('query failed') });
const notification = issue.getNotification();
expect(notification?.controls).toHaveLength(1);
expect(notification?.controls?.[0]).toMatchObject({
icon: 'mdi:refresh',
dismiss: true,
});
});
it('should call manager.retry with the issue key from retry control callback', async () => {
const { issue, api } = createIssue();
issue.trigger({ error: new Error('query failed') });
const control = issue.getNotification()?.controls?.[0];
const tapAction = control?.actions?.tap_action as InternalCallbackActionConfig;
await tapAction.callback(api);
expect(api.getIssueManager().retry).toBeCalledWith('media_query', true);
});
});
describe('needsRetry', () => {
it('should return true after trigger with an error', () => {
const { issue } = createIssue();
issue.trigger({ error: new Error('query failed') });
expect(issue.needsRetry()).toBe(true);
});
it('should return false when not triggered', () => {
const { issue } = createIssue();
expect(issue.needsRetry()).toBe(false);
});
});
describe('retry', () => {
it('should return requery action and clear error and needsRetry', () => {
const { issue, api } = createIssue();
issue.trigger({ error: new Error('query failed') });
const result = issue.retry();
expect(result).toEqual(true);
expect(api.getViewManager().setViewByParametersWithNewQuery).toBeCalled();
expect(issue.needsRetry()).toBe(false);
expect(issue.hasIssue()).toBe(false);
});
it('should return null when needsRetry is false', () => {
const { issue } = createIssue();
const result = issue.retry();
expect(result).toBe(false);
});
});
it('should clear the issue after reset', () => {
const { issue } = createIssue();
issue.trigger({ error: new Error('oops') });
expect(issue.hasIssue()).toBe(true);
issue.reset();
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
it('should clear needsRetry after reset', () => {
const { issue } = createIssue();
issue.trigger({ error: new Error('oops') });
expect(issue.needsRetry()).toBe(true);
issue.reset();
expect(issue.needsRetry()).toBe(false);
});
});
@@ -0,0 +1,109 @@
import { describe, expect, it, vi } from 'vitest';
import { mock } from 'vitest-mock-extended';
import { CardController } from '../../../../src/card-controller/controller';
import { ViewIncompatibleIssue } from '../../../../src/card-controller/issues/issues/view-incompatible';
import { AdvancedCameraCardError } from '../../../../src/types';
import { View } from '../../../../src/view/view';
import { createCardAPI } from '../../../test-utils';
describe('ViewIncompatibleIssue', () => {
const createAPI = (hasView = false): CardController => {
const api = createCardAPI();
vi.mocked(api.getViewManager().getView).mockReturnValue(
hasView ? mock<View>() : null,
);
return api;
};
it('should have correct key', () => {
const issue = new ViewIncompatibleIssue(createAPI());
expect(issue.key).toBe('view_incompatible');
});
it('should report no issue when untriggered', () => {
const issue = new ViewIncompatibleIssue(createAPI());
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
it('should report an issue after trigger', () => {
const issue = new ViewIncompatibleIssue(createAPI());
issue.trigger({ error: new Error('boom') });
expect(issue.hasIssue()).toBe(true);
});
it('should treat a triggered null/undefined error as no issue', () => {
const issue = new ViewIncompatibleIssue(createAPI());
issue.trigger({ error: undefined });
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
describe('isFullCardIssue', () => {
it('should return true when no view is set', () => {
const issue = new ViewIncompatibleIssue(createAPI(false));
expect(issue.isFullCardIssue()).toBe(true);
});
it('should return false when a view is set', () => {
const issue = new ViewIncompatibleIssue(createAPI(true));
expect(issue.isFullCardIssue()).toBe(false);
});
});
describe('getIssue', () => {
it('should return a notification with heading, body, and no retry control', () => {
const issue = new ViewIncompatibleIssue(createAPI());
issue.trigger({ error: new Error('boom') });
expect(issue.getIssue()).toEqual({
icon: 'mdi:video-off',
severity: 'high',
notification: {
heading: {
text: 'View not supported',
icon: 'mdi:video-off',
severity: 'high',
},
body: { text: 'The selected camera or media does not support this view' },
},
});
});
it('should include error context on AdvancedCameraCardError', () => {
const issue = new ViewIncompatibleIssue(createAPI());
issue.trigger({
error: new AdvancedCameraCardError('err', {
view: 'snapshot',
camera: 'cam.office',
}),
});
const result = issue.getIssue();
expect(result?.notification.context).toEqual([
expect.stringContaining('view: snapshot'),
]);
});
it('should omit context on plain errors', () => {
const issue = new ViewIncompatibleIssue(createAPI());
issue.trigger({ error: new Error('plain') });
const result = issue.getIssue();
expect(result?.notification.context).toBeUndefined();
});
});
it('should clear the issue after reset', () => {
const issue = new ViewIncompatibleIssue(createAPI());
issue.trigger({ error: new Error('boom') });
expect(issue.hasIssue()).toBe(true);
issue.reset();
expect(issue.hasIssue()).toBe(false);
expect(issue.getIssue()).toBeNull();
});
});
@@ -0,0 +1,25 @@
// @vitest-environment jsdom
import { describe, expect, it } from 'vitest';
import { createRetryControl } from '../../../src/card-controller/issues/retry-control';
import { InternalCallbackActionConfig } from '../../../src/config/schema/actions/custom/internal';
import { createCardAPI } from '../../test-utils';
describe('createRetryControl', () => {
it('should return a control with expected icon, tooltip, and dismiss', () => {
const control = createRetryControl('media_load');
expect(control.icon).toBe('mdi:refresh');
expect(control.tooltip).toBe('Retry');
expect(control.dismiss).toBe(true);
});
it('should call manager.retry with the issue key when the callback executes', async () => {
const api = createCardAPI();
const control = createRetryControl('media_query');
const tapAction = control.actions?.tap_action as InternalCallbackActionConfig;
await tapAction.callback(api);
expect(api.getIssueManager().retry).toBeCalledWith('media_query', true);
});
});
@@ -0,0 +1,555 @@
import { assert, beforeEach, describe, expect, it, vi } from 'vitest';
import { mock } from 'vitest-mock-extended';
import { IssueStateManager } from '../../../src/card-controller/issues/state-manager';
import { Issue, IssueDescription } from '../../../src/card-controller/issues/types';
import { createHASS } from '../../test-utils';
const createIssueDescription = (
overrides?: Partial<IssueDescription>,
): IssueDescription => ({
icon: 'mdi:test',
severity: 'high',
notification: {
heading: {
text: 'Test heading',
icon: 'mdi:test',
severity: 'high',
},
body: { text: 'Test text' },
},
...overrides,
});
describe('IssueStateManager', () => {
let mockConfigUpgrade: Issue;
let mockLegacyResource: Issue;
let mockMediaLoad: Issue;
const createManager = (issues?: Issue[]): IssueStateManager => {
const manager = new IssueStateManager();
for (const issue of issues ?? [
mockConfigUpgrade,
mockLegacyResource,
mockMediaLoad,
]) {
manager.addIssue(issue);
}
return manager;
};
beforeEach(() => {
vi.resetAllMocks();
mockConfigUpgrade = mock<Issue>({ key: 'config_upgrade' });
mockLegacyResource = mock<Issue>({ key: 'legacy_resource' });
mockMediaLoad = mock<Issue>({ key: 'media_load' });
});
it('should register all provided issues on construction', () => {
const manager = createManager();
const presence = manager.getIssuePresence();
expect(presence.has('config_upgrade')).toBe(false);
expect(presence.has('legacy_resource')).toBe(false);
expect(presence.has('media_load')).toBe(false);
});
describe('detectStatic', () => {
it('should call detectStatic on all issues', async () => {
const manager = createManager();
const hass = createHASS();
await manager.detectStatic(hass);
assert(mockConfigUpgrade.detectStatic);
assert(mockLegacyResource.detectStatic);
assert(mockMediaLoad.detectStatic);
expect(mockConfigUpgrade.detectStatic).toBeCalledWith(hass);
expect(mockLegacyResource.detectStatic).toBeCalledWith(hass);
expect(mockMediaLoad.detectStatic).toBeCalledWith(hass);
});
});
describe('trigger', () => {
it('should call trigger on the matching issue', () => {
const manager = createManager();
manager.trigger('media_load', { targetID: 'cam1' });
assert(mockMediaLoad.trigger);
expect(mockMediaLoad.trigger).toBeCalledWith({ targetID: 'cam1' });
});
it('should do nothing for unknown key', () => {
const manager = createManager();
manager.trigger('unknown' as never, {} as never);
assert(mockMediaLoad.trigger);
expect(mockMediaLoad.trigger).not.toBeCalled();
});
});
describe('detectDynamic', () => {
it('should call detectDynamic on issues with the given state', () => {
const manager = createManager();
manager.detectDynamic({ view: 'live' });
assert(mockMediaLoad.detectDynamic);
expect(mockMediaLoad.detectDynamic).toBeCalledWith({ view: 'live' });
});
});
describe('getFullCardIssue', () => {
it('should return first full-card issue', () => {
const result = createIssueDescription();
vi.mocked(mockMediaLoad.hasIssue).mockReturnValue(true);
assert(mockMediaLoad.isFullCardIssue);
vi.mocked(mockMediaLoad.isFullCardIssue).mockReturnValue(true);
vi.mocked(mockMediaLoad.getIssue).mockReturnValue(result);
const manager = createManager();
expect(manager.getFullCardIssue()).toBe(result);
});
it('should return null when only popup issues exist', () => {
vi.mocked(mockMediaLoad.hasIssue).mockReturnValue(true);
assert(mockMediaLoad.isFullCardIssue);
vi.mocked(mockMediaLoad.isFullCardIssue).mockReturnValue(false);
const manager = createManager();
expect(manager.getFullCardIssue()).toBeNull();
});
it('should skip inactive full-card issues', () => {
vi.mocked(mockMediaLoad.hasIssue).mockReturnValue(false);
const manager = createManager();
expect(manager.getFullCardIssue()).toBeNull();
});
});
describe('hasFullCardIssue', () => {
it('should return true when full-card issue exists', () => {
vi.mocked(mockMediaLoad.hasIssue).mockReturnValue(true);
assert(mockMediaLoad.isFullCardIssue);
vi.mocked(mockMediaLoad.isFullCardIssue).mockReturnValue(true);
vi.mocked(mockMediaLoad.getIssue).mockReturnValue(createIssueDescription());
expect(createManager().hasFullCardIssue()).toBe(true);
});
it('should return false when no full-card issues', () => {
expect(createManager().hasFullCardIssue()).toBe(false);
});
});
describe('getIssueDescriptions', () => {
it('should return results for active issues', () => {
const result = createIssueDescription();
vi.mocked(mockConfigUpgrade.getIssue).mockReturnValue(result);
const manager = createManager();
expect(manager.getIssueDescriptions()).toEqual([
{ key: 'config_upgrade', issue: result },
]);
});
it('should return empty array when no issues active', () => {
expect(createManager().getIssueDescriptions()).toEqual([]);
});
});
describe('getIssuePresence', () => {
it('should return a map keyed by issue key with the current description as value', () => {
const description = createIssueDescription();
vi.mocked(mockConfigUpgrade.getIssue).mockReturnValue(description);
vi.mocked(mockLegacyResource.getIssue).mockReturnValue(null);
const manager = createManager();
const presence = manager.getIssuePresence();
expect(presence.has('config_upgrade')).toBe(true);
expect(presence.get('config_upgrade')).toBe(description);
expect(presence.has('legacy_resource')).toBe(false);
});
});
describe('getNotification', () => {
it('should return notification for an issue', () => {
const notification = { body: { text: 'test' } };
mockMediaLoad.getNotification = vi.fn().mockReturnValue(notification);
const manager = createManager();
expect(manager.getNotification('media_load')).toBe(notification);
});
it('should return null for unknown key', () => {
expect(createManager().getNotification('unknown' as never)).toBeNull();
});
});
describe('retry', () => {
it('should call retry on issues that want retry with non-exclusive result', () => {
assert(mockMediaLoad.needsRetry);
assert(mockMediaLoad.retry);
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
vi.mocked(mockMediaLoad.retry).mockReturnValue(false);
const manager = createManager();
manager.retry();
expect(mockMediaLoad.retry).toBeCalled();
});
it('should call retry on issues that want retry with exclusive result', () => {
assert(mockMediaLoad.needsRetry);
assert(mockMediaLoad.retry);
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
vi.mocked(mockMediaLoad.retry).mockReturnValue(true);
createManager().retry();
expect(mockMediaLoad.retry).toBeCalled();
});
it('should not call retry on issues that do not want retry', () => {
assert(mockMediaLoad.needsRetry);
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(false);
const manager = createManager();
manager.retry();
assert(mockMediaLoad.retry);
expect(mockMediaLoad.retry).not.toBeCalled();
});
it('should stop after exclusive result and not call retry on subsequent issues', () => {
// configUpgrade returns exclusive (true) → loop should stop.
// mediaLoad is registered after, so its retry should not be called.
assert(mockConfigUpgrade.needsRetry);
assert(mockConfigUpgrade.retry);
vi.mocked(mockConfigUpgrade.needsRetry).mockReturnValue(true);
vi.mocked(mockConfigUpgrade.retry).mockReturnValue(true);
assert(mockMediaLoad.needsRetry);
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
const manager = createManager();
manager.retry();
expect(mockConfigUpgrade.retry).toBeCalled();
assert(mockMediaLoad.retry);
expect(mockMediaLoad.retry).not.toBeCalled();
});
it('should continue after non-exclusive result and call retry on subsequent issues', () => {
// configUpgrade returns non-exclusive (false) → loop should continue.
assert(mockConfigUpgrade.needsRetry);
assert(mockConfigUpgrade.retry);
vi.mocked(mockConfigUpgrade.needsRetry).mockReturnValue(true);
vi.mocked(mockConfigUpgrade.retry).mockReturnValue(false);
assert(mockMediaLoad.needsRetry);
assert(mockMediaLoad.retry);
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
vi.mocked(mockMediaLoad.retry).mockReturnValue(false);
const manager = createManager();
manager.retry();
expect(mockConfigUpgrade.retry).toBeCalled();
expect(mockMediaLoad.retry).toBeCalled();
});
});
describe('retry with key', () => {
it('should call retry on the matching issue when needsRetry is true', () => {
assert(mockMediaLoad.needsRetry);
assert(mockMediaLoad.retry);
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
vi.mocked(mockMediaLoad.retry).mockReturnValue(false);
createManager().retry('media_load');
expect(mockMediaLoad.retry).toBeCalled();
});
it('should not call retry on the matching issue when needsRetry is false', () => {
assert(mockMediaLoad.needsRetry);
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(false);
createManager().retry('media_load');
assert(mockMediaLoad.retry);
expect(mockMediaLoad.retry).not.toBeCalled();
});
it('should call retry when force is true even if needsRetry is false', () => {
assert(mockMediaLoad.needsRetry);
assert(mockMediaLoad.retry);
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(false);
vi.mocked(mockMediaLoad.retry).mockReturnValue(false);
createManager().retry('media_load', true);
expect(mockMediaLoad.retry).toBeCalled();
});
it('should do nothing for unknown key', () => {
createManager().retry('unknown' as never);
assert(mockMediaLoad.retry);
expect(mockMediaLoad.retry).not.toBeCalled();
});
});
describe('needsRetry', () => {
it('should return true when issues want retry', () => {
assert(mockMediaLoad.needsRetry);
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
expect(createManager().needsRetry()).toBe(true);
});
it('should return false when no issues want retry', () => {
expect(createManager().needsRetry()).toBe(false);
});
});
describe('logging', () => {
it('should log on static detection when issue is active', async () => {
const spy = vi.spyOn(console, 'warn').mockReturnValue();
const result = createIssueDescription({
notification: { body: { text: 'Legacy issue' } },
});
vi.mocked(mockLegacyResource.hasIssue).mockReturnValue(true);
vi.mocked(mockLegacyResource.getIssue).mockReturnValue(result);
const manager = createManager();
await manager.detectStatic(createHASS());
expect(spy).toBeCalledWith(
'Advanced Camera Card [issue=legacy_resource]: Legacy issue',
);
spy.mockRestore();
});
it('should log on dynamic evaluation when issue becomes active', () => {
const spy = vi.spyOn(console, 'warn').mockReturnValue();
const result = createIssueDescription({
notification: { body: { text: 'Stream issue' } },
});
vi.mocked(mockMediaLoad.hasIssue).mockReturnValueOnce(false).mockReturnValue(true);
vi.mocked(mockMediaLoad.getIssue).mockReturnValue(result);
const manager = createManager();
manager.detectDynamic({ view: 'live' });
expect(spy).toBeCalledWith(
'Advanced Camera Card [issue=media_load]: Stream issue',
);
spy.mockRestore();
});
it('should log on trigger when the issue becomes active', () => {
const spy = vi.spyOn(console, 'warn').mockReturnValue();
const result = createIssueDescription({
notification: { body: { text: 'Triggered' } },
});
vi.mocked(mockMediaLoad.getIssue).mockReturnValue(result);
const manager = createManager();
manager.trigger('media_load', { targetID: 'cam1' });
expect(spy).toBeCalledWith('Advanced Camera Card [issue=media_load]: Triggered');
spy.mockRestore();
});
it('should not log on trigger when the issue stays inactive', () => {
const spy = vi.spyOn(console, 'warn').mockReturnValue();
vi.mocked(mockMediaLoad.getIssue).mockReturnValue(null);
const manager = createManager();
manager.trigger('media_load', { targetID: 'cam1' });
expect(spy).not.toBeCalled();
spy.mockRestore();
});
it('should not log on trigger for an unknown key', () => {
const spy = vi.spyOn(console, 'warn').mockReturnValue();
const manager = createManager();
manager.trigger('unknown' as never, {} as never);
expect(spy).not.toBeCalled();
spy.mockRestore();
});
it('should only log once per issue key', async () => {
const spy = vi.spyOn(console, 'warn').mockReturnValue();
const result = createIssueDescription({
notification: { body: { text: 'Repeated' } },
});
vi.mocked(mockLegacyResource.hasIssue).mockReturnValue(true);
vi.mocked(mockLegacyResource.getIssue).mockReturnValue(result);
const manager = createManager();
await manager.detectStatic(createHASS());
await manager.detectStatic(createHASS());
expect(spy).toBeCalledTimes(1);
spy.mockRestore();
});
it('should not log when issue has no result', async () => {
const spy = vi.spyOn(console, 'warn').mockReturnValue();
vi.mocked(mockLegacyResource.hasIssue).mockReturnValue(false);
const manager = createManager();
await manager.detectStatic(createHASS());
expect(spy).not.toBeCalled();
spy.mockRestore();
});
it('should not log when issue result has no summarizable text', async () => {
const spy = vi.spyOn(console, 'warn').mockReturnValue();
// Notification has neither body.text nor heading.text
const result = createIssueDescription({
notification: {},
});
vi.mocked(mockLegacyResource.hasIssue).mockReturnValue(true);
vi.mocked(mockLegacyResource.getIssue).mockReturnValue(result);
const manager = createManager();
await manager.detectStatic(createHASS());
expect(spy).not.toBeCalled();
spy.mockRestore();
});
it('should log again after the issue clears and re-activates', async () => {
const spy = vi.spyOn(console, 'warn').mockReturnValue();
const first = createIssueDescription({
notification: { body: { text: 'First' } },
});
const second = createIssueDescription({
notification: { body: { text: 'Second' } },
});
vi.mocked(mockLegacyResource.getIssue)
.mockReturnValueOnce(first)
.mockReturnValueOnce(null)
.mockReturnValueOnce(second);
const manager = createManager();
// Activate → log First.
await manager.detectStatic(createHASS());
// Clear → drop dedupe entry.
await manager.detectStatic(createHASS());
// Re-activate with a different payload → log Second.
await manager.detectStatic(createHASS());
expect(spy).toBeCalledTimes(2);
expect(spy).toHaveBeenNthCalledWith(
1,
'Advanced Camera Card [issue=legacy_resource]: First',
);
expect(spy).toHaveBeenNthCalledWith(
2,
'Advanced Camera Card [issue=legacy_resource]: Second',
);
spy.mockRestore();
});
it('should log again after reset and re-activation', () => {
const spy = vi.spyOn(console, 'warn').mockReturnValue();
const description = createIssueDescription({
notification: { body: { text: 'Repeat' } },
});
// Active → cleared-by-reset → active again on next eval.
vi.mocked(mockMediaLoad.getIssue)
.mockReturnValueOnce(description)
.mockReturnValueOnce(null)
.mockReturnValueOnce(description);
const manager = createManager();
manager.detectDynamic({ view: 'live' });
manager.reset('media_load');
// After reset, the issue reports cleared on next detect, releasing the
// dedupe.
manager.detectDynamic({ view: 'live' });
// Then it re-activates (e.g. new trigger arrives).
manager.detectDynamic({ view: 'live' });
expect(spy).toBeCalledTimes(2);
spy.mockRestore();
});
});
describe('reset', () => {
it('should reset a specific issue by key', () => {
const manager = createManager();
manager.reset('media_load');
assert(mockMediaLoad.reset);
expect(mockMediaLoad.reset).toBeCalled();
assert(mockConfigUpgrade.reset);
expect(mockConfigUpgrade.reset).not.toBeCalled();
});
it('should reset all issues when no key is given', () => {
const manager = createManager();
manager.reset();
assert(mockConfigUpgrade.reset);
assert(mockLegacyResource.reset);
assert(mockMediaLoad.reset);
expect(mockConfigUpgrade.reset).toBeCalled();
expect(mockLegacyResource.reset).toBeCalled();
expect(mockMediaLoad.reset).toBeCalled();
});
it('should do nothing for unknown key', () => {
const manager = createManager();
manager.reset('unknown' as never);
assert(mockMediaLoad.reset);
expect(mockMediaLoad.reset).not.toBeCalled();
});
});
describe('suspend', () => {
it('should call suspend on all issues that implement it', () => {
const manager = createManager();
manager.suspend();
assert(mockConfigUpgrade.suspend);
assert(mockLegacyResource.suspend);
assert(mockMediaLoad.suspend);
expect(mockConfigUpgrade.suspend).toBeCalled();
expect(mockLegacyResource.suspend).toBeCalled();
expect(mockMediaLoad.suspend).toBeCalled();
});
});
describe('destroy', () => {
it('should destroy all issues and clear', () => {
const manager = createManager();
manager.destroy();
assert(mockConfigUpgrade.reset);
assert(mockLegacyResource.reset);
assert(mockMediaLoad.reset);
expect(mockConfigUpgrade.reset).toBeCalled();
expect(mockLegacyResource.reset).toBeCalled();
expect(mockMediaLoad.reset).toBeCalled();
expect(manager.getIssuePresence().size).toBe(0);
});
});
});