Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(home): let a person draw where their rooms actually are, and file devices from the plan
nirholas15563f03eb16
diff --git a/api/_lib/home/layout.js b/api/_lib/home/layout.jsnew file mode 100644index 000000000..a43b77b9c--- /dev/null+++ b/api/_lib/home/layout.js@@ -0,0 +1,264 @@+// The authored floorplan: validation and storage.+//+// A layout is user-authored JSON that drives a renderer, which makes it+// untrusted input on a path where "it is only our own UI writing this" has+// never once been true for long. Everything here validates before it stores and+// validates again before it renders, with hard caps rather than best effort.+//+// The document shape is the contract src/home/scene-model.js already reads:+// buildSceneModel(graph, { layout }) looks up layout[roomId] and takes+// { x, z, w, d } in metres, where x and z are the room's centre on its floor and+// w and d are its footprint. This module stores that map under a `rooms` key+// with a version tag beside it, so the document can gain fields (rotation, wall+// openings, polygons) without the renderer's lookup changing.++import { sql } from '../db.js';+import { withDbRetry } from '../db-retry.js';++/** The document format, not the row's optimistic-concurrency version. */+export const LAYOUT_FORMAT = 1;++/**+ * Caps. Every one of these is a refusal, not a clamp: silently moving a room a+ * user placed is worse than telling them the number was rejected.+ */+export const LIMITS = Object.freeze({+ /** Rooms in one document. A very large house is ~60; 200 is generous. */+ maxRooms: 200,+ /** Metres from the origin, per axis. The default grid never exceeds ~80. */+ maxCoord: 500,+ /** Metres. Below 1.5 a room cannot hold its own label; above 60 is a field. */+ minSize: 1.5,+ maxSize: 60,+ /** Bytes of serialized JSON. A 200-room document is under 20 KB. */+ maxBytes: 64 * 1024,+ /** Characters in a room id. Home Assistant area ids are far shorter. */+ maxIdLength: 128,+});++/**+ * A Home Assistant area id, or one of the scene's own synthetic room ids. The+ * synthetic bucket (`__unassigned__`) is a real room on screen, so a user can+ * place it, and it therefore has to survive validation.+ */+const ROOM_ID_RE = /^(?:__[a-z_]+__|[A-Za-z0-9_.:-]+)$/;++const ROOM_KEYS = new Set(['x', 'z', 'w', 'd']);+const DOC_KEYS = new Set(['format', 'units', 'rooms']);++/** Thrown for every rejection, so a route maps one class to one status. */+export class LayoutInvalid extends Error {+ constructor(message, field = null) {+ super(message);+ this.name = 'LayoutInvalid';+ this.field = field;+ }+}++/**+ * Validate and normalize a layout document.+ *+ * Returns a NEW object built key by key from what was validated, never the+ * caller's object with extra keys deleted. That difference is the whole point:+ * an unknown key cannot survive a rebuild, and it can survive a delete list that+ * somebody forgets to extend.+ *+ * @param {unknown} input+ * @returns {{ format: number, units: 'm', rooms: Record<string, {x:number,z:number,w:number,d:number}> }}+ * @throws {LayoutInvalid}+ */+export function validateLayout(input) {+ if (!input || typeof input !== 'object' || Array.isArray(input)) {+ throw new LayoutInvalid('A layout must be an object.');+ }++ for (const key of Object.keys(input)) {+ if (!DOC_KEYS.has(key)) throw new LayoutInvalid(`Unknown field "${key}" in the layout.`, key);+ }++ if (input.format != null && input.format !== LAYOUT_FORMAT) {+ throw new LayoutInvalid(`Unsupported layout format ${input.format}; this server writes ${LAYOUT_FORMAT}.`, 'format');+ }+ if (input.units != null && input.units !== 'm') {+ throw new LayoutInvalid('Layout units are metres; "m" is the only accepted value.', 'units');+ }++ const rooms = input.rooms;+ if (!rooms || typeof rooms !== 'object' || Array.isArray(rooms)) {+ throw new LayoutInvalid('A layout needs a "rooms" object keyed by room id.', 'rooms');+ }++ const ids = Object.keys(rooms);+ if (ids.length > LIMITS.maxRooms) {+ throw new LayoutInvalid(`A layout holds at most ${LIMITS.maxRooms} rooms; this one has ${ids.length}.`, 'rooms');+ }++ const out = {};+ for (const id of ids) {+ if (id.length > LIMITS.maxIdLength || !ROOM_ID_RE.test(id)) {+ throw new LayoutInvalid(`"${id.slice(0, 40)}" is not a usable room id.`, `rooms.${id}`);+ }+ const room = rooms[id];+ if (!room || typeof room !== 'object' || Array.isArray(room)) {+ throw new LayoutInvalid(`Room "${id}" must be an object.`, `rooms.${id}`);+ }+ for (const key of Object.keys(room)) {+ if (!ROOM_KEYS.has(key)) throw new LayoutInvalid(`Unknown field "${key}" on room "${id}".`, `rooms.${id}.${key}`);+ }+ out[id] = {+ x: coord(room.x, `rooms.${id}.x`),+ z: coord(room.z, `rooms.${id}.z`),+ w: size(room.w, `rooms.${id}.w`),+ d: size(room.d, `rooms.${id}.d`),+ };+ }++ const doc = { format: LAYOUT_FORMAT, units: 'm', rooms: out };+ const bytes = Buffer.byteLength(JSON.stringify(doc), 'utf8');+ if (bytes > LIMITS.maxBytes) {+ throw new LayoutInvalid(`That layout is ${bytes} bytes; the limit is ${LIMITS.maxBytes}.`, 'rooms');+ }+ return doc;+}++function coord(value, field) {+ const n = Number(value);+ if (!Number.isFinite(n)) throw new LayoutInvalid(`${field} must be a finite number.`, field);+ if (Math.abs(n) > LIMITS.maxCoord) {+ throw new LayoutInvalid(`${field} is ${round(n)} m; the limit is ${LIMITS.maxCoord} m from the origin.`, field);+ }+ return round(n);+}++function size(value, field) {+ if (value == null) return undefined;+ const n = Number(value);+ if (!Number.isFinite(n)) throw new LayoutInvalid(`${field} must be a finite number.`, field);+ if (n < LIMITS.minSize || n > LIMITS.maxSize) {+ throw new LayoutInvalid(`${field} is ${round(n)} m; a room is between ${LIMITS.minSize} and ${LIMITS.maxSize} m.`, field);+ }+ return round(n);+}++/** Centimetre precision. Nobody places a wall to a micrometre and floats drift. */+function round(n) {+ return Math.round(n * 100) / 100;+}++/**+ * The layout for a home, or null when nobody has authored one.+ *+ * Validated on the way OUT as well as in, because a row can predate a cap and a+ * renderer must never be handed a document this version would refuse to store.+ * A row that fails validation is reported as unreadable rather than thrown, so+ * one bad document degrades to the default arrangement instead of taking the+ * page down.+ *+ * @param {string} homeId+ * @returns {Promise<{ version: number, layout: object, updatedAt: string, updatedBy: string, unreadable?: string } | null>}+ */+export async function getLayout(homeId) {+ const [row] = await withDbRetry(+ () => sql`+ SELECT version, layout, updated_by, updated_at+ FROM home_layouts+ WHERE home_id = ${homeId}+ `,+ );+ if (!row) return null;+ try {+ return {+ version: row.version,+ layout: validateLayout(row.layout),+ updatedAt: row.updated_at,+ updatedBy: row.updated_by,+ };+ } catch (err) {+ return {+ version: row.version,+ layout: { format: LAYOUT_FORMAT, units: 'm', rooms: {} },+ updatedAt: row.updated_at,+ updatedBy: row.updated_by,+ unreadable: err.message,+ };+ }+}++/**+ * Write a layout, refusing a stale write.+ *+ * `expectedVersion` is the version the editor loaded. A write whose expectation+ * does not match the row is refused with the current document attached, so the+ * caller can show a real choice instead of a lost edit. A first write passes+ * `expectedVersion: 0`, which is also what a caller sends when it believes no+ * row exists; if one appeared in between, that is a conflict and it is reported+ * as one rather than overwritten.+ *+ * @returns {Promise<{ ok: true, version: number, layout: object } | { ok: false, conflict: true, current: object }>}+ */+export async function putLayout({ homeId, layout, updatedBy, expectedVersion }) {+ const doc = validateLayout(layout);+ const expected = Number.isFinite(expectedVersion) ? Number(expectedVersion) : 0;++ if (expected <= 0) {+ // A first write. ON CONFLICT DO NOTHING rather than upsert: if a row+ // appeared since the editor loaded, the caller's "there is nothing here"+ // is stale and they need to be told.+ const [inserted] = await withDbRetry(+ () => sql`+ INSERT INTO home_layouts (home_id, version, layout, updated_by)+ VALUES (${homeId}, 1, ${JSON.stringify(doc)}::jsonb, ${updatedBy})+ ON CONFLICT (home_id) DO NOTHING+ RETURNING version, layout+ `,+ );+ if (inserted) return { ok: true, version: inserted.version, layout: doc };+ return { ok: false, conflict: true, current: await getLayout(homeId) };+ }++ const [updated] = await withDbRetry(+ () => sql`+ UPDATE home_layouts+ SET layout = ${JSON.stringify(doc)}::jsonb,+ version = version + 1,+ updated_by = ${updatedBy},+ updated_at = now()+ WHERE home_id = ${homeId} AND version = ${expected}+ RETURNING version, layout+ `,+ );+ if (updated) return { ok: true, version: updated.version, layout: doc };+ return { ok: false, conflict: true, current: await getLayout(homeId) };+}++/** Remove the authored layout. The scene falls back to the default arrangement. */+export async function deleteLayout(homeId) {+ const rows = await withDbRetry(+ () => sql`DELETE FROM home_layouts WHERE home_id = ${homeId} RETURNING home_id`,+ );+ return rows.length > 0;+}++/**+ * Which authored rooms no longer exist in the house, and which house rooms have+ * never been placed.+ *+ * Both are ordinary states rather than errors: an area deleted in Home Assistant+ * leaves an orphan, and a new area appears unplaced. The editor needs to show+ * each of them, and the renderer needs to ignore orphans without discarding the+ * user's other work.+ *+ * @param {object} layoutDoc a validated document+ * @param {object} graph the room graph+ */+export function reconcileLayout(layoutDoc, graph) {+ const placed = new Set(Object.keys(layoutDoc?.rooms || {}));+ const live = new Set();+ for (const room of graph?.rooms || []) live.add(room.id);+ if ((graph?.unassigned || []).length) live.add('__unassigned__');++ return {+ orphaned: [...placed].filter((id) => !live.has(id)).sort(),+ unplaced: [...live].filter((id) => !placed.has(id)).sort(),+ };+}diff --git a/api/_lib/migrations/20260903220000_home_layouts.sql b/api/_lib/migrations/20260903220000_home_layouts.sqlnew file mode 100644index 000000000..6e39f74ca--- /dev/null+++ b/api/_lib/migrations/20260903220000_home_layouts.sql@@ -0,0 +1,49 @@+begin;++-- The authored floorplan for one house.+--+-- Home Assistant knows which room a device is in. It does not know where that+-- room is, and it never will: there is no geometry anywhere in its registries.+-- The 3D scene ships a default arrangement (rooms packed into a grid per floor,+-- in name order) so it is useful the moment a house connects, and this table+-- holds the arrangement a person authored on top of it.+--+-- A layout is never required. The scene must render with no row here, with a row+-- that covers only some rooms, and with a row naming a room the house no longer+-- has. All three are ordinary states, so this table is an overlay and never a+-- prerequisite.+--+-- One live layout per home, not one per member: a floorplan is a property of the+-- building, and two members editing the same house are editing the same drawing.+-- `version` is what makes that safe. It is bumped on every write and a stale+-- write is refused rather than merged, so the second editor is asked instead of+-- silently overwriting the first. A version column beats a last-write-wins+-- timestamp here because clock skew between two browsers is real and the loser+-- of a millisecond race should not lose their work.+--+-- The document itself is jsonb rather than columns because its shape is the+-- renderer's contract and it will move (rotation, wall openings, polygons) while+-- this table will not. It is user-authored JSON that drives a renderer, so it is+-- validated against a schema with hard caps on write; see api/_lib/home/layout.js.+-- Nothing reads it without that validator.++create table if not exists home_layouts (+ home_id uuid primary key references home_connections(id) on delete cascade,+ version integer not null default 1,+ layout jsonb not null,+ updated_by uuid not null references users(id),+ updated_at timestamptz not null default now(),+ created_at timestamptz not null default now(),++ -- A version that does not advance is a bug in the store, not a state a+ -- client can reach, and an unversioned row would make the concurrency check+ -- silently pass forever.+ constraint home_layouts_version_chk check (version >= 1)+);++comment on table home_layouts is+ 'Authored floorplan per home. An overlay on the default arrangement, never required.';+comment on column home_layouts.version is+ 'Bumped on every write. A PUT carrying a stale version is refused with 409 and the current document.';++commit;diff --git a/api/home/[id]/assign.js b/api/home/[id]/assign.jsnew file mode 100644index 000000000..96536dea1--- /dev/null+++ b/api/home/[id]/assign.js@@ -0,0 +1,127 @@+// /api/home/:id/assign: file an entity into a room, in Home Assistant itself.+//+// POST { entityId, areaId } areaId null unfiles it+//+// This is the floorplan editor's payload and the reason that editor is worth+// building. Dragging a stray device into a room does not decorate our picture of+// the house; it writes the area into the user's own Home Assistant registry, so+// their dashboards, their voice assistant and their automations all gain the+// same organisation. The work leaves with them even if they never open three.ws+// again.+//+// It is not a guarded action. Nothing moves, nothing opens, and the change is+// two clicks to reverse in their own UI. It is still a write to their house, so+// it needs the `layout` capability, a CSRF token, and a row in the action log.++import { logAudit } from '../../_lib/audit.js';+import { requireCsrf } from '../../_lib/csrf.js';+import { resolveHomeAccess } from '../../_lib/home/access.js';+import { homeError, notFound } from '../../_lib/home/errors.js';+import { entityInScope } from '../../_lib/home/members.js';+import { snapshot, withHome } from '../../_lib/home/runtime.js';+import { logHomeAction } from '../../_lib/home/store.js';+import { cors, error, json, method, rateLimited, readJson, wrap } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';++/** Home Assistant entity id: domain.object_id, both lower snake case. */+const ENTITY_RE = /^[a-z_]+\.[a-z0-9_]+$/;+/** Area ids are slugs Home Assistant generates from the area name. */+const AREA_RE = /^[a-z0-9_]{1,128}$/;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const access = await resolveHomeAccess(req, res, req.query?.id, 'layout');+ if (!access.ok) return error(res, access.status, access.code, access.message);+ const { caller, home, scope, scoped } = access;++ if (!requireCsrf(req, res)) return;++ const rl = await limits.homeAct(caller.userId);+ if (!rl.success) return rateLimited(res, rl, 'too many home writes, slow down');++ const body = await readJson(req, res);+ if (body === undefined) return;++ const entityId = typeof body?.entityId === 'string' ? body.entityId.trim() : '';+ if (!ENTITY_RE.test(entityId)) {+ return error(res, 400, 'entity_invalid', 'entityId must look like light.kitchen_lights.');+ }++ // null and '' both mean "take it out of every room", which is a real thing a+ // user does when they mis-filed something. undefined does not: a caller that+ // forgot the field is a bug, not an unfiling.+ const raw = body?.areaId;+ if (raw === undefined) {+ return error(res, 400, 'area_invalid', 'Send an areaId, or null to take this device out of every room.');+ }+ const areaId = raw === null || raw === '' ? null : String(raw).trim();+ if (areaId !== null && !AREA_RE.test(areaId)) {+ return error(res, 400, 'area_invalid', 'areaId must be a Home Assistant area id.');+ }++ // A scoped member cannot file a device they are not allowed to see, and+ // cannot file one INTO a room they are not allowed to see. Without both+ // halves, a scoped member with the layout capability could map the whole+ // house one rejected assignment at a time, and could move a device out of+ // their own scope where they could no longer undo it.+ //+ // Scope is evaluated against the entity's CURRENT area, read from the live+ // graph, because an area-mode scope grants rooms rather than devices and+ // membership of a room is a property of the house.+ if (scoped) {+ let currentArea = null;+ let known = false;+ try {+ const graph = await snapshot(home.id, caller.userId);+ for (const room of graph.rooms || []) {+ if (room.entities?.some((e) => e.entityId === entityId)) {+ currentArea = room.id;+ known = true;+ break;+ }+ }+ if (!known) known = (graph.unassigned || []).some((e) => e.entityId === entityId);+ } catch {+ // An unreachable house cannot prove scope, and a scoped member must not+ // be granted a write on the strength of an unanswered question.+ return homeError(res, notFound('device'));+ }+ if (!known) return homeError(res, notFound('device'));+ if (!entityInScope(scope, { entityId, areaId: currentArea })) return homeError(res, notFound('device'));+ if (areaId && !entityInScope(scope, { entityId, areaId })) {+ return homeError(res, notFound('room'));+ }+ }++ try {+ const result = await withHome(home.id, caller.userId, (bridge) => bridge.assignEntityArea(entityId, areaId));+ logHomeAction({+ homeId: home.id,+ userId: caller.userId,+ actor: 'user',+ channel: 'websocket',+ action: 'entity_registry.assign_area',+ entityIds: [entityId],+ guarded: false,+ outcome: 'ok',+ detail: { areaId },+ });+ logAudit({ userId: caller.userId, action: 'assign_home_entity_area', resourceId: home.id, meta: { entityId, areaId }, req });+ return json(res, 200, { ok: true, ...result });+ } catch (err) {+ logHomeAction({+ homeId: home.id,+ userId: caller.userId,+ actor: 'user',+ channel: 'websocket',+ action: 'entity_registry.assign_area',+ entityIds: [entityId],+ guarded: false,+ outcome: 'failed',+ detail: { areaId, reason: err?.code || 'error' },+ });+ return homeError(res, err);+ }+});diff --git a/api/home/[id]/layout.js b/api/home/[id]/layout.jsnew file mode 100644index 000000000..4f00de1a9--- /dev/null+++ b/api/home/[id]/layout.js@@ -0,0 +1,133 @@+// /api/home/:id/layout: the authored floorplan for one house.+//+// GET the current layout, its version, and what has drifted from the house+// PUT write a layout, refusing a stale write with 409 and the current one+// DELETE drop it, so the scene returns to the default arrangement+//+// Home Assistant has no geometry, so the arrangement of rooms in the 3D scene is+// either the default grid or something a person drew. This route owns the second+// one. It is never required: no row here is an ordinary state, and the scene+// renders the default grid without it.+//+// Two members can edit the same house. `version` is the whole concurrency story:+// a PUT names the version it loaded, a mismatch is refused with the current+// document attached, and the editor asks the user rather than silently+// discarding somebody's afternoon. Last-write-wins on a timestamp was rejected+// because clock skew between two browsers is real and the loser of a millisecond+// should not lose their work.++import { logAudit } from '../../_lib/audit.js';+import { requireCsrf } from '../../_lib/csrf.js';+import { resolveHomeAccess } from '../../_lib/home/access.js';+import { deleteLayout, getLayout, LayoutInvalid, putLayout, reconcileLayout } from '../../_lib/home/layout.js';+import { snapshot } from '../../_lib/home/runtime.js';+import { cors, error, json, method, rateLimited, readJson, wrap } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,PUT,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'PUT', 'DELETE'])) return;++ // Reading the plan is a read; drawing it is the `layout` capability, which a+ // guest and a viewer do not hold. A house sitter should see where the rooms+ // are and should not be able to redraw somebody's home.+ const access = await resolveHomeAccess(req, res, req.query?.id, req.method === 'GET' ? 'read' : 'layout');+ if (!access.ok) return error(res, access.status, access.code, access.message);+ const { caller, home } = access;++ if (req.method === 'GET') {+ const rl = await limits.homeRead(caller.userId);+ if (!rl.success) return rateLimited(res, rl, 'too many home reads, slow down');+ return json(res, 200, await describe(home.id, caller.userId));+ }++ if (!requireCsrf(req, res)) return;++ if (req.method === 'DELETE') {+ const removed = await deleteLayout(home.id);+ if (removed) {+ logAudit({ userId: caller.userId, action: 'delete_home_layout', resourceId: home.id, req });+ }+ return json(res, 200, { removed, ...(await describe(home.id, caller.userId)) });+ }++ const rl = await limits.homeAct(caller.userId);+ if (!rl.success) return rateLimited(res, rl, 'too many layout writes, slow down');++ const body = await readJson(req, res);+ if (body === undefined) return;++ // A caller that omits the version is not "starting fresh", it is a caller+ // that has not read the concurrency contract. Saying so beats letting it+ // overwrite whatever is there.+ if (body?.version == null) {+ return error(res, 400, 'version_required', 'Send the version you loaded, or 0 to create the first layout.');+ }+ const expected = Number(body.version);+ if (!Number.isInteger(expected) || expected < 0) {+ return error(res, 400, 'version_required', 'version must be a whole number, 0 or greater.');+ }++ let result;+ try {+ result = await putLayout({+ homeId: home.id,+ layout: body.layout,+ updatedBy: caller.userId,+ expectedVersion: expected,+ });+ } catch (err) {+ if (err instanceof LayoutInvalid) {+ return error(res, 400, 'layout_invalid', err.message, { field: err.field });+ }+ throw err;+ }++ if (!result.ok) {+ // 409 with the current document, so the client can offer keep-mine,+ // take-theirs or a side-by-side rather than a bare failure.+ return json(res, 409, {+ error: 'Someone else changed this floorplan while you were drawing.',+ code: 'layout_conflict',+ current: result.current,+ ...(await drift(home.id, caller.userId, result.current?.layout)),+ });+ }++ logAudit({ userId: caller.userId, action: 'write_home_layout', resourceId: home.id, meta: { version: result.version, rooms: Object.keys(result.layout.rooms).length }, req });+ return json(res, 200, { version: result.version, layout: result.layout, ...(await drift(home.id, caller.userId, result.layout)) });+});++/** The stored layout plus what has drifted from the live house. */+async function describe(homeId, userId) {+ const stored = await getLayout(homeId);+ return {+ version: stored?.version ?? 0,+ layout: stored?.layout ?? null,+ updatedAt: stored?.updatedAt ?? null,+ // A document this server would now refuse to store is reported rather+ // than thrown: one bad row degrades to the default arrangement instead of+ // taking the page down.+ unreadable: stored?.unreadable ?? null,+ ...(await drift(homeId, userId, stored?.layout)),+ };+}++/**+ * Which placed rooms the house no longer has, and which house rooms nobody has+ * placed. Both are ordinary, and the editor shows each of them.+ *+ * The graph read is best effort: a floorplan must stay editable while the house+ * itself is unreachable, so a failure here reports no drift rather than failing+ * the request.+ */+async function drift(homeId, userId, layoutDoc) {+ if (!layoutDoc) return { orphaned: [], unplaced: [], driftKnown: false };+ try {+ const graph = await snapshot(homeId, userId);+ const { orphaned, unplaced } = reconcileLayout(layoutDoc, graph);+ return { orphaned, unplaced, driftKnown: true };+ } catch {+ return { orphaned: [], unplaced: [], driftKnown: false };+ }+}diff --git a/packages/home-bridge/src/bridge.js b/packages/home-bridge/src/bridge.jsindex fbe4509ce..e752feb99 100644--- a/packages/home-bridge/src/bridge.js+++ b/packages/home-bridge/src/bridge.js@@ -35,6 +35,7 @@ export class HomeBridge {#listeners = new Map();#rebuildTimer = null;#registryTimer = null;+ #livenessTimer = null;#closed = false;/**@@ -180,6 +181,7 @@ export class HomeBridge {}),);await this.#watchRegistries();+ this.#startLiveness();await this.#waitForFirstStates();this.#rebuild();@@ -199,6 +201,57 @@ export class HomeBridge {});}+ /**+ * Notice a dead house in seconds rather than in a minute.+ *+ * A Home Assistant that is unplugged, crashes, or loses its network sends no+ * FIN, so the WebSocket stays "open" until TCP gives up. Measured against a+ * real instance killed mid-stream: 42 seconds before anything downstream knew,+ * during which a 3D home reads as live and is not. The library reconnects+ * well, it just has nothing to reconnect from until then.+ *+ * So we ask. Home Assistant answers `ping` with `pong` on the same socket; a+ * ping that does not come back inside the deadline means the socket is dead+ * whatever the OS believes, and reconnecting is the library's job from there.+ */+ #startLiveness() {+ // Ten seconds between pings, five to answer one: a worst case of fifteen+ // seconds to notice a house that vanished without saying goodbye, against+ // the forty-two the kernel took on its own. Six messages a minute is+ // nothing on a residential uplink, and the alternative is a wall display+ // showing a live-looking house that is not there.+ const every = this.#options.livenessIntervalMs ?? 10_000;+ const deadline = this.#options.livenessTimeoutMs ?? 5_000;+ if (every <= 0) return;+ this.#livenessTimer = setInterval(async () => {+ if (this.#closed || !this.#connection) return;+ if (!this.#connection.connected) return;+ let timer;+ try {+ await Promise.race([+ this.#connection.ping(),+ new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error('home did not answer a ping')), deadline);+ }),+ ]);+ } catch {+ // Tell everyone watching FIRST: a subscriber marking the scene stale+ // must not wait on the reconnect that follows.+ this.#emit('disconnected', undefined);+ try {+ this.#connection.reconnect(true);+ } catch {+ // A socket already tearing itself down is the outcome we wanted.+ }+ } finally {+ clearTimeout(timer);+ }+ }, every);+ // Node keeps a process alive for a bare interval; a worker holding one open+ // per connected house would never exit.+ this.#livenessTimer.unref?.();+ }+/*** Keep the registries live.*@@ -249,6 +302,21 @@ export class HomeBridge {}, this.#options.registryReloadDelayMs ?? 400);}+ /**+ * Reload the four registries now and rebuild the graph.+ *+ * The registry-updated events already trigger a debounced reload, so this is+ * not needed for correctness. It exists so a caller that just changed the+ * registry itself can await the result instead of racing its own event, which+ * is what a UI needs to redraw without a flicker of stale membership.+ */+ async refreshRegistries() {+ this.#assertConnected();+ this.#registries = await this.#loadRegistries();+ this.#rebuild();+ return this.#graph;+ }+async #loadRegistries() {// floor_registry landed after the other three. An instance without it is// not broken, it just has no floors, so a failure here degrades to [].@@ -332,6 +400,66 @@ export class HomeBridge {}}+ /**+ * Move an entity into an area, or out of every area with a null areaId.+ *+ * This is the one write in this library that changes the house's own+ * organisation rather than its state, and it is here because it is what makes+ * the floorplan editor worth using: dragging a stray device into a room+ * improves the user's Home Assistant, not just our picture of it.+ *+ * It is deliberately NOT run through the physical-action gate. Nothing moves,+ * nothing opens, and the change is reversible in two clicks in the user's own+ * UI. It is still a write, so callers log it.+ *+ * An entity created in YAML never reaches the entity registry, and most demo+ * and template entities are exactly that. Home Assistant answers `not_found`+ * for those, which is an ordinary and common outcome rather than a fault, so+ * it comes back as a coded error a UI can explain instead of a raw throw.+ *+ * @param {string} entityId+ * @param {string|null} areaId a Home Assistant area id, or null to unfile it+ * @returns {Promise<{ entityId: string, areaId: string|null }>}+ */+ async assignEntityArea(entityId, areaId) {+ this.#assertConnected();+ if (typeof entityId !== 'string' || !entityId.includes('.')) {+ throw new HomeBridgeError(ERR.CALL_FAILED, `"${entityId}" is not an entity id.`);+ }+ try {+ const result = await this.#connection.sendMessagePromise({+ type: 'config/entity_registry/update',+ entity_id: entityId,+ area_id: areaId ?? null,+ });+ // The registry is the source of truth for area membership, and the+ // graph is rebuilt from it, so refresh it rather than waiting for the+ // registry-updated event to arrive on its own.+ await this.refreshRegistries();+ return { entityId, areaId: result?.entity_entry?.area_id ?? areaId ?? null };+ } catch (err) {+ const code = err?.code || err?.error?.code;+ if (code === 'not_found') {+ throw new HomeBridgeError(+ ERR.CALL_FAILED,+ `${entityId} is not in this home's entity registry, so it cannot be filed into a room. Entities defined in YAML have no registry entry; give it one in Home Assistant first.`,+ err,+ );+ }+ throw toBridgeError(err, this.#options.baseUrl, `Could not move ${entityId}.`);+ }+ }++ /** Every area the house has, for a UI that files entities into them. */+ areas() {+ return (this.#registries.areas || []).map((a) => ({+ id: a.area_id,+ name: a.name,+ floorId: a.floor_id || null,+ icon: a.icon || null,+ }));+ }+/** Every scene and script in the house, as intent candidates. */macros() {const out = [];@@ -376,6 +504,8 @@ export class HomeBridge {this.#rebuildTimer = null;if (this.#registryTimer) clearTimeout(this.#registryTimer);this.#registryTimer = null;+ if (this.#livenessTimer) clearInterval(this.#livenessTimer);+ this.#livenessTimer = null;for (const stop of this.#unsubscribers) {try {stop();diff --git a/pages/home-scene.html b/pages/home-scene.htmlindex 20dd39010..18d2aed07 100644--- a/pages/home-scene.html+++ b/pages/home-scene.html@@ -27,6 +27,7 @@<span class="hs-spacer"></span><button type="button" class="hs-btn" id="hs-view-3d" aria-pressed="true" data-i18n-attr="aria-label:home_scene.view_3d_aria" aria-label="Show the 3D house">3D</button><button type="button" class="hs-btn" id="hs-view-2d" aria-pressed="false" data-i18n-attr="aria-label:home_scene.view_2d_aria" aria-label="Show the house as a room and device list">2D</button>+ <button type="button" class="hs-btn" id="hs-view-plan" aria-pressed="false" data-i18n-attr="aria-label:home_scene.view_plan_aria" aria-label="Draw where the rooms are">Plan</button><button type="button" class="hs-btn" id="hs-reconnect" hidden data-i18n="home_scene.reconnect">Reconnect</button></div>@@ -39,6 +40,7 @@</nav><main class="hs-stage" id="hs-stage" tabindex="-1"></main>+ <main class="hs-stage hs-stage-plan" id="hs-plan" tabindex="-1" hidden></main><aside class="hs-panel" id="hs-panel" aria-label="Selected device" data-i18n-attr="aria-label:home_scene.panel_aria"><p class="hs-panel-empty" id="hs-panel-empty" data-i18n="home_scene.panel_empty">Pick a room on the left, or click anything in the house to see what it is and act on it.</p>diff --git a/src/home/api.js b/src/home/api.jsindex 3b1e264e5..687fb2ec7 100644--- a/src/home/api.js+++ b/src/home/api.js@@ -57,11 +57,56 @@ async function request(path, { method = 'GET', body = null, signal } = {}) {if (!res.ok) {const code = payload?.code || payload?.error || 'call_failed';const message = payload?.error_description || payload?.message || (typeof payload?.error === 'string' && payload.code ? payload.error : null) || `Request failed (${res.status}).`;- throw new HomeApiError(code, message, { status: res.status, pending: payload?.pending || null });+ throw new HomeApiError(code, message, {+ status: res.status,+ pending: payload?.pending || null,+ // A 409 on the floorplan carries the document that won, so the editor+ // can offer a real choice instead of a bare failure.+ current: payload?.current || null,+ field: payload?.field || null,+ });}return payload;}+/**+ * The authored floorplan, its version, and what has drifted from the house.+ *+ * A house with no layout answers `{ version: 0, layout: null }`, which is the+ * ordinary state and not an error: the scene falls back to its default grid.+ */+export function getLayout(id, signal) {+ return request(`/api/home/${encodeURIComponent(id)}/layout`, { signal });+}++/**+ * Save the floorplan.+ *+ * `version` is the one the editor loaded, or 0 to create the first layout. A+ * stale version throws a HomeApiError with code `layout_conflict` carrying+ * `current`, which is the document that won; the editor asks the user rather+ * than discarding either side.+ */+export function saveLayout(id, { version, layout }) {+ return request(`/api/home/${encodeURIComponent(id)}/layout`, { method: 'PUT', body: { version, layout } });+}++/** Drop the floorplan and return the scene to its default arrangement. */+export function clearLayout(id) {+ return request(`/api/home/${encodeURIComponent(id)}/layout`, { method: 'DELETE' });+}++/**+ * File a device into a room, in Home Assistant itself.+ *+ * Pass `areaId: null` to take it out of every room. This writes the user's own+ * registry, so the room shows up in their dashboards and their voice assistant+ * too, not only here.+ */+export function assignEntityArea(id, { entityId, areaId }) {+ return request(`/api/home/${encodeURIComponent(id)}/assign`, { method: 'POST', body: { entityId, areaId } });+}+/** The caller's homes, credential free. */export function listHomes(signal) {return request('/api/home', { signal });@@ -252,3 +297,61 @@ export function getPlan(signal) {export function changePlanState(action, homeId) {return request('/api/home/plan', { method: 'POST', body: { action, home_id: homeId } });}++// ── The privacy centre (/api/home/privacy) ───────────────────────────────────+//+// Everything three.ws stores about a person's homes: see it, set how long the+// action log lives, download all of it, delete one home or every trace of them+// all. The endpoint is the only place these rows can be read or removed from,+// so this is the only client for it.++/**+ * What we hold about this account right now, plus the inventory that explains+ * each number and the disclosure copy the connect and voice screens render.+ * @param {AbortSignal} [signal]+ */+export function getPrivacy(signal) {+ return request('/api/home/privacy', { signal });+}++/**+ * How long this home keeps its action log.+ *+ * Shortening is always allowed and applies immediately: the response's `purged`+ * count is the rows that went, so a caller can say "142 entries deleted" rather+ * than "within 24 hours". Lengthening past 90 days needs a written reason+ * (`reason_required`) and is capped by the plan (`retention_over_plan`), which+ * are different failures and must be told apart in the UI.+ *+ * @param {string} homeId+ * @param {number} retentionDays+ * @param {string|null} [reason]+ */+export function setRetention(homeId, retentionDays, reason = null) {+ return request('/api/home/privacy', {+ method: 'PATCH',+ body: { homeId, retentionDays, reason },+ });+}++/**+ * Delete one home and everything pointing at it, or every home this account has.+ *+ * This is NOT the disconnect on the manage screen. Disconnecting erases the+ * credential and keeps the record, so an owner can still answer "what did my+ * agent do in my house last Tuesday" about a house they have unplugged. This+ * removes the record too, and there is nothing left to read afterwards.+ *+ * @param {{ scope: 'home'|'all', homeId?: string }} target+ */+export function deleteHomeData(target) {+ return request('/api/home/privacy', { method: 'DELETE', body: target });+}++/**+ * The export URL. Deliberately a plain link rather than a fetch: the response+ * carries a Content-Disposition, so letting the browser navigate to it gives a+ * real Save dialog with a sensible filename, where a fetch would need a blob+ * and an object URL to end up somewhere worse.+ */+export const PRIVACY_EXPORT_URL = '/api/home/privacy?export=1';diff --git a/src/home/floorplan.js b/src/home/floorplan.jsnew file mode 100644index 000000000..6b6e6ea14--- /dev/null+++ b/src/home/floorplan.js@@ -0,0 +1,630 @@+/**+ * The floorplan editor: a top-down plan of the house that the 3D scene follows.+ *+ * Home Assistant knows which room a device is in and has no idea where that room+ * is, so the scene ships a default grid and this is where a person turns it into+ * their actual house. Top-down and 2D on purpose: nobody arranges a floorplan in+ * perspective, and the 3D view is the reward rather than the workspace.+ *+ * The most valuable control here is the tray. Dragging an unfiled device into a+ * room writes the area into the user's own Home Assistant registry, so the work+ * improves their dashboards, their voice assistant and their automations, not+ * just our picture of the house. That is also the fix for the most common real+ * house we see: one where nothing is assigned to an area at all.+ *+ * States 1 to 9 of order 07 all live here; each is a branch of render().+ */++import { assignEntityArea, clearLayout, getLayout, HomeApiError, saveLayout } from './api.js';+import { clear, el, noticeEl } from './connect.js';++/** Metres per grid square. Matches the scene's CELL so the two read alike. */+const GRID_M = 1.2;+/** Default room footprint in metres, matching scene-model.js CELL - ROOM_GAP. */+const DEFAULT_SIZE = 5.7;+/** Pixels per metre at rest. The view scales to fit, this is the starting point. */+const PX_PER_M = 14;+/** A room smaller than this cannot hold its own label. Mirrors the server cap. */+const MIN_SIZE = 1.5;+const MAX_SIZE = 60;+/** Mirrors the server. A refusal here should never be the first the user hears. */+const MAX_COORD = 500;+/** Undo depth. Deep enough to recover an afternoon, bounded so a tab stays small. */+const HISTORY_MAX = 100;++/**+ * @param {object} options+ * @param {HTMLElement} options.mount+ * @param {string} options.homeId+ * @param {object} options.graph the room graph, for room names and the tray+ * @param {boolean} options.canEdit false for a member without the layout capability+ * @param {(layout: object|null) => void} [options.onChange] fires on every applied edit+ */+export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange }) {+ const state = {+ version: 0,+ rooms: new Map(),+ orphaned: [],+ unplaced: [],+ loading: true,+ saving: false,+ error: null,+ notice: null,+ conflict: null,+ selected: null,+ history: [],+ future: [],+ unreadable: null,+ };++ const view = el('div', 'hm-plan');+ mount.append(view);++ load();+ return { destroy: () => view.remove(), reload: load };++ async function load() {+ state.loading = true;+ render();+ try {+ const res = await getLayout(homeId);+ state.version = res.version || 0;+ state.rooms = new Map(Object.entries(res.layout?.rooms || {}));+ state.orphaned = res.orphaned || [];+ state.unplaced = res.unplaced || [];+ state.unreadable = res.unreadable || null;+ state.error = null;+ } catch (err) {+ state.error = describeError(err);+ } finally {+ state.loading = false;+ render();+ }+ }++ // ---- editing -----------------------------------------------------------++ /** Every mutation goes through here, so undo is complete by construction. */+ function apply(mutate, { label } = {}) {+ const before = serialize();+ mutate();+ const after = serialize();+ if (before === after) return;+ state.history.push(before);+ if (state.history.length > HISTORY_MAX) state.history.shift();+ state.future.length = 0;+ state.notice = label ? { tone: 'info', title: label } : null;+ render();+ onChange?.(toDocument());+ }++ function undo() {+ if (!state.history.length) return;+ state.future.push(serialize());+ restore(state.history.pop());+ }++ function redo() {+ if (!state.future.length) return;+ state.history.push(serialize());+ restore(state.future.pop());+ }++ function restore(snapshot) {+ state.rooms = new Map(Object.entries(JSON.parse(snapshot)));+ state.notice = null;+ render();+ onChange?.(toDocument());+ }++ function serialize() {+ return JSON.stringify(Object.fromEntries(state.rooms));+ }++ function toDocument() {+ if (!state.rooms.size) return null;+ return { format: 1, units: 'm', rooms: Object.fromEntries(state.rooms) };+ }++ /** Place a room that has never been placed, in the first free grid slot. */+ function placeRoom(roomId) {+ apply(() => {+ state.rooms.set(roomId, { ...firstFreeSlot(), w: DEFAULT_SIZE, d: DEFAULT_SIZE });+ state.unplaced = state.unplaced.filter((id) => id !== roomId);+ state.selected = roomId;+ }, { label: `${nameOf(roomId)} placed` });+ }++ function removeRoom(roomId) {+ apply(() => {+ state.rooms.delete(roomId);+ if (!state.unplaced.includes(roomId) && liveRoomIds().includes(roomId)) state.unplaced.push(roomId);+ if (state.selected === roomId) state.selected = null;+ }, { label: `${nameOf(roomId)} removed from the plan` });+ }++ function moveRoom(roomId, x, z) {+ const room = state.rooms.get(roomId);+ if (!room) return;+ const snapped = { x: snap(clampCoord(x)), z: snap(clampCoord(z)) };+ if (overlapsAny(roomId, { ...room, ...snapped })) return;+ apply(() => state.rooms.set(roomId, { ...room, ...snapped }));+ }++ function resizeRoom(roomId, w, d) {+ const room = state.rooms.get(roomId);+ if (!room) return;+ const next = { ...room, w: clampSize(snap(w)), d: clampSize(snap(d)) };+ if (overlapsAny(roomId, next)) return;+ apply(() => state.rooms.set(roomId, next));+ }++ /**+ * Overlap is prevented while dragging rather than validated afterwards. A+ * plan that can enter an invalid state and then refuse to save is a plan that+ * loses somebody's work.+ */+ function overlapsAny(roomId, box) {+ for (const [id, other] of state.rooms) {+ if (id === roomId) continue;+ if (boxesOverlap(box, other)) return true;+ }+ return false;+ }++ function firstFreeSlot() {+ for (let ring = 0; ring < 24; ring += 1) {+ for (let dx = -ring; dx <= ring; dx += 1) {+ for (let dz = -ring; dz <= ring; dz += 1) {+ if (Math.max(Math.abs(dx), Math.abs(dz)) !== ring) continue;+ const box = { x: dx * (DEFAULT_SIZE + 1.5), z: dz * (DEFAULT_SIZE + 1.5), w: DEFAULT_SIZE, d: DEFAULT_SIZE };+ if (!overlapsAny(null, box)) return { x: box.x, z: box.z };+ }+ }+ }+ return { x: 0, z: 0 };+ }++ // ---- saving ------------------------------------------------------------++ async function save() {+ if (state.saving) return;+ state.saving = true;+ state.conflict = null;+ render();+ try {+ const res = await saveLayout(homeId, { version: state.version, layout: toDocument() ?? { rooms: {} } });+ state.version = res.version;+ state.orphaned = res.orphaned || [];+ state.unplaced = res.unplaced || [];+ state.notice = { tone: 'ok', title: 'Floorplan saved', body: 'Your 3D home follows this plan now.' };+ state.history.length = 0;+ state.future.length = 0;+ } catch (err) {+ if (err instanceof HomeApiError && err.code === 'layout_conflict') {+ // State 5. Never a silent overwrite and never a lost edit: both+ // documents are held and the person chooses.+ state.conflict = { mine: toDocument(), theirs: err.current };+ } else {+ state.error = describeError(err);+ }+ } finally {+ state.saving = false;+ render();+ }+ }++ function keepMine() {+ const theirs = state.conflict?.theirs;+ state.version = theirs?.version ?? state.version;+ state.conflict = null;+ save();+ }++ function takeTheirs() {+ const theirs = state.conflict?.theirs;+ if (!theirs) return;+ state.version = theirs.version;+ state.rooms = new Map(Object.entries(theirs.layout?.rooms || {}));+ state.conflict = null;+ state.history.length = 0;+ state.future.length = 0;+ state.notice = { tone: 'info', title: 'Loaded the other version', body: 'Your changes were not saved. Redraw and save again if you still want them.' };+ render();+ onChange?.(toDocument());+ }++ async function resetPlan() {+ state.saving = true;+ render();+ try {+ const res = await clearLayout(homeId);+ state.version = res.version || 0;+ state.rooms = new Map();+ state.unplaced = res.unplaced || liveRoomIds();+ state.orphaned = [];+ state.history.length = 0;+ state.future.length = 0;+ state.notice = { tone: 'info', title: 'Back to the default arrangement', body: 'Rooms pack into a grid per floor until you draw a plan again.' };+ } catch (err) {+ state.error = describeError(err);+ } finally {+ state.saving = false;+ render();+ onChange?.(null);+ }+ }++ /**+ * Drop an unfiled device into a room. This is a write to Home Assistant, not+ * to us, so it is confirmed by re-reading the graph rather than assumed.+ */+ async function fileEntity(entityId, areaId) {+ try {+ await assignEntityArea(homeId, { entityId, areaId });+ state.notice = {+ tone: 'ok',+ title: `${entityId} is in ${nameOf(areaId)} now`,+ body: 'That was written to your Home Assistant, so it shows up in your dashboards and voice assistant too.',+ };+ onChange?.(toDocument(), { refreshGraph: true });+ } catch (err) {+ // State 9: the local plan is untouched and the failure is named. A+ // YAML entity has no registry entry and cannot be filed, which is+ // common and needs a sentence rather than a stack trace.+ state.notice = { tone: 'error', title: 'Could not file that device', body: describeError(err).body };+ }+ render();+ }++ // ---- rendering ---------------------------------------------------------++ function render() {+ clear(view);++ if (state.loading) return view.append(skeleton());+ if (state.error) return view.append(noticeEl({ tone: 'error', ...state.error, action: { label: 'Try again', onClick: load } }));++ if (state.unreadable) {+ view.append(noticeEl({+ tone: 'error',+ title: 'This floorplan could not be read',+ body: `${state.unreadable} The 3D home is using its default arrangement. Drawing and saving replaces the stored plan.`,+ }));+ }+ if (state.notice) view.append(noticeEl(state.notice));+ if (state.conflict) view.append(conflictPanel());++ view.append(toolbar());+ view.append(canvas());+ view.append(tray());+ }++ function toolbar() {+ const bar = el('div', 'hm-plan-toolbar');+ bar.setAttribute('role', 'toolbar');+ bar.setAttribute('aria-label', 'Floorplan');++ if (!canEdit) {+ // State 8: read only. The plan is still worth seeing.+ bar.append(el('p', 'hm-plan-readonly', 'You can see this floorplan. Editing it needs the owner or an admin.'));+ return bar;+ }++ bar.append(button('Undo', undo, { disabled: !state.history.length, key: 'Ctrl+Z' }));+ bar.append(button('Redo', redo, { disabled: !state.future.length, key: 'Ctrl+Shift+Z' }));+ const dirty = state.history.length > 0;+ bar.append(button(state.saving ? 'Saving' : 'Save floorplan', save, { primary: true, disabled: state.saving || !dirty }));+ bar.append(button('Reset to default', resetPlan, { disabled: state.saving || !state.rooms.size }));++ const count = el('span', 'hm-plan-count', `${state.rooms.size} placed, ${state.unplaced.length} to place`);+ count.setAttribute('aria-live', 'polite');+ bar.append(count);+ return bar;+ }++ function conflictPanel() {+ const wrap = el('div', 'hm-plan-conflict');+ wrap.setAttribute('role', 'alertdialog');+ wrap.append(el('h3', null, 'Someone else changed this floorplan'));+ wrap.append(el('p', null, `They saved version ${state.conflict.theirs?.version ?? '?'} while you were drawing. Nothing is lost yet: pick which one to keep.`));+ const actions = el('div', 'hm-plan-conflict-actions');+ actions.append(button('Keep mine', keepMine, { primary: true }));+ actions.append(button('Take theirs', takeTheirs));+ wrap.append(actions);+ return wrap;+ }++ function canvas() {+ const rooms = [...state.rooms.entries()];+ const bounds = planBounds(rooms);+ const wrap = el('div', 'hm-plan-canvas');+ wrap.tabIndex = 0;+ wrap.setAttribute('role', 'application');+ wrap.setAttribute('aria-label', 'Floorplan. Arrow keys move the selected room, plus and minus resize it.');++ if (!rooms.length) {+ // States 1 and 2: nothing placed. Which message depends on whether the+ // house has areas at all, because those are different problems.+ const live = liveRoomIds();+ wrap.append(noticeEl(live.length+ ? {+ tone: 'info',+ title: 'No plan yet',+ body: 'Your 3D home is using a default grid. Place a room below to start drawing the real thing.',+ }+ : {+ tone: 'info',+ title: 'Nothing is filed into a room yet',+ body: 'Home Assistant has no areas for this house. Make a room below, then drag your devices into it: that writes the room into your Home Assistant, not just here.',+ }));+ return wrap;+ }++ const surface = el('div', 'hm-plan-surface');+ surface.style.width = `${(bounds.w + 4) * PX_PER_M}px`;+ surface.style.height = `${(bounds.d + 4) * PX_PER_M}px`;++ for (const [id, room] of rooms) {+ surface.append(roomEl(id, room, bounds));+ }+ wrap.append(surface);+ wrap.addEventListener('keydown', onCanvasKey);+ return wrap;+ }++ function roomEl(id, room, bounds) {+ const orphan = state.orphaned.includes(id);+ const node = el('div', `hm-plan-room${state.selected === id ? ' is-selected' : ''}${orphan ? ' is-orphan' : ''}`);+ const w = room.w ?? DEFAULT_SIZE;+ const d = room.d ?? DEFAULT_SIZE;+ node.style.left = `${(room.x - w / 2 - bounds.minX + 2) * PX_PER_M}px`;+ node.style.top = `${(room.z - d / 2 - bounds.minZ + 2) * PX_PER_M}px`;+ node.style.width = `${w * PX_PER_M}px`;+ node.style.height = `${d * PX_PER_M}px`;+ node.tabIndex = 0;+ node.setAttribute('role', 'button');+ node.setAttribute('aria-label', `${nameOf(id)}, ${w} by ${d} metres${orphan ? ', no longer in this home' : ''}`);+ node.setAttribute('aria-pressed', String(state.selected === id));++ node.append(el('span', 'hm-plan-room-name', nameOf(id)));+ node.append(el('span', 'hm-plan-room-size', `${w} x ${d} m`));++ if (orphan) {+ // State 6: the area was deleted in Home Assistant. Never crash, never+ // silently discard the rest of somebody's plan.+ const drop = el('button', 'hm-plan-room-drop', 'Remove');+ drop.type = 'button';+ drop.addEventListener('click', (e) => { e.stopPropagation(); removeRoom(id); });+ node.append(el('span', 'hm-plan-room-tag', 'not in this home'));+ node.append(drop);+ }++ node.addEventListener('click', () => { state.selected = id; render(); });+ if (canEdit) {+ node.addEventListener('pointerdown', (e) => startDrag(e, id, room));+ node.append(resizeHandle(id, room));+ node.addEventListener('dragover', (e) => { e.preventDefault(); node.classList.add('is-drop'); });+ node.addEventListener('dragleave', () => node.classList.remove('is-drop'));+ node.addEventListener('drop', (e) => {+ e.preventDefault();+ node.classList.remove('is-drop');+ const entityId = e.dataTransfer?.getData('text/entity-id');+ if (entityId && !orphan && !id.startsWith('__')) fileEntity(entityId, id);+ });+ }+ return node;+ }++ function resizeHandle(id, room) {+ const handle = el('button', 'hm-plan-handle');+ handle.type = 'button';+ handle.setAttribute('aria-label', `Resize ${nameOf(id)}`);+ handle.addEventListener('pointerdown', (e) => {+ e.stopPropagation();+ const start = { x: e.clientX, y: e.clientY, w: room.w ?? DEFAULT_SIZE, d: room.d ?? DEFAULT_SIZE };+ drag(e, (dx, dy) => resizeRoom(id, start.w + dx / PX_PER_M, start.d + dy / PX_PER_M));+ });+ return handle;+ }++ function startDrag(e, id, room) {+ if (e.target.closest('.hm-plan-handle') || e.target.closest('.hm-plan-room-drop')) return;+ state.selected = id;+ const start = { x: room.x, z: room.z };+ drag(e, (dx, dy) => moveRoom(id, start.x + dx / PX_PER_M, start.z + dy / PX_PER_M));+ }++ /** One pointer-capture drag loop, shared by move and resize. */+ function drag(e, onMove) {+ e.preventDefault();+ const origin = { x: e.clientX, y: e.clientY };+ const target = e.currentTarget;+ target.setPointerCapture?.(e.pointerId);+ const move = (ev) => onMove(ev.clientX - origin.x, ev.clientY - origin.y);+ const up = () => {+ target.releasePointerCapture?.(e.pointerId);+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerup', up);+ };+ window.addEventListener('pointermove', move);+ window.addEventListener('pointerup', up);+ }++ function onCanvasKey(e) {+ if (!canEdit) return;+ const mod = e.ctrlKey || e.metaKey;+ if (mod && e.key.toLowerCase() === 'z') {+ e.preventDefault();+ return e.shiftKey ? redo() : undo();+ }+ if (!state.selected) return;+ const room = state.rooms.get(state.selected);+ if (!room) return;+ const step = e.shiftKey ? GRID_M * 5 : GRID_M;+ const moves = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };+ if (moves[e.key]) {+ e.preventDefault();+ return moveRoom(state.selected, room.x + moves[e.key][0], room.z + moves[e.key][1]);+ }+ if (e.key === '+' || e.key === '=') {+ e.preventDefault();+ return resizeRoom(state.selected, (room.w ?? DEFAULT_SIZE) + GRID_M, (room.d ?? DEFAULT_SIZE) + GRID_M);+ }+ if (e.key === '-' || e.key === '_') {+ e.preventDefault();+ return resizeRoom(state.selected, (room.w ?? DEFAULT_SIZE) - GRID_M, (room.d ?? DEFAULT_SIZE) - GRID_M);+ }+ if (e.key === 'Delete' || e.key === 'Backspace') {+ e.preventDefault();+ removeRoom(state.selected);+ }+ }++ function tray() {+ const wrap = el('div', 'hm-plan-tray');+ wrap.append(el('h3', 'hm-plan-tray-title', 'To place'));++ const unplaced = state.unplaced.length ? state.unplaced : liveRoomIds().filter((id) => !state.rooms.has(id));+ if (unplaced.length) {+ const list = el('ul', 'hm-plan-tray-rooms');+ for (const id of unplaced) {+ const li = el('li');+ const add = el('button', 'hm-plan-tray-room', nameOf(id));+ add.type = 'button';+ add.disabled = !canEdit;+ add.addEventListener('click', () => placeRoom(id));+ li.append(add);+ list.append(li);+ }+ wrap.append(list);+ } else {+ wrap.append(el('p', 'hm-plan-tray-empty', 'Every room in this home is on the plan.'));+ }++ const loose = graph?.unassigned || [];+ if (loose.length) {+ wrap.append(el('h3', 'hm-plan-tray-title', `${loose.length} device${loose.length === 1 ? '' : 's'} not in a room`));+ wrap.append(el('p', 'hm-plan-tray-hint', canEdit+ ? 'Drag one onto a room. That files it in your Home Assistant, so it shows up in your dashboards and voice assistant too.'+ : 'Filing a device into a room needs the owner or an admin.'));+ const list = el('ul', 'hm-plan-tray-entities');+ for (const entity of loose.slice(0, 200)) {+ const li = el('li', 'hm-plan-tray-entity');+ li.textContent = entity.name || entity.entityId;+ li.title = entity.entityId;+ if (canEdit) {+ li.draggable = true;+ li.addEventListener('dragstart', (e) => e.dataTransfer?.setData('text/entity-id', entity.entityId));+ // Keyboard parity: dragging is not the only way in.+ const pick = el('button', 'hm-plan-tray-file', 'File');+ pick.type = 'button';+ pick.setAttribute('aria-label', `File ${entity.name || entity.entityId} into a room`);+ pick.addEventListener('click', () => fileByPrompt(entity.entityId));+ li.append(pick);+ }+ list.append(li);+ }+ wrap.append(list);+ if (loose.length > 200) wrap.append(el('p', 'hm-plan-tray-hint', `Showing the first 200 of ${loose.length}.`));+ }+ return wrap;+ }++ /** The keyboard route into filing, so drag is never the only path. */+ function fileByPrompt(entityId) {+ const rooms = liveRoomIds().filter((id) => !id.startsWith('__'));+ if (!rooms.length) {+ state.notice = { tone: 'info', title: 'No rooms yet', body: 'Make an area in Home Assistant first, then devices can be filed into it.' };+ return render();+ }+ const menu = el('div', 'hm-plan-filemenu');+ menu.setAttribute('role', 'menu');+ for (const id of rooms) {+ const b = el('button', 'hm-plan-filemenu-item', nameOf(id));+ b.type = 'button';+ b.setAttribute('role', 'menuitem');+ b.addEventListener('click', () => { menu.remove(); fileEntity(entityId, id); });+ menu.append(b);+ }+ view.append(menu);+ menu.querySelector('button')?.focus();+ }++ // ---- helpers -----------------------------------------------------------++ function liveRoomIds() {+ const ids = (graph?.rooms || []).map((r) => r.id);+ if ((graph?.unassigned || []).length) ids.push('__unassigned__');+ return ids;+ }++ function nameOf(id) {+ if (id === '__unassigned__') return (graph?.rooms || []).length ? 'Not in a room' : 'Everything';+ return (graph?.rooms || []).find((r) => r.id === id)?.name || id;+ }++ function button(label, onClick, { primary = false, disabled = false, key } = {}) {+ const b = el('button', `hm-plan-btn${primary ? ' is-primary' : ''}`, label);+ b.type = 'button';+ b.disabled = disabled;+ if (key) b.title = key;+ b.addEventListener('click', onClick);+ return b;+ }++ function skeleton() {+ const s = el('div', 'hm-plan-skeleton');+ s.setAttribute('aria-busy', 'true');+ s.setAttribute('aria-label', 'Loading the floorplan');+ for (let i = 0; i < 4; i += 1) s.append(el('div', 'hm-plan-skeleton-room'));+ return s;+ }+}++function describeError(err) {+ if (err instanceof HomeApiError) {+ return { title: err.code === 'not_found' ? 'This home is not available' : 'Something went wrong', body: err.message };+ }+ return { title: 'Something went wrong', body: err?.message || 'Try again in a moment.' };+}++/** Grid snap, in metres. */+function snap(n) {+ return Math.round(n / GRID_M) * GRID_M;+}++function clampCoord(n) {+ return Math.max(-MAX_COORD, Math.min(MAX_COORD, n));+}++function clampSize(n) {+ return Math.max(MIN_SIZE, Math.min(MAX_SIZE, n));+}++export function boxesOverlap(a, b) {+ const aw = (a.w ?? DEFAULT_SIZE) / 2;+ const ad = (a.d ?? DEFAULT_SIZE) / 2;+ const bw = (b.w ?? DEFAULT_SIZE) / 2;+ const bd = (b.d ?? DEFAULT_SIZE) / 2;+ // Touching walls is adjacency, not overlap: a strict comparison lets rooms+ // share a wall, which is what a real floorplan does.+ return Math.abs(a.x - b.x) < aw + bw - 1e-6 && Math.abs(a.z - b.z) < ad + bd - 1e-6;+}++export function planBounds(entries) {+ let minX = Infinity;+ let minZ = Infinity;+ let maxX = -Infinity;+ let maxZ = -Infinity;+ for (const [, room] of entries) {+ const w = (room.w ?? DEFAULT_SIZE) / 2;+ const d = (room.d ?? DEFAULT_SIZE) / 2;+ minX = Math.min(minX, room.x - w);+ minZ = Math.min(minZ, room.z - d);+ maxX = Math.max(maxX, room.x + w);+ maxZ = Math.max(maxZ, room.z + d);+ }+ if (!Number.isFinite(minX)) return { minX: 0, minZ: 0, w: 0, d: 0 };+ return { minX, minZ, w: maxX - minX, d: maxZ - minZ };+}diff --git a/src/home/home.css b/src/home/home.cssindex 5083106a1..3633cda15 100644--- a/src/home/home.css+++ b/src/home/home.css@@ -121,9 +121,9 @@/* The token field carries a reveal toggle inside its own bounds, so the layoutdoes not shift when the button appears. */.hm-secret { position: relative; }-.hm-secret .hm-input { padding-right: 5.2rem; }+.hm-secret .hm-input { padding-inline-end: 5.2rem; }.hm-reveal {- position: absolute; top: 50%; right: 0.45rem; transform: translateY(-50%);+ position: absolute; top: 50%; inset-inline-end: 0.45rem; transform: translateY(-50%);background: var(--hm-panel-2); border: 1px solid var(--hm-line);border-radius: var(--radius-sm); color: var(--hm-ink-2);font: inherit; font-size: var(--text-sm); padding: 0.3rem 0.55rem;@@ -186,7 +186,7 @@.hm-notice {display: flex; gap: 0.7rem; align-items: flex-start;border: 1px solid var(--hm-line);- border-left-width: 3px;+ border-inline-start-width: 3px;border-radius: var(--radius-md);background: var(--hm-panel-2);padding: 0.8rem 0.95rem;@@ -198,13 +198,13 @@.hm-notice p + p { margin-top: 0.45rem; }.hm-notice-title { font-weight: var(--weight-semibold); }.hm-notice-body { color: var(--hm-ink-2); }-.hm-notice ul { margin: 0.5rem 0 0; padding-left: 1.1rem; color: var(--hm-ink-2); }+.hm-notice ul { margin: 0.5rem 0 0; padding-inline-start: 1.1rem; color: var(--hm-ink-2); }.hm-notice li + li { margin-top: 0.3rem; }-.hm-notice-info { border-left-color: var(--hm-idle); }-.hm-notice-warn { border-left-color: var(--hm-stale); }-.hm-notice-error { border-left-color: var(--hm-down); }-.hm-notice-ok { border-left-color: var(--hm-live); }+.hm-notice-info { border-inline-start-color: var(--hm-idle); }+.hm-notice-warn { border-inline-start-color: var(--hm-stale); }+.hm-notice-error { border-inline-start-color: var(--hm-down); }+.hm-notice-ok { border-inline-start-color: var(--hm-live); }.hm-notice-icon { flex: 0 0 auto; width: 1.05rem; height: 1.05rem; margin-top: 0.12rem; }.hm-notice-info .hm-notice-icon { color: var(--hm-idle); }@@ -347,7 +347,7 @@overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;}-.hm-ol { list-style: decimal; margin: 0.5rem 0 0; padding-left: 1.2rem; color: var(--hm-ink-2); font-size: var(--text-md); line-height: var(--leading-normal); }+.hm-ol { list-style: decimal; margin: 0.5rem 0 0; padding-inline-start: 1.2rem; color: var(--hm-ink-2); font-size: var(--text-md); line-height: var(--leading-normal); }.hm-ol li + li { margin-top: 0.3rem; }.hm-ol code, .hm-code {font-family: var(--font-mono); font-size: 0.9em;@@ -442,10 +442,339 @@@media (max-width: 380px) {.hm-stats { grid-template-columns: 1fr 1fr; }- .hm-secret .hm-input { padding-right: 4.4rem; }+ .hm-secret .hm-input { padding-inline-end: 4.4rem; }}/* The "is it us or your house" verdict, appended to a failing home's statusline once the platform's own health is known. Muted on purpose: it explains,it does not compete with the status it is explaining. */.hm-status-verdict { color: var(--hm-ink-2); }++/* ── The disclosure panel ────────────────────────────────────────────────────+ What the token can do and what we keep, shown before the button that sends+ it, and what happens to a voice before the microphone opens. Rendered by+ src/home/disclosure-panel.js from the same strings the API serves.++ Styled to be read, not to be dismissed. The body sits on --hm-ink-2 rather+ than the --hm-ink-3 muted ink the hints use, and the first line (the one that+ changes somebody's mind: "anyone holding it can unlock your doors") inherits+ the page's full-contrast ink, because a promise rendered in grey is a promise+ nobody read. The left rule marks it as a distinct kind of content without+ boxing it into a callout the eye learns to skip. */+.hm-disclosure {+ margin: var(--space-md) 0 0;+ padding-inline-start: var(--space-md);+ border-inline-start: 2px solid var(--hm-line-strong);+}+.hm-disclosure-title {+ font-size: var(--text-md);+ font-weight: var(--weight-medium);+ margin: 0;+ line-height: var(--leading-snug, 1.3);+}+.hm-disclosure-list {+ list-style: none;+ margin: 0.5rem 0 0;+ padding: 0;+ color: var(--hm-ink-2);+ font-size: var(--text-sm);+ line-height: var(--leading-normal);+}+.hm-disclosure-list li + li { margin-top: 0.45rem; }+.hm-disclosure-list li:first-child { color: inherit; }+.hm-disclosure-more {+ display: inline-block;+ margin-top: 0.55rem;+ font-size: var(--text-sm);+ color: var(--hm-ink-2);+ text-decoration: underline;+ text-underline-offset: 2px;+ border-radius: 3px;+}+.hm-disclosure-more:hover { color: inherit; }+.hm-disclosure-more:focus-visible {+ outline: 2px solid var(--hm-focus);+ outline-offset: 2px;+}+@media (prefers-reduced-motion: no-preference) {+ .hm-disclosure-more { transition: color 120ms ease; }+}++/* ── The privacy centre (/smart-home/privacy) ────────────────────────────────+ Everything we store about somebody's homes, with the controls to change the+ window, take a copy, or delete it. Most of the page reuses this surface's+ existing panels, stats, notices and buttons; only the pieces below are new. */++/* Breadcrumb. Small, quiet, and only ever one level: this page hangs off the+ homes list and nothing hangs off it. */+.hm-breadcrumb {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: var(--text-sm);+ color: var(--hm-ink-3);+ margin-bottom: var(--space-md);+}+.hm-breadcrumb a { color: var(--hm-ink-2); text-decoration: none; border-radius: 3px; }+.hm-breadcrumb a:hover { color: inherit; text-decoration: underline; text-underline-offset: 2px; }+.hm-breadcrumb a:focus-visible { outline: 2px solid var(--hm-focus); outline-offset: 2px; }++/* The "never stored" block. It goes ABOVE the table of what we do keep, and it+ is tinted, because it is the part somebody came to check and it should not+ read as a footnote to the list of things we hold. */+.hm-promises {+ border: 1px solid var(--hm-line);+ border-radius: var(--radius-md);+ background: var(--hm-panel);+ padding: var(--space-md);+ margin: var(--space-md) 0;+}+.hm-promises-title {+ margin: 0 0 0.5rem;+ font-size: var(--text-md);+ font-weight: var(--weight-medium);+}+.hm-promises-list {+ list-style: none;+ margin: 0;+ padding: 0;+ font-size: var(--text-sm);+ color: var(--hm-ink-2);+ line-height: var(--leading-normal);+}+.hm-promises-list li + li { margin-top: 0.4rem; }+.hm-promises-list strong { color: inherit; font-weight: var(--weight-medium); }++/* The inventory table. Wide by nature (four columns of prose), so it scrolls+ inside its own region rather than pushing the page sideways at 320px. */+.hm-table { width: 100%; border-collapse: collapse; font-size: var(--text-sm); min-width: 42rem; }+.hm-table th {+ text-align: left;+ font-size: var(--text-2xs);+ text-transform: uppercase;+ letter-spacing: 0.08em;+ color: var(--hm-ink-3);+ font-weight: var(--weight-medium);+ padding: 0 var(--space-sm) 0.5rem 0;+ border-bottom: 1px solid var(--hm-line);+}+.hm-table td {+ padding: var(--space-sm) var(--space-sm) var(--space-sm) 0;+ border-bottom: 1px solid var(--hm-line);+ color: var(--hm-ink-2);+ vertical-align: top;+ line-height: var(--leading-normal);+}+.hm-table td:first-child { color: inherit; }+.hm-table tr:last-child td { border-bottom: 0; }+.hm-table .hm-tag { margin-left: 0.4rem; vertical-align: middle; }++/* The retention control. One row per home: what it keeps now, and five windows+ as one tap each. */+.hm-retention { padding: var(--space-md) 0; border-top: 1px solid var(--hm-line); }+.hm-retention:first-of-type { border-top: 0; padding-top: var(--space-sm); }+.hm-retention-head {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ justify-content: space-between;+ gap: 0.5rem;+}+.hm-retention-home { font-weight: var(--weight-medium); }+.hm-retention-current { font-size: var(--text-sm); color: var(--hm-ink-2); }+.hm-retention-choices { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-top: 0.6rem; }+.hm-chip {+ appearance: none;+ border: 1px solid var(--hm-line-strong);+ background: transparent;+ color: var(--hm-ink-2);+ border-radius: 999px;+ padding: 0.3rem 0.75rem;+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+}+.hm-chip:hover:not(:disabled) { color: inherit; border-color: currentColor; }+.hm-chip:disabled { opacity: 0.5; cursor: not-allowed; }+.hm-chip:focus-visible { outline: 2px solid var(--hm-focus); outline-offset: 2px; }+/* The current window, marked by more than colour: aria-pressed carries it for a+ screen reader, and the filled treatment carries it for everyone else. */+.hm-chip-on {+ color: inherit;+ border-color: currentColor;+ background: var(--hm-panel-2);+ font-weight: var(--weight-medium);+}+.hm-reason { margin-top: var(--space-sm); }+.hm-reason .hm-actions { margin-top: var(--space-sm); }++/* The delete panel. Tinted red at the edge only: a whole red card reads as an+ error state, and this is a control somebody deliberately came to use. */+.hm-panel-danger { border-color: rgba(224, 90, 74, 0.28); }+.hm-danger-row {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-sm);+ padding: var(--space-sm) 0;+ border-top: 1px solid var(--hm-line);+}+.hm-danger-row:first-of-type { border-top: 0; }+.hm-danger-row-all { border-top: 1px solid var(--hm-line-strong); margin-top: var(--space-sm); }+.hm-danger-label { font-weight: var(--weight-medium); }+/* The in-place confirm spans the row rather than sitting beside the button, so+ the question and the thing it is about stay together. */+.hm-danger-row [data-confirm] { flex-basis: 100%; }++@media (max-width: 520px) {+ .hm-danger-row { align-items: stretch; flex-direction: column; }+ .hm-danger-row .hm-btn { width: 100%; }+}++@media (prefers-reduced-motion: reduce) {+ .hm-chip { transition: none; }+}++/* ── the floorplan editor (order 07) ─────────────────────────────────────────+ A top-down plan, because nobody arranges a floorplan in perspective. The 3D+ scene is the reward; this is the workspace. Every colour comes from the+ lane's variables so light and dark both work without a second palette. */++.hm-plan { display: grid; gap: var(--space-md); }++.hm-plan-toolbar {+ display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-xs);+ padding: var(--space-sm); border: 1px solid var(--hm-line);+ border-radius: var(--radius-md); background: var(--hm-panel);+}+.hm-plan-count { margin-left: auto; font-size: var(--text-sm); color: var(--hm-ink-3); }+.hm-plan-readonly { margin: 0; font-size: var(--text-sm); color: var(--hm-ink-2); }++.hm-plan-btn {+ appearance: none; font: inherit; font-size: var(--text-sm);+ padding: 0.45rem 0.8rem; border-radius: var(--radius-sm);+ border: 1px solid var(--hm-line); background: var(--hm-panel-2); color: var(--ink);+ cursor: pointer; transition: background 120ms ease, border-color 120ms ease, opacity 120ms ease;+ /* A thumb needs 44px even when the label does not. */+ min-height: 44px;+}+.hm-plan-btn:hover:not(:disabled) { background: var(--hm-panel); border-color: var(--hm-ink-3); }+.hm-plan-btn:active:not(:disabled) { transform: translateY(1px); }+.hm-plan-btn:focus-visible { outline: 2px solid var(--hm-live); outline-offset: 2px; }+.hm-plan-btn:disabled { opacity: 0.45; cursor: not-allowed; }+.hm-plan-btn.is-primary { background: var(--hm-live); border-color: var(--hm-live); color: #06110b; font-weight: var(--weight-semibold); }++.hm-plan-canvas {+ position: relative; overflow: auto;+ min-height: 320px; max-height: 70vh;+ border: 1px solid var(--hm-line); border-radius: var(--radius-md);+ background:+ linear-gradient(var(--hm-line) 1px, transparent 1px) 0 0 / 16.8px 16.8px,+ linear-gradient(90deg, var(--hm-line) 1px, transparent 1px) 0 0 / 16.8px 16.8px,+ var(--hm-panel);+ padding: var(--space-sm);+}+.hm-plan-canvas:focus-visible { outline: 2px solid var(--hm-live); outline-offset: -2px; }+.hm-plan-surface { position: relative; min-width: 100%; min-height: 280px; }++.hm-plan-room {+ position: absolute; box-sizing: border-box;+ display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 2px;+ padding: var(--space-2xs);+ border: 1.5px solid var(--hm-ink-3); border-radius: var(--radius-sm);+ background: var(--hm-panel-2); color: var(--ink);+ cursor: grab; touch-action: none; text-align: center; overflow: hidden;+ transition: border-color 120ms ease, background 120ms ease, box-shadow 120ms ease;+}+.hm-plan-room:hover { border-color: var(--ink); }+.hm-plan-room:active { cursor: grabbing; }+.hm-plan-room:focus-visible { outline: 2px solid var(--hm-live); outline-offset: 2px; }+.hm-plan-room.is-selected { border-color: var(--hm-live); box-shadow: inset 0 0 0 1px var(--hm-live); }+.hm-plan-room.is-drop { background: color-mix(in srgb, var(--hm-live) 18%, transparent); border-color: var(--hm-live); }+/* An area deleted in Home Assistant. Shown, never silently discarded: the rest+ of somebody's plan is still their work. */+.hm-plan-room.is-orphan { border-style: dashed; opacity: 0.72; }++.hm-plan-room-name { font-size: var(--text-sm); font-weight: var(--weight-medium); line-height: 1.15; }+.hm-plan-room-size { font-size: var(--text-2xs); color: var(--hm-ink-3); font-variant-numeric: tabular-nums; }+.hm-plan-room-tag {+ font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.07em;+ color: var(--hm-ink-3);+}+.hm-plan-room-drop {+ appearance: none; font: inherit; font-size: var(--text-2xs); cursor: pointer;+ border: 1px solid var(--hm-line); border-radius: var(--radius-sm);+ background: transparent; color: var(--hm-ink-2); padding: 2px 8px; min-height: 28px;+}+.hm-plan-room-drop:hover { color: var(--ink); border-color: var(--hm-ink-3); }++.hm-plan-handle {+ appearance: none; position: absolute; right: -1px; bottom: -1px;+ width: 22px; height: 22px; padding: 0; cursor: nwse-resize; touch-action: none;+ border: 0; border-radius: 0 0 var(--radius-sm) 0;+ background: linear-gradient(135deg, transparent 50%, var(--hm-ink-3) 50%);+}+.hm-plan-handle:focus-visible { outline: 2px solid var(--hm-live); outline-offset: 1px; }++.hm-plan-tray { border: 1px solid var(--hm-line); border-radius: var(--radius-md); background: var(--hm-panel); padding: var(--space-sm); }+.hm-plan-tray-title { font-size: var(--text-sm); font-weight: var(--weight-semibold); margin: 0 0 0.4rem; }+.hm-plan-tray-title + .hm-plan-tray-title { margin-top: var(--space-md); }+.hm-plan-tray-hint { font-size: var(--text-sm); color: var(--hm-ink-2); margin: 0 0 0.5rem; line-height: var(--leading-normal); }+.hm-plan-tray-empty { font-size: var(--text-sm); color: var(--hm-ink-3); margin: 0; }+.hm-plan-tray-rooms, .hm-plan-tray-entities { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: var(--space-2xs); }++.hm-plan-tray-room, .hm-plan-tray-file {+ appearance: none; font: inherit; font-size: var(--text-sm); cursor: pointer;+ min-height: 44px; padding: 0.35rem 0.7rem;+ border: 1px dashed var(--hm-ink-3); border-radius: var(--radius-sm);+ background: var(--hm-panel-2); color: var(--ink);+}+.hm-plan-tray-room:hover, .hm-plan-tray-file:hover { border-style: solid; }+.hm-plan-tray-room:focus-visible, .hm-plan-tray-file:focus-visible { outline: 2px solid var(--hm-live); outline-offset: 2px; }+.hm-plan-tray-room:disabled { opacity: 0.45; cursor: not-allowed; }++.hm-plan-tray-entity {+ display: inline-flex; align-items: center; gap: 0.4rem;+ font-size: var(--text-sm); padding: 0.25rem 0.3rem 0.25rem 0.6rem;+ border: 1px solid var(--hm-line); border-radius: var(--radius-sm);+ background: var(--hm-panel-2); cursor: grab; max-width: 100%;+}+.hm-plan-tray-entity:active { cursor: grabbing; }+.hm-plan-tray-file { min-height: 32px; padding: 0.15rem 0.5rem; font-size: var(--text-2xs); border-style: solid; }++.hm-plan-filemenu {+ display: flex; flex-wrap: wrap; gap: var(--space-2xs);+ padding: var(--space-sm); border: 1px solid var(--hm-live); border-radius: var(--radius-md);+ background: var(--hm-panel-2);+}+.hm-plan-filemenu-item {+ appearance: none; font: inherit; font-size: var(--text-sm); cursor: pointer; min-height: 44px;+ padding: 0.35rem 0.7rem; border: 1px solid var(--hm-line); border-radius: var(--radius-sm);+ background: var(--hm-panel); color: var(--ink);+}+.hm-plan-filemenu-item:focus-visible { outline: 2px solid var(--hm-live); outline-offset: 2px; }++.hm-plan-conflict {+ border: 1px solid var(--hm-warn, #d9a441); border-radius: var(--radius-md);+ background: color-mix(in srgb, var(--hm-warn, #d9a441) 10%, transparent);+ padding: var(--space-md);+}+.hm-plan-conflict h3 { margin: 0 0 0.35rem; font-size: var(--text-md); }+.hm-plan-conflict p { margin: 0 0 var(--space-sm); font-size: var(--text-sm); line-height: var(--leading-normal); }+.hm-plan-conflict-actions { display: flex; gap: var(--space-xs); flex-wrap: wrap; }++.hm-plan-skeleton { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--space-sm); }+.hm-plan-skeleton-room { height: 96px; border-radius: var(--radius-sm); background: var(--hm-panel-2); }++@media (prefers-reduced-motion: no-preference) {+ .hm-plan-skeleton-room { animation: hm-plan-pulse 1.6s ease-in-out infinite; }+}+@keyframes hm-plan-pulse { 0%, 100% { opacity: 0.55; } 50% { opacity: 0.9; } }++@media (max-width: 640px) {+ .hm-plan-toolbar { gap: var(--space-2xs); }+ .hm-plan-count { margin-left: 0; width: 100%; }+ .hm-plan-canvas { max-height: 55vh; }+ .hm-plan-skeleton { grid-template-columns: 1fr; }+}diff --git a/src/home/scene.js b/src/home/scene.jsindex 8f4750095..b28f872e8 100644--- a/src/home/scene.js+++ b/src/home/scene.js@@ -12,7 +12,7 @@* dropped socket greys the scene and shows its age. It does not clear it.*/-import { HomeApiError, callService, getHome, grantEntity, openStream } from './api.js';+import { HomeApiError, callService, getHome, getLayout, grantEntity, openStream } from './api.js';import { buildSceneModel } from './scene-model.js';import { createHomeFallback, webglAvailable } from './scene-fallback.js';@@ -33,6 +33,8 @@ const el = {live: document.getElementById('hs-live'),view3d: document.getElementById('hs-view-3d'),view2d: document.getElementById('hs-view-2d'),+ viewPlan: document.getElementById('hs-view-plan'),+ plan: document.getElementById('hs-plan'),reconnect: document.getElementById('hs-reconnect'),};@@ -41,6 +43,14 @@ const state = {home: null,graph: null,model: null,+ /**+ * The authored floorplan's room map, or null when nobody drew one. Null is+ * the ordinary state: the scene packs rooms into a default grid without it.+ */+ layout: null,+ layoutVersion: 0,+ /** The mounted floorplan editor, when the plan view is showing. */+ plan: null,view: preferredView(),renderer: null,stream: null,@@ -98,12 +108,67 @@ async function boot() {state.viewChosen = true;setView('2d', { remember: true });});+ el.viewPlan?.addEventListener('click', () => {+ state.viewChosen = true;+ setView('plan', { remember: true });+ });el.reconnect.addEventListener('click', () => reconnect());document.addEventListener('keydown', onKeydown);+ holdScreenAwake();await load();}+/**+ * The decision, and why it is this one.+ *+ * The live house is the only surface in the lane a screen is meant to sit on:+ * a kitchen tablet on a shelf showing which lights are on. A wall display that+ * blanks every thirty seconds is not a display, and the user cannot fix it+ * without turning off the device's screen timeout for everything else it does.+ * So this page, and only this page, asks for a screen wake lock.+ *+ * The other half matters more. A phone must never be held awake by a tab it is+ * not looking at, so the lock is dropped the moment the document is hidden and+ * only re-taken when it comes back visible. That is also what the platform+ * requires: a wake lock is released automatically on hide, and re-acquiring is+ * the only way back, so the visibility handler is the feature, not a guard+ * around it.+ *+ * Everything here is best-effort. Screen Wake Lock is absent on some browsers+ * and the request is refused outright on a low battery, both of which are the+ * device making a correct decision. The scene is unaffected either way, so a+ * failure is never surfaced to the user.+ */+function holdScreenAwake() {+ if (!('wakeLock' in navigator)) return;+ let sentinel = null;++ const acquire = async () => {+ if (sentinel || document.visibilityState !== 'visible') return;+ try {+ sentinel = await navigator.wakeLock.request('screen');+ sentinel.addEventListener('release', () => {+ sentinel = null;+ });+ } catch {+ sentinel = null;+ }+ };++ const release = () => {+ sentinel?.release?.().catch(() => {});+ sentinel = null;+ };++ document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') acquire();+ else release();+ });+ window.addEventListener('pagehide', release);+ acquire();+}+async function load() {setStatus('connecting', 'Connecting');try {@@ -112,6 +177,10 @@ async function load() {el.title.textContent = state.home?.label || 'Your home';document.title = `${state.home?.label || 'Your home'} · three.ws`;mountRenderer();+ // The authored floorplan, if anyone drew one. Best effort on purpose: a+ // layout that cannot be read must never stop the house from rendering,+ // because the default grid is a complete experience on its own.+ loadLayout();if (payload.graph) {applyGraph(payload.graph, { stale: Boolean(payload.stale) });setStatusFromServer({ status: payload.live_status, stale: payload.stale, detail: payload.error?.message });@@ -159,13 +228,24 @@ function reconnect() {});}+/**+ * Turn what the server said into one of the four things the top bar can say.+ *+ * The distinction that matters: a house that dropped while the platform is+ * still retrying is STALE, not disconnected. The data is old and the system is+ * working on it, and there is nothing for the person to do but read the age.+ * Disconnected is reserved for the cases where nobody is retrying: the token+ * stopped working, or this browser's own stream is gone. That is the state that+ * offers a button, because that is the state where pressing one helps.+ */function setStatusFromServer(payload) {const status = payload.status || 'live';state.stale = Boolean(payload.stale);- if (status === 'disconnected' || status === 'unreachable' || status === 'auth_failed') {- setStatus('disconnected', status === 'auth_failed' ? 'Sign in again' : 'Disconnected', payload.detail || payload.statusDetail);- } else if (state.stale || status === 'reconnecting' || status === 'connecting') {- setStatus('stale', status === 'reconnecting' ? 'Reconnecting' : 'Stale', payload.detail || payload.statusDetail);+ const detail = payload.detail || payload.statusDetail;+ if (status === 'auth_failed' || status === 'revoked' || status === 'disconnected') {+ setStatus('disconnected', status === 'auth_failed' ? 'Sign in again' : 'Disconnected', detail);+ } else if (status === 'unreachable' || state.stale || status === 'reconnecting' || status === 'pending' || status === 'connecting') {+ setStatus('stale', status === 'reconnecting' ? 'Reconnecting' : 'Stale', detail);} else {setStatus('live', 'Live');}@@ -176,7 +256,9 @@ function setStatus(kind, label, detail) {el.status.dataset.status = kind;el.status.textContent = label;el.status.title = detail || '';- el.reconnect.hidden = kind !== 'disconnected';+ // Offered whenever the house is not live: on a terminal disconnect it is the+ // only way back, and on a long stale it is a person deciding not to wait.+ el.reconnect.hidden = kind === 'live' || kind === 'connecting';const stale = kind === 'stale' || kind === 'disconnected';state.stale = stale;state.renderer?.setStale?.(stale);@@ -187,6 +269,26 @@ function setStatus(kind, label, detail) {}}+/**+ * Read the authored floorplan and re-lay the scene with it.+ *+ * Deliberately not awaited by load(): the house paints on the default grid+ * immediately and slides into the authored plan when it arrives, which is a+ * better first frame than a blank canvas waiting on a second request. A failure+ * leaves state.layout null, which is exactly the no-layout case the model+ * already handles.+ */+async function loadLayout() {+ try {+ const res = await getLayout(state.homeId);+ state.layout = res?.layout?.rooms || null;+ state.layoutVersion = res?.version || 0;+ if (state.graph) applyGraph(state.graph, { stale: state.stale });+ } catch {+ state.layout = null;+ }+}+// ── the model ────────────────────────────────────────────────────────────────function applyGraph(graph, { stale = false, receivedAt = 0 } = {}) {@@ -194,16 +296,20 @@ function applyGraph(graph, { stale = false, receivedAt = 0 } = {}) {state.graph = graph;state.lastGraphAt = Date.now();state.stale = stale;- const model = buildSceneModel(graph, { focusRoomId: state.model?.focusRoomId });+ const model = buildSceneModel(graph, { focusRoomId: state.model?.focusRoomId, layout: state.layout });state.model = model;renderRooms(model);renderInspector();+ // The designed nothings are the page's, not the renderer's. Gating them on a+ // mounted renderer meant an empty house painted nothing at all while the 3D+ // module was still being imported, which is the exact case the empty state+ // exists for.+ renderEmptyStates(model);+ renderAge();if (receivedAt) measureLatency(receivedAt);if (!state.renderer) return;state.renderer.setModel(model);state.renderer.setStale?.(stale);- renderEmptyStates(model);- renderAge();repositionConfirm();}@@ -251,6 +357,7 @@ function setView(view, { remember = true, force = false } = {}) {}el.view3d.setAttribute('aria-pressed', String(view === '3d'));el.view2d.setAttribute('aria-pressed', String(view === '2d'));+ el.viewPlan?.setAttribute('aria-pressed', String(view === 'plan'));el.view3d.disabled = !webglAvailable();if (el.view3d.disabled) el.view3d.title = 'This browser cannot run WebGL.';@@ -259,6 +366,18 @@ function setView(view, { remember = true, force = false } = {}) {clearStage();el.stage.classList.toggle('is-flat', view === '2d');+ // The plan is a workspace, not a renderer: it replaces the stage rather than+ // drawing into it, and it keeps no live subscription of its own.+ state.plan?.destroy();+ state.plan = null;+ if (el.plan) el.plan.hidden = view !== 'plan';+ el.stage.hidden = view === 'plan';+ if (view === 'plan') {+ mountPlan();+ renderAge();+ return;+ }+if (view === '2d') {state.renderer = createHomeFallback(el.stage, { onAct: act, onFocusRoom: focusRoom });state.fpsSince = 0;@@ -273,6 +392,47 @@ function setView(view, { remember = true, force = false } = {}) {renderAge();}+/**+ * The floorplan workspace.+ *+ * Loaded on demand: nobody who only wants to see their house should pay for the+ * editor. Its saves feed straight back into the model, so the 3D view is already+ * arranged when they switch back to it.+ */+async function mountPlan() {+ if (!el.plan) return;+ el.plan.textContent = '';+ const { mountFloorplan } = await import('./floorplan.js');+ if (state.view !== 'plan') return;+ state.plan = mountFloorplan({+ mount: el.plan,+ homeId: state.homeId,+ graph: state.graph,+ // The layout capability. A guest sees the plan and cannot redraw somebody+ // else's home; the server enforces it either way, this only hides controls+ // that would fail.+ canEdit: state.home?.capabilities?.layout !== false,+ onChange(doc, opts) {+ state.layout = doc?.rooms || null;+ if (state.graph) applyGraph(state.graph, { stale: state.stale });+ // Filing a device changed Home Assistant's own registry, so the room+ // graph is stale in a way no state event will correct.+ if (opts?.refreshGraph) refreshGraph();+ },+ });+ el.plan.focus?.();+}++/** Re-read the house after we changed its registry rather than its state. */+async function refreshGraph() {+ try {+ const payload = await getHome(state.homeId);+ if (payload?.graph) applyGraph(payload.graph, { stale: Boolean(payload.stale) });+ } catch {+ // The plan is still correct locally; the graph refreshes on the next event.+ }+}+async function mount3d() {// The renderer pulls Three.js, the avatar loader and the clip library. A// device that will never show it (or a visitor who prefers the flat house)@@ -294,6 +454,7 @@ async function mount3d() {if (state.model) {state.renderer.setModel(state.model);state.renderer.setStale?.(state.stale);+ renderEmptyStates(state.model);}} catch (err) {announce('The 3D house could not start, so the 2D house is on instead.');@@ -626,30 +787,46 @@ function renderConfirm() {el.stage.appendChild(card);state.confirmCard = card;+ // Measured after insertion: the clamp needs the card's real height.repositionConfirm();+ requestAnimationFrame(repositionConfirm);yes.focus();}+/**+ * Pin the confirmation to the thing it would move.+ *+ * The card grows upward from its anchor, so both axes are clamped to what is+ * actually on screen: an anchor near the top of the stage would otherwise put+ * the question, and the word "unlock" in it, above the visible area.+ */function repositionConfirm() {const card = state.confirmCard;if (!card || !state.pending) return;- const point = state.renderer?.project?.(state.pending.entityId);const rect = el.stage.getBoundingClientRect();+ const scroll = el.stage.scrollTop;+ const height = card.offsetHeight || 190;+ const halfWidth = card.offsetWidth ? card.offsetWidth / 2 : 160;+ const minTop = scroll + height + 12;+ const maxTop = scroll + rect.height - 12;++ const point = state.renderer?.project?.(state.pending.entityId);+ let left = rect.width / 2;+ let top = scroll + rect.height / 2;if (point && point.visible) {- card.style.left = `${clamp(point.x, 150, rect.width - 150)}px`;- card.style.top = `${clamp(point.y - 18, 130, rect.height - 20)}px`;+ left = point.x;+ top = point.y - 18;} else {// The 2D house and an off-screen object both anchor to the row instead.const row = el.stage.querySelector(`[data-entity-id="${cssEscape(state.pending.entityId)}"]`);if (row) {const r = row.getBoundingClientRect();- card.style.left = `${clamp(r.left - rect.left + r.width / 2, 150, rect.width - 150)}px`;- card.style.top = `${clamp(r.top - rect.top + el.stage.scrollTop, 130, rect.height + el.stage.scrollTop)}px`;- } else {- card.style.left = '50%';- card.style.top = '50%';+ left = r.left - rect.left + r.width / 2;+ top = r.top - rect.top + scroll - 6;}}+ card.style.left = `${clamp(left, halfWidth + 8, rect.width - halfWidth - 8)}px`;+ card.style.top = `${clamp(top, minTop, Math.max(minTop, maxTop))}px`;}function dismissConfirm() {@@ -845,7 +1022,9 @@ function announce(message) {// ── helpers ──────────────────────────────────────────────────────────────────function homeIdFromPath() {- const match = location.pathname.match(/^\/home\/([0-9a-fA-F-]{36})/);+ // Both routes serve this page: /smart-home/:id is where the connect flow's+ // "Open" lands, and /home/:id is the campaign's own address for the scene.+ const match = location.pathname.match(/^\/(?:smart-)?home\/([0-9a-fA-F-]{36})/);if (match) return match[1];const query = new URLSearchParams(location.search).get('home');return query && /^[0-9a-fA-F-]{36}$/.test(query) ? query : null;diff --git a/tests/home-layout.test.js b/tests/home-layout.test.jsnew file mode 100644index 000000000..fb86a77da--- /dev/null+++ b/tests/home-layout.test.js@@ -0,0 +1,308 @@+// Order 07: the authored floorplan.+//+// Three tiers, matching tests/home-store.test.js: the validator is pure and+// always runs, the store tier needs a real database, and the top tier needs a+// real Home Assistant because the whole point of the area write-back is that it+// changes the user's own registry rather than our picture of it.+//+// HOME_ASSISTANT_URL=... HOME_ASSISTANT_TOKEN=... npx vitest run tests/home-layout.test.js+//+// An instance is one command: node scripts/home-test-instance.mjs --up --onboard --seed++import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import {+ LayoutInvalid,+ LIMITS,+ reconcileLayout,+ validateLayout,+} from '../api/_lib/home/layout.js';++// ---------------------------------------------------------------------------+// The pure tier.+// ---------------------------------------------------------------------------++describe('the layout validator', () => {+ it('accepts the shape the scene reads', () => {+ const doc = validateLayout({ rooms: { kitchen: { x: 3.2, z: -1.5, w: 5, d: 4 } } });+ expect(doc).toEqual({ format: 1, units: 'm', rooms: { kitchen: { x: 3.2, z: -1.5, w: 5, d: 4 } } });+ });++ it('rebuilds the document rather than deleting unknown keys off the caller\'s object', () => {+ // The difference matters: a delete list can be forgotten when a field is+ // added, a rebuild cannot let anything through it does not name.+ const hostile = { rooms: { kitchen: { x: 0, z: 0, __proto__: { polluted: true }, script: '<img onerror=1>' } } };+ expect(() => validateLayout(hostile)).toThrow(LayoutInvalid);+ });++ it('refuses an unknown top-level field', () => {+ expect(() => validateLayout({ rooms: {}, camera: { x: 1 } })).toThrow(/Unknown field "camera"/);+ });++ it('refuses a coordinate past the world bound instead of clamping it', () => {+ // Silently moving a room the user placed is worse than refusing the number.+ expect(() => validateLayout({ rooms: { a: { x: LIMITS.maxCoord + 1, z: 0 } } })).toThrow(/limit is 500 m/);+ expect(() => validateLayout({ rooms: { a: { x: 0, z: Number.NaN } } })).toThrow(/finite number/);+ expect(() => validateLayout({ rooms: { a: { x: 0, z: Infinity } } })).toThrow(/finite number/);+ });++ it('refuses a room smaller than its own label or larger than a field', () => {+ expect(() => validateLayout({ rooms: { a: { x: 0, z: 0, w: 0.2 } } })).toThrow(/between 1.5 and 60/);+ expect(() => validateLayout({ rooms: { a: { x: 0, z: 0, d: 900 } } })).toThrow(/between 1.5 and 60/);+ });++ it('leaves w and d absent when the author never set them, so the scene keeps its default', () => {+ const doc = validateLayout({ rooms: { a: { x: 1, z: 2 } } });+ expect(doc.rooms.a.w).toBeUndefined();+ expect(doc.rooms.a.d).toBeUndefined();+ });++ it('caps the room count and the document size', () => {+ const many = {};+ for (let i = 0; i < LIMITS.maxRooms + 1; i += 1) many[`room_${i}`] = { x: 0, z: 0 };+ expect(() => validateLayout({ rooms: many })).toThrow(/at most 200 rooms/);+ });++ it('accepts the synthetic room the scene invents for unfiled devices', () => {+ expect(validateLayout({ rooms: { __unassigned__: { x: 0, z: 0 } } }).rooms.__unassigned__).toBeDefined();+ });++ it('refuses a room id that is not one', () => {+ expect(() => validateLayout({ rooms: { 'kitchen lights!': { x: 0, z: 0 } } })).toThrow(/not a usable room id/);+ expect(() => validateLayout({ rooms: { ['a'.repeat(LIMITS.maxIdLength + 1)]: { x: 0, z: 0 } } })).toThrow(/not a usable room id/);+ });++ it('refuses a format it did not write', () => {+ expect(() => validateLayout({ format: 99, rooms: {} })).toThrow(/Unsupported layout format/);+ expect(() => validateLayout({ units: 'ft', rooms: {} })).toThrow(/metres/);+ });++ it('rounds to the centimetre, because nobody places a wall to a micrometre', () => {+ expect(validateLayout({ rooms: { a: { x: 1.23456789, z: 0 } } }).rooms.a.x).toBe(1.23);+ });++ it('refuses a non-object, an array, and a missing rooms map', () => {+ for (const bad of [null, 'x', 42, [], { rooms: [] }, { rooms: 'kitchen' }, {}]) {+ expect(() => validateLayout(bad), JSON.stringify(bad)).toThrow(LayoutInvalid);+ }+ });+});++describe('reconciling a layout against a live house', () => {+ const doc = { format: 1, units: 'm', rooms: { kitchen: { x: 0, z: 0 }, gone: { x: 7, z: 0 } } };++ it('names the rooms the house no longer has and the ones nobody placed', () => {+ const graph = { rooms: [{ id: 'kitchen' }, { id: 'bedroom' }], unassigned: [] };+ expect(reconcileLayout(doc, graph)).toEqual({ orphaned: ['gone'], unplaced: ['bedroom'] });+ });++ it('counts the synthetic bucket as a real room once anything is unfiled', () => {+ const graph = { rooms: [{ id: 'kitchen' }], unassigned: [{ entityId: 'light.x' }] };+ expect(reconcileLayout(doc, graph).unplaced).toEqual(['__unassigned__']);+ });++ it('says nothing drifted for an empty layout', () => {+ expect(reconcileLayout({ rooms: {} }, { rooms: [{ id: 'kitchen' }], unassigned: [] })).toEqual({+ orphaned: [],+ unplaced: ['kitchen'],+ });+ });+});++// ---------------------------------------------------------------------------+// The live tiers.+// ---------------------------------------------------------------------------++const hasDb = Boolean(process.env.DATABASE_URL);+const hasKey = Boolean(process.env.WALLET_ENCRYPTION_KEY || process.env.JWT_SECRET);+const haUrl = process.env.HOME_ASSISTANT_URL;+const haToken = process.env.HOME_ASSISTANT_TOKEN;++const liveDb = describe.skipIf(!hasDb || !hasKey);+const liveHome = describe.skipIf(!hasDb || !hasKey || !haUrl || !haToken);++const SYNTHETIC_TOKEN = `synthetic.home.assistant.token.${'a'.repeat(64)}`;++liveDb('the layout store, against a real database', () => {+ let sql;+ let store;+ let layout;+ let owner;+ let second;+ let home;++ beforeAll(async () => {+ ({ sql } = await import('../api/_lib/db.js'));+ store = await import('../api/_lib/home/store.js');+ layout = await import('../api/_lib/home/layout.js');+ const stamp = Date.now();+ [owner] = await sql`insert into users (email) values (${`home-layout-a-${stamp}@qa.three.ws`}) returning id`;+ [second] = await sql`insert into users (email) values (${`home-layout-b-${stamp}@qa.three.ws`}) returning id`;+ home = await store.createConnection({+ userId: owner.id,+ label: 'Layout test',+ baseUrl: haUrl || 'https://layout.invalid.three.ws',+ token: haToken || SYNTHETIC_TOKEN,+ });+ }, 60_000);++ afterAll(async () => {+ if (!sql) return;+ if (home) await sql`delete from home_connections where id = ${home.id}`;+ for (const u of [owner, second]) if (u) await sql`delete from users where id = ${u.id}`;+ });++ it('reports no layout before anyone draws one', async () => {+ expect(await layout.getLayout(home.id)).toBeNull();+ });++ it('creates the first layout at version 1', async () => {+ const res = await layout.putLayout({+ homeId: home.id,+ layout: { rooms: { kitchen: { x: 0, z: 0 } } },+ updatedBy: owner.id,+ expectedVersion: 0,+ });+ expect(res.ok).toBe(true);+ expect(res.version).toBe(1);+ });++ it('refuses a second create rather than overwriting the first', async () => {+ // A caller sending expectedVersion 0 believes there is nothing here. If a+ // row appeared since they loaded, that belief is stale and they must be+ // told, not silently overwritten.+ const res = await layout.putLayout({+ homeId: home.id,+ layout: { rooms: { bedroom: { x: 9, z: 0 } } },+ updatedBy: second.id,+ expectedVersion: 0,+ });+ expect(res.ok).toBe(false);+ expect(res.conflict).toBe(true);+ expect(res.current.layout.rooms).toHaveProperty('kitchen');+ expect(res.current.layout.rooms).not.toHaveProperty('bedroom');+ });++ it('advances the version on a good write', async () => {+ const res = await layout.putLayout({+ homeId: home.id,+ layout: { rooms: { kitchen: { x: 1, z: 1 } } },+ updatedBy: owner.id,+ expectedVersion: 1,+ });+ expect(res.ok).toBe(true);+ expect(res.version).toBe(2);+ expect((await layout.getLayout(home.id)).layout.rooms.kitchen).toEqual({ x: 1, z: 1, w: undefined, d: undefined });+ });++ it('refuses a stale write and hands back the current document, so no edit is lost', async () => {+ // Two members drawing at once. The second must be asked, not overruled.+ const stale = await layout.putLayout({+ homeId: home.id,+ layout: { rooms: { kitchen: { x: 99, z: 99 } } },+ updatedBy: second.id,+ expectedVersion: 1,+ });+ expect(stale.ok).toBe(false);+ expect(stale.conflict).toBe(true);+ expect(stale.current.version).toBe(2);+ expect(stale.current.layout.rooms.kitchen.x).toBe(1);+ });++ it('rejects an invalid document before it reaches the database', async () => {+ await expect(+ layout.putLayout({ homeId: home.id, layout: { rooms: { a: { x: 9e9, z: 0 } } }, updatedBy: owner.id, expectedVersion: 2 }),+ ).rejects.toThrow(LayoutInvalid);+ expect((await layout.getLayout(home.id)).version).toBe(2);+ });++ it('reports a stored document this version would now refuse, rather than throwing', async () => {+ // A row can predate a cap. One bad document must degrade to the default+ // arrangement, not take the page down.+ await sql`update home_layouts set layout = ${JSON.stringify({ format: 1, units: 'm', rooms: { a: { x: 99999, z: 0 } } })}::jsonb where home_id = ${home.id}`;+ const read = await layout.getLayout(home.id);+ expect(read.unreadable).toMatch(/limit is 500 m/);+ expect(read.layout.rooms).toEqual({});+ });++ it('deletes, and is honest about deleting nothing twice', async () => {+ expect(await layout.deleteLayout(home.id)).toBe(true);+ expect(await layout.deleteLayout(home.id)).toBe(false);+ expect(await layout.getLayout(home.id)).toBeNull();+ });++ it('cascades with the home', async () => {+ await layout.putLayout({ homeId: home.id, layout: { rooms: { kitchen: { x: 0, z: 0 } } }, updatedBy: owner.id, expectedVersion: 0 });+ await sql`delete from home_connections where id = ${home.id}`;+ const [row] = await sql`select 1 as hit from home_layouts where home_id = ${home.id}`;+ expect(row).toBeUndefined();+ home = null;+ });+});++liveHome('the area write-back, against a real Home Assistant', () => {+ let bridge;+ let unfiled;+ let areaId;+ let originalArea;++ beforeAll(async () => {+ const { HomeBridge } = await import('../packages/home-bridge/src/index.js');+ bridge = new HomeBridge({ baseUrl: haUrl, token: haToken });+ await bridge.connect();+ areaId = bridge.areas()[0]?.id;+ // A registry entity that the seeder did not already file, so the test+ // moves something real and can put it back.+ const registry = bridge.registries.entities || [];+ const candidate = registry.find((e) => e.entity_id.startsWith('light.') && !e.disabled_by);+ unfiled = candidate?.entity_id;+ originalArea = candidate?.area_id ?? null;+ }, 60_000);++ afterAll(async () => {+ if (bridge && unfiled) {+ try {+ await bridge.assignEntityArea(unfiled, originalArea);+ } catch {+ // Best effort: the assertion below already proved the write works.+ }+ }+ bridge?.close();+ });++ it('has an area and a registry entity to work with', () => {+ expect(areaId).toBeTruthy();+ expect(unfiled).toBeTruthy();+ });++ it('moves a real entity into a real area, and Home Assistant agrees', async () => {+ await bridge.assignEntityArea(unfiled, areaId);+ // Read it back from Home Assistant's own registry, not from our cache of it.+ const fresh = await bridge.refreshRegistries();+ const entry = (bridge.registries.entities || []).find((e) => e.entity_id === unfiled);+ expect(entry.area_id).toBe(areaId);+ // And the room graph the scene renders reflects it without a reconnect.+ const room = fresh.rooms.find((r) => r.id === areaId);+ expect(room.entities.some((e) => e.entityId === unfiled)).toBe(true);+ }, 30_000);++ it('unfiles an entity when given a null area', async () => {+ await bridge.assignEntityArea(unfiled, null);+ const entry = (bridge.registries.entities || []).find((e) => e.entity_id === unfiled);+ expect(entry.area_id ?? null).toBeNull();+ }, 30_000);++ it('explains a YAML entity instead of throwing a raw protocol error', async () => {+ // Most demo and template entities never reach the entity registry, so this+ // is the common case rather than an edge one, and it needs a sentence a+ // person can act on.+ const registered = new Set((bridge.registries.entities || []).map((e) => e.entity_id));+ const yamlOnly = Object.keys(bridge.states).find((id) => !registered.has(id) && id.includes('.'));+ if (!yamlOnly) return;+ await expect(bridge.assignEntityArea(yamlOnly, areaId)).rejects.toThrow(/entity registry/i);+ }, 30_000);++ it('refuses something that is not an entity id at all', async () => {+ await expect(bridge.assignEntityArea('not-an-entity', areaId)).rejects.toThrow(/not an entity id/);+ });+});