Compare commits

...
Author SHA1 Message Date
renovate[bot] fbd1de0ec7 Update dependency cropperjs to v1.7.0 (#54810)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-10-10 17:16:56 +02:00
renovate[bot] 9f50d399a6 Update babel monorepo to v8.0.7 (#54813)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-10-10 17:16:19 +02:00
renovate[bot] da632926bb Update dependency @versatiles/style to v6.3.1 (#54814)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-10-10 17:15:37 +02:00
renovate[bot] 0e9b62e7d0 Update dependency @versatiles/style to v6.3.0 (#54804)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-10-10 05:42:05 +00:00
Elias Lecomte 2f09fb9e5b Improve demo water consumption and cost statistics (#54648)
* Add demo water statistics and long energy source names

* Align demo water statistics scaling and consumption costs

* Preserve non-admin permissions when the test app refreshes its user

* Restore original demo energy meter friendly names

* Remove unrelated authentication scenario fix from water statistics PR

* Derive demo costs generically and scale water by bucket duration
2026-10-10 08:39:06 +03:00
karwosts 1a922fc067 Fix time_format field appearing when it shouldn't in tile editor (#54799)
Fix time_format field appearing when it shouldnt in tile editor.
2026-10-10 08:35:10 +03:00
renovate[bot] 54e15575d2 Update pnpm to v12.10.1 (#54803)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-10-10 08:32:26 +03:00
renovate[bot] e9bfc29729 Update dependency maplibre-gl to v6.13.0 (#54806)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-10-10 08:31:33 +03:00
Jan-Philipp Benecke 743755a59f Fix script graph crash on template shorthand conditions (#54798)
* Fix script graph crash on template shorthand conditions

* Move string to ConditionWithShorthand
2026-10-09 16:17:44 -07:00
Aidan TimsonandClaude ea1d3fef73 Add E2E tests for creating an automation (#54791)
Cover creating an automation from the picker through the save dialog,
the save dialog refusing an empty name, and discarding a new automation
when leaving the editor.

The app harness now registers the demo's display registry mock, which
answers the refetch the app makes when a saved automation fires
entity_registry_updated.


Claude-Session: https://claude.ai/code/session_011L15xnuJiRZnioxrmNwDfb

Co-authored-by: Claude <[email protected]>
2026-10-09 19:02:28 +03:00
12 changed files with 864 additions and 451 deletions
+33 -4
View File
@@ -60,7 +60,7 @@ const generateSumStatistics = (
end: Date,
period: "5minute" | "hour" | "day" | "month" = "hour",
initValue: number,
maxDiff: number
maxDiff: number | ((start: Date, end: Date) => number)
): StatisticValue[] => {
const statistics: StatisticValue[] = [];
let currentDate = new Date(start);
@@ -69,7 +69,9 @@ const generateSumStatistics = (
const now = new Date();
while (end > currentDate && currentDate < now) {
const nextDate = getNextDate(currentDate, period);
const add = Math.random() * maxDiff;
const bound =
typeof maxDiff === "function" ? maxDiff(currentDate, nextDate) : maxDiff;
const add = Math.random() * bound;
sum += add;
statistics.push({
start: currentDate.getTime(),
@@ -136,6 +138,15 @@ const statisticsFunctions: Record<
period: "5minute" | "hour" | "day" | "month"
) => StatisticValue[]
> = {
"sensor.energy_water": (_id, start, end, period = "hour") =>
generateSumStatistics(
start,
end,
period,
4000,
(bucketStart, bucketEnd) =>
(20 * (bucketEnd.getTime() - bucketStart.getTime())) / 3600000
),
"sensor.energy_consumption_tarif_1": (
_id: string,
start: Date,
@@ -301,6 +312,11 @@ const statisticsFunctions: Record<
return [...morning, ...production, ...evening, ...rest];
},
};
// Prices are per source unit; water uses litres (4 currency units per m³).
const derivedCosts: Record<string, { source: string; price: number }> = {
"sensor.energy_water_cost": { source: "sensor.energy_water", price: 0.004 },
};
export const mockRecorder = (mockHass: MockHomeAssistant) => {
mockHass.mockWS(
"recorder/get_statistics_metadata",
@@ -317,10 +333,23 @@ export const mockRecorder = (mockHass: MockHomeAssistant) => {
const end = end_time ? new Date(end_time) : new Date();
const statistics: Record<string, StatisticValue[]> = {};
const cache: Record<string, StatisticValue[]> = {};
const getStats = (id: string) => {
cache[id] ??= statisticsFunctions[id](id, start, end, period);
return cache[id];
};
statistic_ids.forEach((id: string) => {
if (id in statisticsFunctions) {
statistics[id] = statisticsFunctions[id](id, start, end, period);
if (id in derivedCosts) {
const { source, price } = derivedCosts[id];
let cost = 0;
statistics[id] = getStats(source).map((statistic) => {
const change = statistic.change! * price;
cost += change;
return { ...statistic, change, state: cost, sum: cost };
});
} else if (id in statisticsFunctions) {
statistics[id] = getStats(id);
} else {
const entityState = hass.states[id];
const state = entityState ? Number(entityState.state) : 1;
+8 -8
View File
@@ -40,7 +40,7 @@
"license": "Apache-2.0",
"type": "module",
"dependencies": {
"@babel/runtime": "8.0.5",
"@babel/runtime": "8.0.7",
"@braintree/sanitize-url": "7.1.2",
"@codemirror/autocomplete": "6.20.3",
"@codemirror/commands": "6.11.1",
@@ -85,7 +85,7 @@
"@swc/helpers": "0.5.23",
"@tsparticles/engine": "4.4.0",
"@tsparticles/preset-links": "4.4.0",
"@versatiles/style": "6.2.0",
"@versatiles/style": "6.3.1",
"@vibrant/color": "4.0.4",
"@vvo/tzdb": "6.198.0",
"@webcomponents/scoped-custom-element-registry": "0.0.10",
@@ -94,7 +94,7 @@
"color-name": "2.1.1",
"comlink": "4.4.2",
"core-js": "3.50.0",
"cropperjs": "1.6.3",
"cropperjs": "1.7.0",
"culori": "4.0.2",
"date-fns": "4.4.0",
"deep-clone-simple": "1.1.1",
@@ -113,7 +113,7 @@
"lit": "3.3.3",
"lit-html": "3.3.3",
"luxon": "3.7.2",
"maplibre-gl": "6.12.0",
"maplibre-gl": "6.13.0",
"marked": "18.1.0",
"memoize-one": "6.0.0",
"nanoid": "6.0.2",
@@ -141,11 +141,11 @@
},
"devDependencies": {
"@ampproject/remapping": "2.3.0",
"@babel/core": "8.0.6",
"@babel/helper-compilation-targets": "8.0.6",
"@babel/core": "8.0.7",
"@babel/helper-compilation-targets": "8.0.7",
"@babel/helper-define-polyfill-provider": "1.0.0",
"@babel/plugin-transform-runtime": "8.0.6",
"@babel/preset-env": "8.0.6",
"@babel/preset-env": "8.0.7",
"@bundle-stats/plugin-webpack-filter": "4.22.3",
"@eslint/js": "10.0.1",
"@gfx/zopfli": "1.0.15",
@@ -225,7 +225,7 @@
"webpackbar": "7.0.0",
"workbox-build": "7.4.1"
},
"packageManager": "[email protected].0",
"packageManager": "[email protected].1",
"volta": {
"node": "24.21.0"
}
+444 -432
View File
File diff suppressed because it is too large Load Diff
+7 -1
View File
@@ -362,11 +362,17 @@ export type ConditionWithShorthand =
| ShorthandAndConditionList
| ShorthandAndCondition
| ShorthandOrCondition
| ShorthandNotCondition;
| ShorthandNotCondition
| string;
export const expandConditionWithShorthand = (
cond: ConditionWithShorthand
): Condition => {
// A bare template string is shorthand for a template condition
if (typeof cond === "string") {
return { condition: "template", value_template: cond };
}
if ("condition" in cond && Array.isArray(cond.condition)) {
return {
condition: "and",
+5 -4
View File
@@ -68,7 +68,7 @@ const TIMESTAMP_STATE_PROPS = ["last_updated", "last_changed"];
const TIMESTAMP_CONTENTS = [...TIMESTAMP_STATE_PROPS, "last_triggered"];
const TIMESTAMP_DOMAIN_CONTENTS = {
const TIMESTAMP_DOMAIN_CONTENTS: Record<string, string[] | undefined> = {
calendar: ["start_time", "end_time"],
input_datetime: ["timestamp"],
sun: [
@@ -106,10 +106,11 @@ export const stateContentHasTimestamp = (
}
}
}
const domainContents = TIMESTAMP_DOMAIN_CONTENTS[domain];
return (
TIMESTAMP_DOMAIN_CONTENTS[domain] &&
content &&
contentArray.some((c) => TIMESTAMP_DOMAIN_CONTENTS[domain].includes(c))
!!content &&
!!domainContents &&
contentArray.some((c) => domainContents.includes(c))
);
};
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { expandConditionWithShorthand } from "../../src/data/automation";
describe("expandConditionWithShorthand", () => {
it("expands a template string to a template condition", () => {
expect(
expandConditionWithShorthand("{{ is_state('sun.sun', 'below_horizon') }}")
).toEqual({
condition: "template",
value_template: "{{ is_state('sun.sun', 'below_horizon') }}",
});
});
it("expands a condition list to an and condition", () => {
const conditions = [{ condition: "state", entity_id: "light.kitchen" }];
expect(
expandConditionWithShorthand({ condition: conditions } as any)
).toEqual({ condition: "and", conditions });
});
it("expands building block shorthand", () => {
const conditions = [{ condition: "state", entity_id: "light.kitchen" }];
expect(expandConditionWithShorthand({ or: conditions } as any)).toEqual({
condition: "or",
conditions,
});
});
it("returns a regular condition unchanged", () => {
const condition = { condition: "state", entity_id: "light.kitchen" } as any;
expect(expandConditionWithShorthand(condition)).toBe(condition);
});
});
+99
View File
@@ -0,0 +1,99 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mockRecorder } from "../../demo/src/stubs/recorder";
import type { Statistics } from "../../src/data/recorder";
import type { MockHomeAssistant } from "../../src/fake_data/provide_hass";
const fetchWater = (
period: "5minute" | "hour" | "day" | "month",
ids = ["sensor.energy_water", "sensor.energy_water_cost"],
start = "2026-01-01T00:00:00Z",
end = "2026-02-01T00:00:00Z"
): Statistics => {
const mockWS = vi.fn();
const hass = { mockWS, states: {} } as unknown as MockHomeAssistant;
mockRecorder(hass);
const handler = mockWS.mock.calls.find(
([type]) => type === "recorder/statistics_during_period"
)![1];
return handler(
{
statistic_ids: ids,
start_time: start,
end_time: end,
period,
},
hass
);
};
describe("demo water statistics", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-03-01T00:00:00Z"));
vi.spyOn(Math, "random").mockReturnValue(0.5);
});
afterEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
});
it.each([
["5minute", 20 / 24],
["hour", 10],
["day", 240],
["month", 7440],
] as const)("scales consumption for %s buckets", (period, expected) => {
expect(fetchWater(period)["sensor.energy_water"][0].change).toBeCloseTo(
expected
);
});
it.each([
["2026-02-01", "2026-03-01", 6720],
["2024-02-01", "2024-03-01", 6960],
["2026-04-01", "2026-05-01", 7200],
])("uses the actual month duration from %s", (start, end, expected) => {
vi.setSystemTime(new Date("2027-01-01T00:00:00Z"));
const stats = fetchWater(
"month",
undefined,
`${start}T00:00:00Z`,
`${end}T00:00:00Z`
);
expect(stats["sensor.energy_water"][0].change).toBeCloseTo(expected);
});
it("scales each month independently in a multi-month request", () => {
vi.setSystemTime(new Date("2027-01-01T00:00:00Z"));
const stats = fetchWater(
"month",
undefined,
"2026-01-01T00:00:00Z",
"2026-04-01T00:00:00Z"
);
expect(stats["sensor.energy_water"].map((bucket) => bucket.change)).toEqual(
[7440, 6720, 7440]
);
});
it.each([
["sensor.energy_water", "sensor.energy_water_cost"],
["sensor.energy_water_cost", "sensor.energy_water"],
["sensor.energy_water_cost"],
])("derives costs regardless of requested IDs: %j", (...ids) => {
vi.spyOn(Math, "random").mockReturnValueOnce(0.25).mockReturnValue(0.5);
const stats = fetchWater("hour", ids);
const costs = stats["sensor.energy_water_cost"];
expect(costs[0].change).toBeCloseTo(5 * 0.004);
let total = 0;
costs.forEach((cost, index) => {
const consumption = stats["sensor.energy_water"]?.[index];
if (consumption) {
expect(cost.change).toBeCloseTo(consumption.change! * 0.004);
}
total += cost.change!;
expect(cost.sum).toBeCloseTo(total);
expect(cost.state).toBeCloseTo(total);
});
});
});
+89
View File
@@ -0,0 +1,89 @@
import { expect, type Locator, type Page } from "@playwright/test";
import type { AutomationConfig } from "../../../../src/data/automation";
import { PANEL_TIMEOUT, QUICK_TIMEOUT } from "../../helpers";
import { goToPanel } from "./helpers";
export const automationPicker = (page: Page) =>
page.locator("ha-automation-picker");
export const automationEditor = (page: Page) =>
page.locator("manual-automation-editor");
// Scoped to the dialog, the editor has a Save button of its own.
export const automationSaveDialog = (page: Page) =>
page.locator("ha-dialog-automation-save");
export async function openAutomationPicker(page: Page) {
await goToPanel(page, "/?scenario=automation-editor#/config/automation");
await expect(automationPicker(page)).toBeAttached({
timeout: PANEL_TIMEOUT,
});
}
export async function startNewAutomation(page: Page) {
await automationPicker(page)
.getByRole("button", { name: "Create automation" })
.click();
await page
.locator("ha-dialog-new-automation ha-list-item")
.filter({ hasText: "Create new automation" })
.click();
await expect(page).toHaveURL(/#\/config\/automation\/edit\/new$/);
await expect(automationEditor(page)).toBeAttached({
timeout: PANEL_TIMEOUT,
});
}
// Picks the element through the dialog's search, which is the same on wide
// and narrow layouts, unlike browsing its groups.
export async function addAutomationElement(
page: Page,
type: "trigger" | "action",
name: string
) {
await automationEditor(page)
.getByRole("button", { name: `Add ${type}`, exact: true })
.click();
const dialog = page.locator("add-automation-element-dialog");
await dialog.locator("ha-input-search input").fill(name);
await dialog
.locator("ha-automation-add-search ha-list-item-button")
.filter({ hasText: name })
.first()
.click();
await expect(dialog.locator("ha-input-search")).toBeHidden({
timeout: QUICK_TIMEOUT,
});
// The new element opens in the sidebar, which is a bottom sheet over the
// Save button on narrow layouts, so close it like a user would.
const sidebar = automationEditor(page).locator("ha-automation-sidebar");
await sidebar.getByRole("button", { name: "Close", exact: true }).click();
await expect(sidebar).toHaveClass(/hidden/);
}
// The host element, which carries the "dirty" class while there are unsaved
// changes.
export const saveAutomationButton = (page: Page) =>
automationEditor(page).locator('ha-button[slot="fab"]');
export const expectAutomationSaveDialog = async (
page: Page,
title: string
): Promise<Locator> => {
const dialog = automationSaveDialog(page);
await expect(dialog.getByRole("dialog", { name: title })).toBeVisible({
timeout: QUICK_TIMEOUT,
});
return dialog;
};
export const readSavedAutomation = (page: Page, id: string) =>
page.evaluate(
(automationId) =>
window.__mockHass.callApi<AutomationConfig>(
"GET",
`config/automation/config/${automationId}`
),
id
);
+5 -1
View File
@@ -18,7 +18,10 @@ import {
import { mockDeviceRegistry } from "../../../../demo/src/stubs/device_registry";
import { mockEnergy } from "../../../../demo/src/stubs/energy";
import { energyEntities } from "../../../../demo/src/stubs/entities";
import { mockEntityRegistry } from "../../../../demo/src/stubs/entity_registry";
import {
mockEntityRegistry,
mockEntityRegistryDisplay,
} from "../../../../demo/src/stubs/entity_registry";
import { mockEvents } from "../../../../demo/src/stubs/events";
import { mockFloorRegistry } from "../../../../demo/src/stubs/floor_registry";
import { mockFrontend } from "../../../../demo/src/stubs/frontend";
@@ -168,6 +171,7 @@ export class HaTest extends HomeAssistantAppEl {
mockDeviceRegistry(hass);
mockFloorRegistry(hass);
mockLabelRegistry(hass);
mockEntityRegistryDisplay(hass);
mockEntityRegistry(hass, []);
mockConfigEntries(hass);
mockIcons(hass);
+15
View File
@@ -372,6 +372,20 @@ const delayedMediaBrowseErrorScenario: Scenario = (hass) => {
hass.mockWS("media_source/browse_media", () => browsePromise);
};
const automationEditorScenario: Scenario = async (hass) => {
// A direct load of an automation route otherwise races the config panel
// translations that the editor's buttons and dialogs are named by.
await hass.loadFragmentTranslation("config");
// Like a default install, so creating an automation starts in the dialog
// that also offers blueprints.
hass.updateHass({
config: {
...hass.config,
components: [...hass.config.components, "blueprint"],
},
});
};
const systemLogReportingScenario: Scenario = async (hass) => {
await hass.loadFragmentTranslation("config");
hass.updateHass({
@@ -497,6 +511,7 @@ const systemLogReportingScenario: Scenario = async (hass) => {
export const scenarios: Record<string, Scenario> = {
default: defaultScenario,
"automation-editor": automationEditorScenario,
"non-admin": nonAdminScenario,
"dark-theme": darkThemeScenario,
"custom-theme": customThemeScenario,
+125
View File
@@ -0,0 +1,125 @@
/**
* E2E tests for creating automations in the HA test app (port 8095).
*
* Run with:
* pnpm test:e2e:app -g "Automation editor"
*/
import { expect, test } from "@playwright/test";
import {
addAutomationElement,
automationEditor,
automationPicker,
automationSaveDialog,
expectAutomationSaveDialog,
openAutomationPicker,
readSavedAutomation,
saveAutomationButton,
startNewAutomation,
} from "./app/src/automation";
import {
expectNoPageErrors,
PANEL_TIMEOUT,
QUICK_TIMEOUT,
trackPageErrors,
} from "./helpers";
test.describe("Automation editor", () => {
let errors: ReturnType<typeof trackPageErrors>;
test.beforeEach(async ({ page }) => {
errors = trackPageErrors(page);
await openAutomationPicker(page);
await startNewAutomation(page);
});
test.afterEach(() => {
expectNoPageErrors(errors);
});
test("creates an automation through the save dialog", async ({ page }) => {
await addAutomationElement(page, "trigger", "Home Assistant");
await addAutomationElement(page, "action", "Wait for time to pass (delay)");
await saveAutomationButton(page).click();
const dialog = await expectAutomationSaveDialog(page, "Save");
const name = dialog.getByRole("textbox", { name: "Name" });
await expect(name).toHaveValue("New automation");
await name.fill("E2E test automation");
await dialog.getByRole("button", { name: "Add description" }).click();
await dialog
.getByRole("textbox", { name: "Description" })
.fill("Created by Playwright");
await dialog.getByRole("button", { name: "Save", exact: true }).click();
await expect(page).toHaveURL(/#\/config\/automation\/edit\/\d+$/, {
timeout: PANEL_TIMEOUT,
});
const id = page.url().split("/").pop()!;
await expect(dialog.getByRole("dialog")).toBeHidden();
// Shown when the new automation never reaches the entity registry.
await expect(
page.locator("dialog-automation-save-timeout")
).not.toBeAttached();
await expect(page.locator("hass-subpage .main-title")).toHaveText(
"E2E test automation"
);
await expect(saveAutomationButton(page)).not.toHaveClass(/dirty/);
expect(await readSavedAutomation(page, id)).toEqual({
id,
alias: "E2E test automation",
description: "Created by Playwright",
mode: "single",
triggers: [{ trigger: "homeassistant", event: "start" }],
conditions: [],
actions: [{ delay: expect.anything() }],
});
await page.goBack();
await expect(
automationPicker(page).getByRole("row", { name: /E2E test automation/ })
).toBeVisible({ timeout: PANEL_TIMEOUT });
});
test("keeps the save dialog open without a name", async ({ page }) => {
await addAutomationElement(page, "trigger", "Home Assistant");
await saveAutomationButton(page).click();
const dialog = await expectAutomationSaveDialog(page, "Save");
await dialog.getByRole("textbox", { name: "Name" }).clear();
await dialog.getByRole("button", { name: "Save", exact: true }).click();
await expect(
dialog.getByText("Cannot save automation without a name")
).toBeVisible({ timeout: QUICK_TIMEOUT });
await expect(dialog.getByRole("dialog")).toBeVisible();
await dialog.getByRole("button", { name: "Cancel" }).click();
await expect(dialog.getByRole("dialog")).toBeHidden();
await expect(page).toHaveURL(/#\/config\/automation\/edit\/new$/);
await expect(saveAutomationButton(page)).toHaveClass(/dirty/);
});
test("discards a new automation when leaving without saving", async ({
page,
}) => {
await addAutomationElement(page, "trigger", "Home Assistant");
await page.locator("hass-subpage ha-icon-button-arrow-prev").click();
const dialog = await expectAutomationSaveDialog(
page,
"Save new automation?"
);
await dialog.getByRole("button", { name: "Don't save" }).click();
await expect(page).toHaveURL(/#\/config\/automation\/dashboard$/, {
timeout: PANEL_TIMEOUT,
});
// The harness has no automations, so the picker is still empty.
await expect(
automationPicker(page).getByRole("heading", { name: "Start automating" })
).toBeVisible();
await expect(automationEditor(page)).not.toBeAttached();
await expect(automationSaveDialog(page).getByRole("dialog")).toBeHidden();
});
});
+1 -1
View File
@@ -6,7 +6,7 @@ const APP_BASE_URL = `http://localhost:${APP_PORT}`;
export default defineConfig({
testDir: ".",
testMatch: ["app.spec.ts", "onboarding.spec.ts"],
testMatch: ["app.spec.ts", "automation.spec.ts", "onboarding.spec.ts"],
timeout: 60_000,
expect: { timeout: 15_000 },