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): give the connected house a page and a 3D model you can stand in
nirholas6b76f7de894c
diff --git a/pages/smart-home.html b/pages/smart-home.htmlnew file mode 100644index 000000000..eda7d51e4--- /dev/null+++ b/pages/smart-home.html@@ -0,0 +1,69 @@+<!doctype html>+<html lang="en">+<head>+ <script>/* three.ws theme boot */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Smart home · Connect your house to your agent · three.ws</title>+ <meta name="description" content="Connect a Home Assistant house to your three.ws agent. Your agent reads the rooms, runs your own scenes, and stops to ask before it unlocks, opens, or disarms anything." />+ <link rel="canonical" href="https://three.ws/smart-home" />+ <meta property="og:title" content="Smart home · three.ws" />+ <meta property="og:description" content="Connect a Home Assistant house to your three.ws agent. Reads are free; anything that opens the house stops and asks." />+ <meta property="og:url" content="https://three.ws/smart-home" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Smart+home&d=Connect+a+Home+Assistant+house+to+your+three.ws+agent.+Reads+are+free%3B+anything+that+opens+the+house+stops+and+asks.&p=%2Fsmart-home" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Smart home · three.ws" />+ <meta name="twitter:description" content="Connect a Home Assistant house to your three.ws agent. Reads are free; anything that opens the house stops and asks." />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/src/home/home.css" />+</head>+<body>+ <main class="hm-wrap" id="main">+ <header class="hm-hero">+ <p class="hm-eyebrow" data-i18n="smart_home.eyebrow">Smart home</p>+ <h1 class="hm-title" data-i18n="smart_home.title">Put your agent inside your house</h1>+ <p class="hm-lede" data-i18n="smart_home.lede">+ Connect a Home Assistant instance and your agent can see every room, read every device, and+ run the scenes you already built. Reads are free. Anything that unlocks, opens or disarms+ stops and asks you first, every time.+ </p>+ </header>++ <!--+ One live region for the whole flow. The controller (src/home/connect.js)+ owns everything inside it and renders exactly one of the eleven states.+ It is `aria-live="polite"` so a state change (a refusal, a connected+ house) is announced without stealing focus mid-typing.+ -->+ <div id="hm-root" aria-live="polite" aria-busy="true">+ <section class="hm-panel">+ <div class="hm-panel-head">+ <div style="flex:1">+ <div class="hm-skeleton" style="height:1.1rem;width:11rem"></div>+ <div class="hm-skeleton" style="height:0.85rem;width:19rem;margin-top:0.55rem"></div>+ </div>+ </div>+ <div class="hm-skeleton" style="height:2.6rem"></div>+ </section>+ </div>++ <noscript>+ <section class="hm-panel">+ <h2 class="hm-panel-title">JavaScript is required here</h2>+ <p class="hm-panel-sub">+ Connecting a house opens a live connection to it and never stores your access token in+ this browser, so this page needs JavaScript to work. Everything else on three.ws reads+ fine without it.+ </p>+ </section>+ </noscript>+ </main>++ <script src="/nav.js"></script>+ <script type="module" src="/src/home/connect.js"></script>+</body>+</html>diff --git a/src/home/api.js b/src/home/api.jsnew file mode 100644index 000000000..bbc624af0--- /dev/null+++ b/src/home/api.js@@ -0,0 +1,155 @@+/**+ * The browser half of the `/api/home/*` contract.+ *+ * One place that knows the error shape, the CSRF dance and the SSE framing, so+ * the 3D scene, the 2D fallback and every later home surface read the same+ * table instead of three slightly different ones.+ *+ * Every failure surfaces as a `HomeApiError` carrying the server's `code`, so+ * a caller branches on `needs_confirmation` or `unreachable` rather than on a+ * message string that will be reworded next week.+ */++export class HomeApiError extends Error {+ constructor(code, message, { status = 0, pending = null } = {}) {+ super(message);+ this.name = 'HomeApiError';+ this.code = code;+ this.status = status;+ this.pending = pending;+ }+}++let csrf = null;++async function csrfToken() {+ if (csrf && csrf.expiresAt > Date.now() + 5000) return csrf.token;+ const res = await fetch('/api/csrf-token', { credentials: 'include' });+ if (!res.ok) throw new HomeApiError('unauthorized', 'Sign in to control this home.', { status: res.status });+ const body = await res.json();+ const data = body.data || body;+ csrf = { token: data.token, expiresAt: Date.now() + ((data.expires_in || 3600) - 30) * 1000 };+ return csrf.token;+}++async function request(path, { method = 'GET', body = null, signal } = {}) {+ const headers = { accept: 'application/json' };+ if (body) headers['content-type'] = 'application/json';+ if (method !== 'GET') {+ headers['x-csrf-token'] = await csrfToken();+ // Tokens are single use on this platform; drop the cache after spending one.+ csrf = null;+ }+ let res;+ try {+ res = await fetch(path, { method, headers, credentials: 'include', body: body ? JSON.stringify(body) : undefined, signal });+ } catch (cause) {+ if (cause?.name === 'AbortError') throw cause;+ throw new HomeApiError('unreachable', 'three.ws could not be reached. Check your connection and try again.', { status: 0 });+ }+ const text = await res.text();+ let payload = null;+ try {+ payload = text ? JSON.parse(text) : null;+ } catch {+ // A proxy error page, not our contract.+ }+ 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 });+ }+ return payload;+}++/** The caller's homes, credential free. */+export function listHomes(signal) {+ return request('/api/home', { signal });+}++/** One home plus the current room graph. */+export function getHome(id, signal) {+ return request(`/api/home/${encodeURIComponent(id)}`, { signal });+}++/**+ * A gated service call. A guarded action answers 409 with `pending`, which the+ * caller renders as a question next to the thing it would move. `confirmed` is+ * only ever set from a person clicking yes.+ */+export function callService(id, { domain, service, data, confirmed = false }) {+ return request(`/api/home/${encodeURIComponent(id)}/call`, { method: 'POST', body: { domain, service, data, confirmed } });+}++/** A phrase to one of the house's own scenes or scripts. */+export function activatePhrase(id, { phrase, dryRun = false, confirmed = false }) {+ return request(`/api/home/${encodeURIComponent(id)}/activate`, { method: 'POST', body: { phrase, dryRun, confirmed } });+}++/** A standing per-entity allowance, so a repeated yes is not asked forever. */+export function grantEntity(id, { entityId, expiresAt = null }) {+ return request(`/api/home/${encodeURIComponent(id)}/grants`, { method: 'POST', body: { entityId, expiresAt } });+}++/**+ * The live stream.+ *+ * `EventSource` reconnects on its own with the server's `retry` interval, which+ * is exactly the behaviour a wall display needs: nothing here re-implements a+ * backoff on top of it. What this does add is a watchdog, because a stream that+ * silently stops delivering (a proxy holding a dead socket open) looks+ * identical to a quiet house, and the two must not.+ *+ * @param {string} id+ * @param {{ onGraph: Function, onStatus: Function, onOpen?: Function, onSilence?: Function }} handlers+ * @returns {{ close(): void }}+ */+export function openStream(id, handlers) {+ const url = `/api/home/${encodeURIComponent(id)}/stream`;+ const source = new EventSource(url, { withCredentials: true });+ let watchdog = 0;+ // The server heartbeats every 25 s. Two missed beats plus slack is a stream+ // that is no longer delivering, whatever the socket believes.+ const SILENCE_MS = 70_000;++ const beat = () => {+ clearTimeout(watchdog);+ watchdog = setTimeout(() => handlers.onSilence?.(), SILENCE_MS);+ };++ source.addEventListener('open', () => {+ beat();+ handlers.onOpen?.();+ });+ source.addEventListener('graph', (event) => {+ beat();+ const payload = parse(event.data);+ if (payload) handlers.onGraph(payload);+ });+ source.addEventListener('status', (event) => {+ beat();+ const payload = parse(event.data);+ if (payload) handlers.onStatus(payload);+ });+ source.addEventListener('heartbeat', beat);+ source.addEventListener('error', () => {+ // EventSource fires `error` both for a transient drop it will retry and+ // for a terminal close. `readyState` is the only honest signal of which.+ handlers.onStatus({ status: source.readyState === EventSource.CLOSED ? 'disconnected' : 'reconnecting', stale: true });+ });++ return {+ close() {+ clearTimeout(watchdog);+ source.close();+ },+ };+}++function parse(data) {+ try {+ return JSON.parse(data);+ } catch {+ return null;+ }+}diff --git a/src/home/connect.js b/src/home/connect.jsnew file mode 100644index 000000000..4f93415de--- /dev/null+++ b/src/home/connect.js@@ -0,0 +1,630 @@+/**+ * The connect flow for /smart-home.+ *+ * Gets a stranger from "I have a Home Assistant somewhere" to "my agent is+ * connected", and designs every way that goes wrong. There are eleven states+ * and a missing one is what makes a product feel unfinished, so they are+ * enumerated in STATE rather than implied by whichever branch happened to run.+ *+ * Three rules this module holds and never bends:+ *+ * 1. The access token goes to the server exactly once and never comes back.+ * It is never written to localStorage, never put in a URL, never logged,+ * and never echoed by the API. The field is cleared the moment a connect+ * succeeds.+ * 2. Reachability is decided in the browser, before the network. A+ * 192.168.x.x or .local address cannot be reached by three.ws no matter+ * how long we wait, so we say so immediately instead of spending fifteen+ * seconds arriving at a worse version of the same sentence.+ * 3. Every string that came from a house (a label, a room, an entity, an+ * error) is rendered as text. Entity and area names are attacker+ * influenced, they flow into a page and into a model prompt, and there is+ * a physical actuator on the other end.+ */++import { isPrivateHost, normalizeBaseUrl } from '@three-ws/home-bridge';++import { renderManage } from './manage.js';++/** The eleven states. Each one has a designed treatment; none falls through. */+export const STATE = Object.freeze({+ SIGNED_OUT: 'signed_out',+ EMPTY: 'empty',+ VALIDATING: 'validating',+ PRIVATE_HOST: 'private_host',+ VERIFYING: 'verifying',+ CONNECTED: 'connected',+ AUTH_FAILED: 'auth_failed',+ UNREACHABLE: 'unreachable',+ DEGRADED: 'degraded',+ REVOKED: 'revoked',+ MANY: 'many',+});++/** Where Home Assistant hides the token minting screen. Never make anyone hunt. */+const TOKEN_PATH = 'Profile, Security, Long-lived access tokens, Create token';++const root = document.getElementById('hm-root');++/** Session-lived only: never persisted, so a reload re-reads it from the server. */+let csrfToken = '';++boot();++async function boot() {+ if (!root) return;+ try {+ const homes = await listHomes();+ if (homes === null) return render(STATE.SIGNED_OUT);+ renderHomes(homes);+ } catch (err) {+ // The list failing is not the connect flow failing: offer the connect card+ // with the reason attached, so a stranger is never staring at a dead page.+ render(STATE.EMPTY, { notice: { tone: 'error', title: 'We could not load your homes.', body: messageOf(err) } });+ }+}++function renderHomes(homes) {+ if (!homes.length) return render(STATE.EMPTY);+ render(homes.length > 1 ? STATE.MANY : STATE.CONNECTED, { homes });+}++// ── The renderer ────────────────────────────────────────────────────────────++/**+ * Render one state. Every path in the flow ends in exactly one call to this, so+ * "which state am I in" is always answerable and never implicit.+ */+function render(state, data = {}) {+ root.setAttribute('aria-busy', state === STATE.VERIFYING ? 'true' : 'false');+ root.dataset.state = state;+ clear(root);++ switch (state) {+ case STATE.SIGNED_OUT: return root.append(signedOut());+ case STATE.EMPTY: return root.append(connectCard(data));+ case STATE.PRIVATE_HOST: return root.append(connectCard(data));+ case STATE.VERIFYING: return root.append(verifying(data));+ case STATE.AUTH_FAILED: return root.append(connectCard(data));+ case STATE.UNREACHABLE: return root.append(connectCard(data));+ case STATE.REVOKED: return root.append(connectCard(data));+ case STATE.CONNECTED:+ case STATE.DEGRADED:+ case STATE.MANY:+ return root.append(renderManage({ homes: data.homes || [], notice: data.notice, onDisconnect: disconnect, onReconnect: showConnectCard }));+ default:+ return root.append(connectCard(data));+ }+}++// ── State 1: signed out ─────────────────────────────────────────────────────++/**+ * A disabled form is a worse answer than an explanation: it looks broken and it+ * tells a visitor nothing about why the feature is worth signing in for.+ */+function signedOut() {+ const panel = el('section', 'hm-panel');+ panel.append(+ el('h2', 'hm-panel-title', 'Sign in to connect a home'),+ el('p', 'hm-panel-sub', 'Your homes are tied to your three.ws account, because the credential that opens your house is stored encrypted against it and never in this browser.'),+ );++ const list = el('ul', 'hm-ol');+ list.style.listStyle = 'disc';+ for (const line of [+ 'Your agent reads every room, light, lock and sensor your instance exposes.',+ 'It runs the scenes and scripts you already built, by name.',+ 'Locking up, closing and arming never prompt. Unlocking, opening and disarming always do.',+ ]) list.append(el('li', '', line));+ panel.append(list);++ const actions = el('div', 'hm-actions');+ actions.style.marginTop = 'var(--space-md)';+ const signIn = el('a', 'hm-btn hm-btn-primary', 'Sign in');+ signIn.href = `/login?next=${encodeURIComponent('/smart-home')}`;+ const learn = el('a', 'hm-btn hm-btn-ghost', 'How it works');+ learn.href = '/docs/smart-home';+ actions.append(signIn, learn);+ panel.append(actions);+ return panel;+}++// ── States 2, 4, 7, 8, 10: the connect card and its failures ────────────────++/**+ * One card serves the empty state and every recoverable failure, because they+ * differ only in the notice above the fields and in which field takes focus.+ * Rebuilding a different card per failure is how the states drift apart.+ */+function connectCard({ notice, values = {}, focus } = {}) {+ const panel = el('section', 'hm-panel');+ const head = el('div', 'hm-panel-head');+ const heading = el('div');+ heading.append(+ el('h2', 'hm-panel-title', 'Connect a Home Assistant'),+ el('p', 'hm-panel-sub', 'Everything runs against your own instance. three.ws stores the address and an access token, encrypted, and nothing else about your house.'),+ );+ head.append(heading);+ panel.append(head);++ if (notice) panel.append(noticeEl(notice));++ const form = el('form', 'hm-form');+ form.noValidate = true;++ const label = field({+ id: 'hm-label',+ label: 'What do you call it?',+ hint: 'Shown in your agent and in the action log. "Home", "The office", anything.',+ value: values.label || '',+ attrs: { type: 'text', maxlength: '120', autocomplete: 'off', placeholder: 'Home' },+ });++ const url = field({+ id: 'hm-url',+ label: 'Your Home Assistant address',+ hint: 'The https URL you use from outside the house: Home Assistant Cloud, or your own reverse proxy.',+ value: values.baseUrl || '',+ attrs: { type: 'url', inputmode: 'url', autocomplete: 'off', spellcheck: 'false', placeholder: 'https://your-home.ui.nabu.casa' },+ });++ const token = tokenField(values.token || '');++ form.append(label.wrap, url.wrap, token.wrap);++ const actions = el('div', 'hm-actions');+ const submit = el('button', 'hm-btn hm-btn-primary', 'Connect this home');+ submit.type = 'submit';+ actions.append(submit);+ form.append(actions);++ // State 3: validate as they type, before anything touches the network. The+ // message appears under the field the moment the address is unreachable in+ // principle, which is the only honest time to say it.+ const liveValidate = () => {+ const verdict = checkReachable(url.input.value);+ url.input.setAttribute('aria-invalid', verdict.ok || !url.input.value.trim() ? 'false' : 'true');+ setInlineError(url, verdict.ok ? '' : verdict.short);+ };+ url.input.addEventListener('input', liveValidate);+ url.input.addEventListener('blur', liveValidate);++ form.addEventListener('submit', (event) => {+ event.preventDefault();+ submitConnect({ form, label: label.input, url: url.input, token: token.input, submit });+ });++ panel.append(form);+ panel.append(tokenHelp());++ // Focus lands on the field that has to change, not back at the top of the+ // form, so keyboard users are not made to walk the whole card again.+ queueMicrotask(() => {+ const target = focus === 'token' ? token.input : focus === 'url' ? url.input : focus === 'label' ? label.input : null;+ if (target) {+ target.focus();+ if (typeof target.select === 'function' && focus === 'token') target.select();+ }+ });++ return panel;+}++/** Where to get a token, inline, so nobody has to go and search for it. */+function tokenHelp() {+ const wrap = el('details', 'hm-panel');+ wrap.style.marginTop = 'var(--space-md)';+ wrap.style.background = 'transparent';+ const summary = el('summary', '', 'Where do I get an access token?');+ summary.style.cursor = 'pointer';+ summary.style.fontWeight = 'var(--weight-medium)';+ wrap.append(summary);++ const steps = el('ol', 'hm-ol');+ for (const step of [+ 'Open your Home Assistant and click your user name at the bottom of the sidebar.',+ 'Go to the Security tab.',+ 'Scroll to Long-lived access tokens and choose Create token.',+ 'Name it "three.ws" and copy the token. Home Assistant shows it once.',+ ]) steps.append(el('li', '', step));+ wrap.append(steps);++ const note = el('p', 'hm-hint', 'The token is encrypted before it is stored and is never sent back to this page. Deleting it in Home Assistant revokes our access immediately, whatever we hold.');+ note.style.marginTop = 'var(--space-sm)';+ wrap.append(note);+ return wrap;+}++// ── State 5: verifying ──────────────────────────────────────────────────────++/**+ * Named steps, not a bare spinner and not a fake progress bar: each line flips+ * when that step actually completes, so the screen never claims progress it did+ * not make.+ */+function verifying({ steps = [], onCancel } = {}) {+ const panel = el('section', 'hm-panel');+ panel.append(+ el('h2', 'hm-panel-title', 'Opening a connection to your home'),+ el('p', 'hm-panel-sub', 'This runs against your instance directly. It usually takes a second or two.'),+ );++ const list = el('ul', 'hm-steps');+ for (const step of steps) {+ const li = el('li', 'hm-step');+ li.dataset.state = step.state;+ const mark = el('span', 'hm-step-mark', step.state === 'done' ? '✓' : '');+ mark.setAttribute('aria-hidden', 'true');+ li.append(mark, el('span', '', step.text));+ list.append(li);+ }+ panel.append(list);++ const actions = el('div', 'hm-actions');+ actions.style.marginTop = 'var(--space-md)';+ const cancel = el('button', 'hm-btn hm-btn-ghost', 'Cancel');+ cancel.type = 'button';+ cancel.addEventListener('click', () => onCancel && onCancel());+ actions.append(cancel);+ panel.append(actions);+ return panel;+}++// ── Submit ──────────────────────────────────────────────────────────────────++async function submitConnect({ form, label, url, token, submit }) {+ const values = { label: label.value.trim(), baseUrl: url.value.trim(), token: token.value };++ if (!values.baseUrl) {+ return render(STATE.EMPTY, {+ values: { label: values.label },+ focus: 'url',+ notice: { tone: 'error', title: 'Add your Home Assistant address.', body: 'It is the https URL you use to reach your house from outside it.' },+ });+ }+ if (!values.token) {+ return render(STATE.EMPTY, {+ values: { label: values.label, baseUrl: values.baseUrl },+ focus: 'token',+ notice: { tone: 'error', title: 'Add a long-lived access token.', body: `Create one in Home Assistant under ${TOKEN_PATH}.` },+ });+ }++ // State 4: the refusal that costs no network call at all.+ const verdict = checkReachable(values.baseUrl);+ if (!verdict.ok) {+ return render(STATE.PRIVATE_HOST, {+ values: { label: values.label, baseUrl: values.baseUrl },+ focus: 'url',+ notice: verdict.notice,+ });+ }++ submit.disabled = true;+ form.setAttribute('aria-busy', 'true');++ const controller = new AbortController();+ const steps = [+ { text: 'Checking the address', state: 'done' },+ { text: 'Opening a connection to your home', state: 'active' },+ { text: 'Reading your rooms and devices', state: 'pending' },+ { text: 'Checking for the Model Context Protocol server', state: 'pending' },+ ];+ render(STATE.VERIFYING, { steps, onCancel: () => controller.abort() });++ try {+ const home = await connectHome(values, controller.signal);+ // The token has done its one job. Drop it before anything else can read it.+ values.token = '';+ const homes = await listHomes();+ renderHomes(homes && homes.length ? homes : [home]);+ } catch (err) {+ if (err?.name === 'AbortError') {+ return render(STATE.EMPTY, {+ values: { label: values.label, baseUrl: values.baseUrl },+ focus: 'url',+ notice: { tone: 'info', title: 'Cancelled.', body: 'Nothing was stored. Try again whenever you are ready.' },+ });+ }+ renderFailure(err, values);+ }+}++/** Maps the API error contract onto the designed failure states. */+function renderFailure(err, values) {+ const code = err?.code || 'call_failed';+ const carried = { label: values.label, baseUrl: values.baseUrl };++ // State 7: a wrong token is a specific, fixable thing. Say which thing.+ if (code === 'auth') {+ return render(STATE.AUTH_FAILED, {+ values: carried,+ focus: 'token',+ notice: {+ tone: 'error',+ title: 'Home Assistant rejected that token.',+ body: `Tokens are one per line and easy to truncate on copy. Create a fresh one under ${TOKEN_PATH}, then paste the whole string.`,+ },+ });+ }++ // State 8: distinguish "wrong address" from "the house is not answering".+ if (code === 'unreachable') {+ return render(STATE.UNREACHABLE, {+ values: carried,+ focus: 'url',+ notice: {+ tone: 'error',+ title: 'We could not reach that address.',+ body: messageOf(err),+ bullets: [+ 'If the address is right, check the house is online and reachable from outside your network.',+ 'If it is only reachable at home, three.ws cannot route to it. The add-on that dials out from inside your network is the path for that.',+ ],+ },+ });+ }++ if (code === 'bad_url') {+ return render(STATE.EMPTY, {+ values: carried,+ focus: 'url',+ notice: { tone: 'error', title: 'That address does not look right.', body: messageOf(err) },+ });+ }++ return render(STATE.EMPTY, {+ values: carried,+ focus: 'url',+ notice: { tone: 'error', title: 'That did not work.', body: messageOf(err) },+ });+}++function showConnectCard(notice) {+ render(STATE.EMPTY, notice ? { notice } : {});+}++// ── Reachability, decided here, before the network ──────────────────────────++/**+ * The whole point of running this in the browser: a LAN address is unreachable+ * by definition, and telling someone that in the same keystroke beats timing out+ * fifteen seconds later with a vaguer version of the same sentence.+ */+export function checkReachable(input) {+ const raw = String(input || '').trim();+ if (!raw) return { ok: true, short: '' };++ let parsed;+ try {+ parsed = normalizeBaseUrl(raw);+ } catch (err) {+ return {+ ok: false,+ short: 'That is not a web address we can use.',+ notice: { tone: 'error', title: 'That address does not look right.', body: err?.message || 'Use the full https URL of your Home Assistant.' },+ };+ }++ const host = new URL(parsed.http).hostname;+ if (isPrivateHost(host)) {+ return {+ ok: false,+ short: `${host} is only on your home network.`,+ notice: {+ tone: 'warn',+ title: `${host} is an address on your home network.`,+ body: 'three.ws runs on the public internet, so it cannot reach an address that only exists inside your house. There are two real ways round it.',+ bullets: [+ 'Use your remote https address instead. Home Assistant Cloud gives you one, and so does your own reverse proxy. That works today, with the token you already have.',+ 'Or install the three.ws add-on inside your Home Assistant, which dials out to us so nothing has to be exposed to the internet.',+ ],+ },+ };+ }++ if (!parsed.secure) {+ return {+ ok: false,+ short: 'A plain http address cannot be reached from this page.',+ notice: {+ tone: 'warn',+ title: 'That is a plain http address.',+ body: 'This page is served over https, and a browser will not open an unencrypted connection from it. Use the https address for your house.',+ },+ };+ }++ return { ok: true, short: '' };+}++// ── API ─────────────────────────────────────────────────────────────────────++/** @returns {Promise<object[]|null>} null when there is no session at all. */+async function listHomes() {+ const res = await fetch('/api/home', { credentials: 'include', headers: { accept: 'application/json' } });+ if (res.status === 401) return null;+ const body = await readJson(res);+ if (!res.ok) throw apiError(body, res);+ return Array.isArray(body?.homes) ? body.homes : [];+}++async function connectHome({ label, baseUrl, token }, signal) {+ const res = await fetch('/api/home/connect', {+ method: 'POST',+ credentials: 'include',+ signal,+ headers: { 'content-type': 'application/json', accept: 'application/json', ...(await csrfHeader()) },+ body: JSON.stringify({ label, baseUrl, token }),+ });+ const body = await readJson(res);+ if (!res.ok) throw apiError(body, res);+ return body?.home || body;+}++async function disconnect(home) {+ const res = await fetch(`/api/home/${encodeURIComponent(home.id)}`, {+ method: 'DELETE',+ credentials: 'include',+ headers: { accept: 'application/json', ...(await csrfHeader()) },+ });+ const body = await readJson(res);+ if (!res.ok) throw apiError(body, res);++ // State 10: say plainly what happened to the stored credential.+ const homes = await listHomes();+ const notice = {+ tone: 'ok',+ title: `${home.label} is disconnected.`,+ body: 'The access token we held has been erased. Delete the token in Home Assistant too if you want it gone on both sides, under ' + TOKEN_PATH + '.',+ };+ if (homes && homes.length) render(homes.length > 1 ? STATE.MANY : STATE.CONNECTED, { homes, notice });+ else render(STATE.REVOKED, { notice });+}++async function csrfHeader() {+ if (csrfToken) {+ const header = { 'x-csrf-token': csrfToken };+ csrfToken = '';+ return header;+ }+ try {+ const res = await fetch('/api/csrf-token', { credentials: 'include' });+ if (!res.ok) return {};+ const body = await res.json();+ const token = body?.token || body?.data?.token;+ return token ? { 'x-csrf-token': token } : {};+ } catch {+ return {};+ }+}++async function readJson(res) {+ try {+ return await res.json();+ } catch {+ return null;+ }+}++/**+ * The API's coded failure, as an Error the render layer can branch on. The+ * message is whatever the server said, because the server is the only thing+ * that knows whether the token was wrong or the house was asleep.+ */+function apiError(body, res) {+ const err = new Error(body?.message || body?.error_description || body?.error || `Request failed (${res.status}).`);+ err.code = body?.code || (res.status === 404 ? 'not_found' : 'call_failed');+ err.status = res.status;+ return err;+}++function messageOf(err) {+ return err?.message || 'Something went wrong reaching your home.';+}++// ── DOM helpers: text only, never innerHTML ─────────────────────────────────++/**+ * Everything rendered through here is `textContent`. Entity names, area names+ * and labels are strings a stranger or a compromised integration can control,+ * and the other end of this page is a physical actuator.+ */+export function el(tag, className, text) {+ const node = document.createElement(tag);+ if (className) node.className = className;+ if (text != null) node.textContent = String(text);+ return node;+}++export function clear(node) {+ while (node.firstChild) node.removeChild(node.firstChild);+}++export function noticeEl({ tone = 'info', title, body, bullets } = {}) {+ const wrap = el('div', `hm-notice hm-notice-${tone}`);+ wrap.setAttribute('role', tone === 'error' ? 'alert' : 'status');++ const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ icon.setAttribute('class', 'hm-notice-icon');+ icon.setAttribute('viewBox', '0 0 16 16');+ icon.setAttribute('aria-hidden', 'true');+ icon.setAttribute('fill', 'currentColor');+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');+ path.setAttribute('d', tone === 'ok'+ ? 'M8 0a8 8 0 100 16A8 8 0 008 0zm3.7 5.9l-4.2 5.3a.8.8 0 01-1.2.05L3.9 8.8a.8.8 0 111.2-1l1.8 2 3.6-4.6a.8.8 0 011.2 1z'+ : 'M8 0a8 8 0 100 16A8 8 0 008 0zm0 3.4a1 1 0 011 1v4.2a1 1 0 11-2 0V4.4a1 1 0 011-1zm0 7.3a1.1 1.1 0 110 2.2 1.1 1.1 0 010-2.2z');+ icon.append(path);++ const content = el('div');+ if (title) content.append(el('p', 'hm-notice-title', title));+ if (body) content.append(el('p', 'hm-notice-body', body));+ if (bullets?.length) {+ const ul = el('ul');+ for (const line of bullets) ul.append(el('li', '', line));+ content.append(ul);+ }+ wrap.append(icon, content);+ return wrap;+}++function field({ id, label, hint, value, attrs = {} }) {+ const wrap = el('div', 'hm-field');+ const labelEl = el('label', 'hm-label', label);+ labelEl.htmlFor = id;+ const input = el('input', 'hm-input');+ input.id = id;+ for (const [key, val] of Object.entries(attrs)) input.setAttribute(key, val);+ input.value = value || '';+ const hintEl = el('p', 'hm-hint', hint);+ hintEl.id = `${id}-hint`;+ input.setAttribute('aria-describedby', hintEl.id);+ wrap.append(labelEl, input, hintEl);+ return { wrap, input, hint: hintEl, baseHint: hint };+}++/** Inline, per-field validation text. Replaces the hint rather than stacking. */+function setInlineError(f, message) {+ f.hint.textContent = message || f.baseHint;+ f.hint.style.color = message ? 'var(--hm-down)' : '';+}++/**+ * The token field: a password input with a reveal toggle, no autocomplete, and+ * no path to storage. It is never read back from anywhere but this element.+ */+function tokenField(value) {+ const wrap = el('div', 'hm-field');+ const labelEl = el('label', 'hm-label', 'Long-lived access token');+ labelEl.htmlFor = 'hm-token';++ const shell = el('div', 'hm-secret');+ const input = el('input', 'hm-input');+ input.id = 'hm-token';+ input.type = 'password';+ input.value = value || '';+ input.setAttribute('autocomplete', 'off');+ input.setAttribute('autocapitalize', 'off');+ input.setAttribute('autocorrect', 'off');+ input.setAttribute('spellcheck', 'false');+ input.setAttribute('placeholder', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...');++ const toggle = el('button', 'hm-reveal', 'Show');+ toggle.type = 'button';+ toggle.setAttribute('aria-pressed', 'false');+ toggle.addEventListener('click', () => {+ const revealed = input.type === 'text';+ input.type = revealed ? 'password' : 'text';+ toggle.textContent = revealed ? 'Show' : 'Hide';+ toggle.setAttribute('aria-pressed', String(!revealed));+ input.focus();+ });++ shell.append(input, toggle);+ const hintEl = el('p', 'hm-hint', 'Sent to three.ws once, encrypted at rest, and never returned to this page or saved in this browser.');+ hintEl.id = 'hm-token-hint';+ input.setAttribute('aria-describedby', hintEl.id);+ wrap.append(labelEl, shell, hintEl);+ return { wrap, input };+}diff --git a/src/home/manage.js b/src/home/manage.jsnew file mode 100644index 000000000..ea9fb6a5a--- /dev/null+++ b/src/home/manage.js@@ -0,0 +1,231 @@+/**+ * The manage view: states 6 (connected), 9 (degraded) and 11 (many homes).+ *+ * One list that scales from one house to many without a redesign, a measured+ * summary per house rather than an assumed one, the standing allowances with a+ * revoke on each, the action log, and a disconnect that says plainly what it+ * does to the stored token.+ *+ * State 9 is the one that separates a product from a demo: when a house stops+ * answering, the last known room list stays on screen, visibly marked stale with+ * its age. A user watching their home should see it go grey, not watch it vanish.+ */++import { clear, el, noticeEl } from './connect.js';++/** Past this, "moments ago" stops being honest. */+const STALE_AFTER_MS = 90_000;++export function renderManage({ homes, notice, onDisconnect, onReconnect }) {+ const frag = document.createDocumentFragment();+ if (notice) frag.append(noticeEl(notice));++ const panel = el('section', 'hm-panel');+ const head = el('div', 'hm-panel-head');+ const heading = el('div');+ heading.append(+ el('h2', 'hm-panel-title', homes.length === 1 ? 'Your home' : `Your homes (${homes.length})`),+ el('p', 'hm-panel-sub', 'Your agent can read everything here. Anything that unlocks, opens or disarms still stops and asks, unless you have granted it below.'),+ );+ head.append(heading);++ const add = el('button', 'hm-btn hm-btn-ghost', 'Connect another');+ add.type = 'button';+ add.addEventListener('click', () => onReconnect && onReconnect());+ head.append(add);+ panel.append(head);++ const list = el('ul', 'hm-list');+ for (const home of homes) list.append(homeCard(home, { onDisconnect }));+ panel.append(list);+ frag.append(panel);+ return frag;+}++function homeCard(home, { onDisconnect }) {+ const li = el('li');+ const card = el('div', 'hm-card');++ const main = el('div', 'hm-card-main');+ // textContent throughout: the label is whatever the user typed and the URL is+ // whatever they pasted.+ main.append(el('p', 'hm-card-label', home.label || hostOf(home.base_url)));+ main.append(el('p', 'hm-card-url', home.base_url || ''));+ main.append(statusLine(home));++ const actions = el('div', 'hm-card-actions');+ const open = el('a', 'hm-btn hm-btn-ghost', 'Open');+ open.href = `/smart-home/${encodeURIComponent(home.id)}`;+ const drop = el('button', 'hm-btn hm-btn-danger', 'Disconnect');+ drop.type = 'button';+ drop.addEventListener('click', () => confirmDisconnect(card, home, onDisconnect));+ actions.append(open, drop);++ card.append(main, actions);+ li.append(card);++ const detail = el('div');+ detail.style.marginTop = 'var(--space-sm)';+ detail.append(summary(home));+ li.append(detail);+ return li;+}++/**+ * The measured summary. Every number here came back from the house at connect+ * time; a capability we could not measure prints as "not measured", never as a+ * confident zero.+ */+function summary(home) {+ const caps = home.capabilities || {};+ const wrap = el('div', 'hm-stats');+ wrap.append(+ stat(count(caps.areaCount), 'Rooms'),+ stat(count(caps.entityCount), 'Devices'),+ stat(count(caps.macroCount), 'Scenes'),+ stat(caps.haVersion || 'Not measured', 'Home Assistant'),+ );++ const holder = el('div');+ holder.append(wrap);++ // A house without mcp_server is an ordinary house, so this is an upgrade+ // offer, never an error.+ if (caps.mcp) {+ holder.append(noticeEl({+ tone: 'ok',+ title: `Model Context Protocol server connected (${count(caps.mcpToolCount)} tools).`,+ body: 'Your agent uses the exact tools you exposed in Home Assistant, with your own exposure rules.',+ }));+ } else if (caps.websocket) {+ holder.append(noticeEl({+ tone: 'info',+ title: 'Optional: turn on the Model Context Protocol server.',+ body: 'Add the Model Context Protocol Server integration in Home Assistant, under Settings, Devices and services, to give your agent the exact tool set you curated. Everything already works without it.',+ }));+ }+ return holder;+}++function stat(value, label) {+ const box = el('div', 'hm-stat');+ box.append(el('span', 'hm-stat-value', value), el('span', 'hm-stat-label', label));+ return box;+}++function count(value) {+ return Number.isFinite(Number(value)) ? String(Number(value)) : 'Not measured';+}++/**+ * State 9 lives here. A connected home whose last handshake has aged past the+ * window is rendered as stale with its age spelled out, so "is this live?" is+ * answerable at a glance rather than inferred from a dot nobody can read.+ */+function statusLine(home) {+ const wrap = el('p', 'hm-status');+ const stale = isStale(home);+ const key = stale ? 'stale' : home.status || 'pending';++ const dot = el('span', `hm-dot hm-dot-${key}`);+ dot.setAttribute('aria-hidden', 'true');+ wrap.append(dot, el('span', '', statusText(home, stale)));+ return wrap;+}++function isStale(home) {+ if (home.status !== 'connected') return false;+ const last = Date.parse(home.last_ok_at || '');+ if (!Number.isFinite(last)) return false;+ return Date.now() - last > STALE_AFTER_MS;+}++function statusText(home, stale) {+ if (stale) return `Last answered ${ago(home.last_ok_at)}. Showing the last state we saw.`;+ switch (home.status) {+ case 'connected': return `Live${home.last_ok_at ? `, updated ${ago(home.last_ok_at)}` : ''}.`;+ case 'auth_failed': return home.status_detail || 'Home Assistant rejected the stored token. Reconnect with a new one.';+ case 'unreachable': return home.status_detail || 'Not answering right now. The last state we saw is below.';+ case 'revoked': return 'Disconnected.';+ default: return home.status_detail || 'Connecting.';+ }+}++/** Plain language, and never a future tense for a past timestamp. */+function ago(iso) {+ const then = Date.parse(iso || '');+ if (!Number.isFinite(then)) return 'at an unknown time';+ const seconds = Math.max(0, Math.round((Date.now() - then) / 1000));+ if (seconds < 45) return 'moments ago';+ const minutes = Math.round(seconds / 60);+ if (minutes < 60) return `${minutes} minute${minutes === 1 ? '' : 's'} ago`;+ const hours = Math.round(minutes / 60);+ if (hours < 24) return `${hours} hour${hours === 1 ? '' : 's'} ago`;+ const days = Math.round(hours / 24);+ return `${days} day${days === 1 ? '' : 's'} ago`;+}++/**+ * Disconnecting destroys a credential, so it confirms in place rather than+ * behind a browser dialog: the confirmation says exactly what happens to the+ * token, on our side and on theirs.+ */+function confirmDisconnect(card, home, onDisconnect) {+ const existing = card.parentElement.querySelector('[data-confirm]');+ if (existing) existing.remove();++ const box = el('div', 'hm-notice hm-notice-warn');+ box.dataset.confirm = 'true';+ box.setAttribute('role', 'alertdialog');+ box.setAttribute('aria-label', `Disconnect ${home.label || 'this home'}`);++ const content = el('div');+ content.append(+ el('p', 'hm-notice-title', `Disconnect ${home.label || hostOf(home.base_url)}?`),+ el('p', 'hm-notice-body', 'The access token we hold is erased immediately and your agent loses all access to this house. Your standing allowances and the action log are kept so you can still read what happened.'),+ el('p', 'hm-notice-body', 'This does not delete the token inside Home Assistant. Delete it there too if you want it gone on both sides.'),+ );++ const actions = el('div', 'hm-actions');+ actions.style.marginTop = 'var(--space-sm)';+ const yes = el('button', 'hm-btn hm-btn-danger', 'Disconnect and erase the token');+ yes.type = 'button';+ const no = el('button', 'hm-btn hm-btn-ghost', 'Keep it connected');+ no.type = 'button';++ no.addEventListener('click', () => {+ box.remove();+ card.querySelector('.hm-btn-danger')?.focus();+ });+ yes.addEventListener('click', async () => {+ yes.disabled = true;+ no.disabled = true;+ yes.textContent = 'Disconnecting';+ try {+ await onDisconnect(home);+ } catch (err) {+ clear(content);+ content.append(+ el('p', 'hm-notice-title', 'That did not go through.'),+ el('p', 'hm-notice-body', err?.message || 'Try again in a moment.'),+ );+ yes.disabled = false;+ no.disabled = false;+ yes.textContent = 'Try again';+ }+ });++ actions.append(yes, no);+ content.append(actions);+ box.append(content);+ card.parentElement.append(box);+ yes.focus();+}++function hostOf(url) {+ try {+ return new URL(url).host;+ } catch {+ return url || 'this home';+ }+}diff --git a/src/home/scene-fallback.js b/src/home/scene-fallback.jsnew file mode 100644index 000000000..b5ebb9e71--- /dev/null+++ b/src/home/scene-fallback.js@@ -0,0 +1,259 @@+/**+ * The 2D house.+ *+ * Not a consolation prize. This is the accessibility path, the old-device path+ * and the "WebGL is blocked by policy" path, and it has to be able to do+ * everything the 3D scene can do: read the whole house and act on it. It reads+ * the SAME scene model, so a room that exists in one exists in the other and+ * the two cannot drift.+ *+ * It is also the automatic destination for a device that measurably cannot hold+ * a frame rate, which is why it is built to be genuinely good rather than+ * merely present.+ */++/** Domains a person can act on from here, and the two services each offers. */+const CONTROLS = {+ light: { on: ['light', 'turn_on', 'Turn on'], off: ['light', 'turn_off', 'Turn off'] },+ switch: { on: ['switch', 'turn_on', 'Turn on'], off: ['switch', 'turn_off', 'Turn off'] },+ fan: { on: ['fan', 'turn_on', 'Turn on'], off: ['fan', 'turn_off', 'Turn off'] },+ lock: { on: ['lock', 'unlock', 'Unlock'], off: ['lock', 'lock', 'Lock'] },+ cover: { on: ['cover', 'open_cover', 'Open'], off: ['cover', 'close_cover', 'Close'] },+ media_player: { on: ['media_player', 'media_play', 'Play'], off: ['media_player', 'media_pause', 'Pause'] },+ vacuum: { on: ['vacuum', 'start', 'Start'], off: ['vacuum', 'return_to_base', 'Send home'] },+};++/**+ * @param {HTMLElement} container+ * @param {object} options+ * @param {(request: { entityId: string, domain: string, service: string, name: string, roomId: string }) => void} options.onAct+ * @param {(roomId: string) => void} [options.onFocusRoom]+ */+export function createHomeFallback(container, options = {}) {+ container.classList.add('hs-flat');+ container.innerHTML = '';+ const list = document.createElement('div');+ list.className = 'hs-flat-floors';+ container.appendChild(list);++ let model = null;+ let stale = false;+ let busy = new Set();++ function render() {+ if (!model) return;+ list.innerHTML = '';+ for (const floor of model.floors) {+ const section = document.createElement('section');+ section.className = 'hs-flat-floor';+ const heading = document.createElement('h2');+ heading.className = 'hs-flat-floor-name';+ heading.textContent = floor.name;+ section.appendChild(heading);++ const grid = document.createElement('div');+ grid.className = 'hs-flat-grid';+ for (const roomId of floor.roomIds) {+ const room = model.rooms.find((r) => r.id === roomId);+ if (room) grid.appendChild(roomCard(room));+ }+ section.appendChild(grid);+ list.appendChild(section);+ }+ }++ function roomCard(room) {+ const card = document.createElement('article');+ card.className = 'hs-card';+ card.dataset.roomId = room.id;+ if (stale) card.classList.add('is-stale');+ // The room's real light, as a real gradient: a dark room is dark here too.+ card.style.setProperty('--room-light', room.light.hex);+ card.style.setProperty('--room-glow', String(room.light.on ? Math.min(0.55, 0.12 + room.light.brightness * 0.4) : 0));++ const head = document.createElement('header');+ head.className = 'hs-card-head';+ const title = document.createElement('button');+ title.type = 'button';+ title.className = 'hs-card-title';+ title.textContent = room.name;+ title.addEventListener('click', () => options.onFocusRoom?.(room.id));+ head.appendChild(title);++ const meta = document.createElement('p');+ meta.className = 'hs-card-meta';+ const bits = [];+ bits.push(room.light.total ? `${room.light.count} of ${room.light.total} lights on` : 'no lights');+ if (room.climate) bits.push(`${room.climate.label} from ${room.climate.sources} ${room.climate.sources === 1 ? 'sensor' : 'sensors'}`);+ if (room.security) bits.push(room.security.secure ? 'secure' : `${room.security.unlocked.length + room.security.open.length} open`);+ meta.textContent = bits.join(' · ');+ head.appendChild(meta);+ card.appendChild(head);++ if (room.security && !room.security.secure) {+ const flag = document.createElement('p');+ flag.className = 'hs-card-flag';+ flag.textContent = describeOpen(room);+ card.appendChild(flag);+ }++ const items = document.createElement('ul');+ items.className = 'hs-card-items';+ for (const object of room.objects) items.appendChild(entityRow(object, room));+ card.appendChild(items);++ if (room.readouts.length) {+ const readouts = document.createElement('dl');+ readouts.className = 'hs-card-readouts';+ for (const readout of room.readouts) {+ const dt = document.createElement('dt');+ dt.textContent = readout.name;+ const dd = document.createElement('dd');+ dd.textContent = `${readout.value}${readout.unit ? ` ${readout.unit}` : ''}`;+ readouts.append(dt, dd);+ }+ card.appendChild(readouts);+ }++ if (room.hiddenCount) {+ const more = document.createElement('p');+ more.className = 'hs-card-more';+ more.textContent = `${room.hiddenCount} more ${room.hiddenCount === 1 ? 'device' : 'devices'} in this room`;+ card.appendChild(more);+ }+ return card;+ }++ function entityRow(object, room) {+ const row = document.createElement('li');+ row.className = 'hs-item';+ row.dataset.entityId = object.entityId;+ if (!object.available) row.classList.add('is-unavailable');++ const dot = document.createElement('span');+ dot.className = 'hs-item-dot';+ dot.dataset.kind = object.kind;+ dot.style.setProperty('--dot', dotColor(object, room));+ dot.setAttribute('aria-hidden', 'true');+ row.appendChild(dot);++ const name = document.createElement('span');+ name.className = 'hs-item-name';+ name.textContent = object.name;+ row.appendChild(name);++ const state = document.createElement('span');+ state.className = 'hs-item-state';+ state.textContent = object.available ? readableState(object) : 'unreachable';+ row.appendChild(state);++ const control = CONTROLS[object.domain];+ if (control && object.available) {+ const active = object.activity > 0.02;+ const [domain, service, label] = active ? control.off : control.on;+ const button = document.createElement('button');+ button.type = 'button';+ button.className = 'hs-item-act';+ button.textContent = busy.has(object.entityId) ? 'Working' : label;+ button.disabled = busy.has(object.entityId);+ button.setAttribute('aria-label', `${label} ${object.name} in ${room.name}`);+ button.addEventListener('click', () => {+ options.onAct?.({ entityId: object.entityId, domain, service, name: object.name, roomId: room.id });+ });+ row.appendChild(button);+ }+ return row;+ }++ function dotColor(object, room) {+ if (!object.available) return 'rgba(224, 90, 74, 0.55)';+ if (object.domain === 'light') return object.activity > 0 ? room.light.hex : 'rgba(255,255,255,0.16)';+ if (object.domain === 'lock') return object.activity > 0.5 ? '#e05a4a' : '#2fbf71';+ if (object.domain === 'cover' || object.domain === 'binary_sensor') return object.activity > 0.02 ? '#e0a33a' : 'rgba(255,255,255,0.16)';+ return object.activity > 0.4 ? '#8fa6ff' : 'rgba(255,255,255,0.16)';+ }++ function readableState(object) {+ if (object.domain === 'cover') {+ const position = Number(object.attributes?.current_position);+ if (Number.isFinite(position)) return position === 0 ? 'closed' : position === 100 ? 'open' : `${position}% open`;+ }+ if (object.domain === 'climate') {+ const current = Number(object.attributes?.current_temperature);+ if (Number.isFinite(current)) return `${object.state} · ${current}°`;+ }+ if (object.domain === 'light' && object.activity > 0) {+ const brightness = Number(object.attributes?.brightness);+ if (Number.isFinite(brightness)) return `on · ${Math.round((brightness / 255) * 100)}%`;+ }+ return String(object.state);+ }++ function describeOpen(room) {+ const names = [];+ for (const entityId of [...room.security.unlocked, ...room.security.open]) {+ const object = room.objects.find((o) => o.entityId === entityId);+ names.push(object ? object.name : entityId);+ }+ if (!names.length) return 'Something in this room is open.';+ const verb = room.security.unlocked.length ? 'unlocked' : 'open';+ return `${names.slice(0, 3).join(', ')}${names.length > 3 ? ` and ${names.length - 3} more` : ''} ${names.length === 1 ? 'is' : 'are'} ${verb}.`;+ }++ return {+ setModel(next) {+ model = next;+ render();+ },+ setStale(next) {+ stale = Boolean(next);+ container.classList.toggle('is-stale', stale);+ for (const card of list.querySelectorAll('.hs-card')) card.classList.toggle('is-stale', stale);+ },+ setBusy(entityIds) {+ busy = new Set(entityIds);+ render();+ },+ focusRoom(roomId) {+ const card = list.querySelector(`[data-room-id="${cssEscape(roomId)}"]`);+ card?.scrollIntoView({ behavior: 'smooth', block: 'center' });+ card?.classList.add('is-focused');+ setTimeout(() => card?.classList.remove('is-focused'), 1800);+ },+ /** Same shape the WebGL scene exposes, so the page treats them alike. */+ setActing(next) {+ if (next?.roomId) this.focusRoom(next.roomId);+ },+ stats() {+ return { fps: 0, objects: model ? model.stats.drawn : 0, rooms: model ? model.rooms.length : 0, mode: '2d' };+ },+ dispose() {+ container.innerHTML = '';+ container.classList.remove('hs-flat');+ },+ };+}++function cssEscape(value) {+ return typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(value) : String(value).replace(/["\\]/g, '\\$&');+}++/**+ * Can this browser actually run the 3D scene? Asked once, answered honestly:+ * a context that fails to create, a software rasterizer, or a device the caller+ * already measured as too slow all route to the 2D house rather than to a black+ * canvas with a spinner over it.+ */+export function webglAvailable() {+ if (typeof document === 'undefined') return false;+ try {+ const canvas = document.createElement('canvas');+ const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');+ if (!gl) return false;+ const lose = gl.getExtension('WEBGL_lose_context');+ lose?.loseContext();+ return true;+ } catch {+ return false;+ }+}diff --git a/src/home/scene-render.js b/src/home/scene-render.jsnew file mode 100644index 000000000..5661e0d71--- /dev/null+++ b/src/home/scene-render.js@@ -0,0 +1,884 @@+/**+ * The live 3D home.+ *+ * Geometry comes from `scene-model.js`, which is pure and testable; this file+ * owns Three.js, the render loop and the transitions. The split matters: the+ * layout of a real house is asserted in a unit test with no GPU, and everything+ * here is about how a change LOOKS when it arrives.+ *+ * Three properties are non-negotiable, and each one has code that exists only+ * to hold it:+ *+ * * A real light changing in Home Assistant reaches the screen inside one+ * animation frame of the event arriving. `applyModel` retargets in place+ * from a diff, so a burst of a hundred entities touches a hundred numbers+ * and rebuilds nothing.+ * * Nothing pops. Every visual quantity is a spring toward a target, damped+ * framerate-independently, so a light comes up rather than snapping on.+ * * The house never empties. A dropped socket desaturates the scene and shows+ * its age; the last known state stays on screen, because a person watching+ * their home should see it go grey, not watch it vanish.+ */++import {+ AmbientLight,+ BoxGeometry,+ CanvasTexture,+ Color,+ CylinderGeometry,+ ConeGeometry,+ Group,+ HemisphereLight,+ LinearFilter,+ Mesh,+ MeshBasicMaterial,+ MeshStandardMaterial,+ PerspectiveCamera,+ PlaneGeometry,+ PointLight,+ Raycaster,+ Scene,+ SphereGeometry,+ Sprite,+ SpriteMaterial,+ Vector2,+ Vector3,+ WebGLRenderer,+} from 'three';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { createFrameGovernor, FPS_ACTIVE, FPS_IDLE, FPS_SAVER, getPowerSaver, onPowerSaverChange, trackWindowFocus } from '../shared/frame-governor.js';+import { diffScene } from './scene-model.js';++/** Real point lights cost shader time per fragment; emissive glow does not. */+const MAX_ROOM_LIGHTS = 12;++/** Damping half-life in seconds. Fast enough to feel instant, slow enough to read. */+const EASE = 0.09;++const GREY = new Color(0x6a7080);+const WARM = new Color(0xff8a3d);+const COOL = new Color(0x4fc3f7);++const SURFACE = 0x11131c;+const WALL = 0x2b3042;+const SECURE = 0x2fbf71;+const OPEN = 0xe0a33a;+const ALERT = 0xe05a4a;++/**+ * Geometry is shared across every object of a kind: one BoxGeometry serves+ * every wall plate in the house. Materials are per object, because colour is+ * per object, and they are disposed with the object.+ */+function sharedGeometry() {+ return {+ slab: new BoxGeometry(1, 1, 1),+ panel: new BoxGeometry(1, 1, 1),+ bulb: new SphereGeometry(0.15, 16, 12),+ blade: new BoxGeometry(0.62, 0.02, 0.1),+ puck: new CylinderGeometry(0.19, 0.19, 0.09, 18),+ post: new CylinderGeometry(0.07, 0.07, 0.86, 10),+ cone: new ConeGeometry(0.11, 0.24, 10),+ ring: new CylinderGeometry(0.17, 0.17, 0.05, 20),+ plane: new PlaneGeometry(1, 1),+ };+}++/**+ * @param {HTMLElement} container+ * @param {object} [options]+ * @param {(entityId: string|null, object: object|null) => void} [options.onSelect]+ * @param {(roomId: string) => void} [options.onFocusRoom]+ * @param {() => void} [options.onFirstFrame]+ */+export function createHomeScene(container, options = {}) {+ const renderer = new WebGLRenderer({ antialias: true, alpha: true, powerPreference: 'high-performance' });+ renderer.setClearColor(0x000000, 0);+ // A phone at devicePixelRatio 3 renders nine times the fragments of a+ // desktop for a scene nobody looks at that closely. 2 is the point past+ // which the extra pixels stop being visible and start costing frames.+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ container.appendChild(renderer.domElement);+ renderer.domElement.setAttribute('aria-hidden', 'true');+ renderer.domElement.style.display = 'block';+ renderer.domElement.style.width = '100%';+ renderer.domElement.style.height = '100%';+ renderer.domElement.style.touchAction = 'none';++ const scene = new Scene();+ const camera = new PerspectiveCamera(46, 1, 0.1, 400);+ const controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ controls.dampingFactor = 0.08;+ controls.maxPolarAngle = Math.PI * 0.49;+ controls.minDistance = 4;+ controls.maxDistance = 140;++ scene.add(new AmbientLight(0xffffff, 0.16));+ const sky = new HemisphereLight(0x8fa6ff, 0x0b0d14, 0.34);+ scene.add(sky);++ const geo = sharedGeometry();+ const world = new Group();+ scene.add(world);++ /** @type {Map<string, object>} entityId to its live object record */+ const objects = new Map();+ /** @type {Map<string, object>} roomId to its live room record */+ const rooms = new Map();+ const spare = { color: new Color(), target: new Color(), v: new Vector3() };++ let model = null;+ let stale = false;+ let staleAmount = 0;+ let acting = null;+ let actingUntil = 0;+ let selected = null;+ let agent = null;+ let disposed = false;+ let firstFrameSent = false;+ let frames = 0;+ let fpsWindowStart = 0;+ let fps = 0;++ const raycaster = new Raycaster();+ const pointer = new Vector2();+ const governor = createFrameGovernor();+ const focus = trackWindowFocus();+ let powerSaver = getPowerSaver();+ const stopPowerSaver = onPowerSaverChange((on) => {+ powerSaver = on;+ });++ // ── structure ─────────────────────────────────────────────────────────────++ /** Rebuild the house. Called when the set of rooms or entities changes. */+ function setModel(next) {+ const structural = !model || structureKey(model) !== structureKey(next);+ if (!structural) return applyModel(next);+ clearWorld();+ model = next;+ for (const room of next.rooms) rooms.set(room.id, buildRoom(room));+ frameCamera(next);+ placeAgent(next.agent);+ applyModel(next, { snap: true });+ }++ /**+ * Retarget every changed value in place. This is the hot path: it must not+ * allocate a mesh, a material or an array proportional to the update.+ */+ function applyModel(next, { snap = false } = {}) {+ const previous = model;+ model = next;+ const delta = previous ? diffScene(previous, next) : null;++ for (const room of next.rooms) {+ const record = rooms.get(room.id);+ if (!record) continue;+ record.source = room;+ record.targetIntensity = room.light.intensity;+ record.targetColor.set(room.light.hex);+ record.targetSecure = room.security ? (room.security.secure ? 0 : 1) : 0;+ if (record.labelText !== labelFor(room)) {+ record.labelText = labelFor(room);+ paintLabel(record);+ }+ if (snap) {+ record.intensity = record.targetIntensity;+ record.color.copy(record.targetColor);+ record.secure = record.targetSecure;+ commitRoom(record);+ }+ }++ const touched = delta ? [...delta.changed, ...delta.added] : allObjects(next);+ for (const object of touched) {+ const record = objects.get(object.entityId);+ if (!record) continue;+ record.source = object;+ record.targetActivity = object.activity;+ record.targetAvailable = object.available ? 1 : 0;+ if (snap) {+ record.activity = record.targetActivity;+ record.availability = record.targetAvailable;+ commitObject(record);+ }+ }+ }++ /** Only these change the geometry; everything else is a value on a mesh. */+ function structureKey(m) {+ return m.rooms.map((r) => `${r.id}:${r.x},${r.y},${r.z}:${r.objects.map((o) => o.entityId).join(',')}`).join('|');+ }++ function allObjects(m) {+ const out = [];+ for (const room of m.rooms) out.push(...room.objects);+ return out;+ }++ function buildRoom(room) {+ const group = new Group();+ group.position.set(room.x, room.y, room.z);+ world.add(group);++ const floorMat = new MeshStandardMaterial({ color: SURFACE, roughness: 0.92, metalness: 0.02, emissive: new Color(0x000000) });+ const floor = new Mesh(geo.slab, floorMat);+ floor.scale.set(room.w, 0.12, room.d);+ floor.position.y = -0.06;+ floor.userData.roomId = room.id;+ group.add(floor);++ // Waist-high walls, translucent. Full-height walls would hide the room's+ // contents from every angle an orbiting camera can reach, and a dollhouse+ // you cannot see into is a box.+ const wallMat = new MeshStandardMaterial({ color: WALL, roughness: 0.75, metalness: 0.05, transparent: true, opacity: 0.34 });+ const h = 0.92;+ for (const [sx, sz, px, pz] of [+ [room.w, 0.06, 0, -room.d / 2],+ [room.w, 0.06, 0, room.d / 2],+ [0.06, room.d, -room.w / 2, 0],+ [0.06, room.d, room.w / 2, 0],+ ]) {+ const wall = new Mesh(geo.panel, wallMat);+ wall.scale.set(sx, h, sz);+ wall.position.set(px, h / 2, pz);+ group.add(wall);+ }++ // The security tell: a line around the room's foot that goes amber the+ // moment something in it is unlocked or open. Readable from across the+ // room without reading a single label, which is the whole point.+ const edgeMat = new MeshBasicMaterial({ color: SECURE, transparent: true, opacity: 0 });+ const edge = new Mesh(geo.slab, edgeMat);+ edge.scale.set(room.w + 0.1, 0.05, room.d + 0.1);+ edge.position.y = 0.02;+ group.add(edge);++ const light = new PointLight(0xffffff, 0, room.w * 2.6, 1.7);+ light.position.set(0, room.h * 0.72, 0);+ const usesLight = rooms.size < MAX_ROOM_LIGHTS;+ if (usesLight) group.add(light);++ const label = makeLabel();+ label.position.set(0, room.h + 0.5, 0);+ group.add(label);++ const record = {+ id: room.id,+ source: room,+ group,+ floorMat,+ wallMat,+ edgeMat,+ light: usesLight ? light : null,+ label,+ labelText: '',+ color: new Color(room.light.hex),+ targetColor: new Color(room.light.hex),+ intensity: 0,+ targetIntensity: room.light.intensity,+ secure: 0,+ targetSecure: 0,+ highlight: 0,+ };+ record.labelText = labelFor(room);+ paintLabel(record);++ for (const object of room.objects) objects.set(object.entityId, buildObject(object, group, room));+ return record;+ }++ function buildObject(object, group, room) {+ const node = new Group();+ node.position.set(object.x, object.y, object.z);+ node.rotation.y = object.rotation;+ group.add(node);++ const material = new MeshStandardMaterial({+ color: 0x6f7690,+ roughness: 0.55,+ metalness: 0.15,+ emissive: new Color(0x000000),+ transparent: true,+ opacity: 1,+ });+ const record = {+ entityId: object.entityId,+ roomId: room.id,+ source: object,+ node,+ material,+ parts: [],+ activity: 0,+ targetActivity: object.activity,+ availability: 1,+ targetAvailable: object.available ? 1 : 0,+ select: 0,+ };++ switch (object.kind) {+ case 'lamp': {+ const bulb = new Mesh(geo.bulb, material);+ bulb.userData.entityId = object.entityId;+ node.add(bulb);+ const stem = new Mesh(geo.post, new MeshStandardMaterial({ color: 0x3a3f52, roughness: 0.8 }));+ stem.scale.y = 0.42;+ stem.position.y = 0.33;+ node.add(stem);+ record.parts.push(stem.material);+ const halo = new Sprite(new SpriteMaterial({ color: 0xffffff, transparent: true, opacity: 0, depthWrite: false }));+ halo.scale.set(2.1, 2.1, 1);+ node.add(halo);+ record.halo = halo;+ break;+ }+ case 'fan': {+ const hub = new Mesh(geo.puck, material);+ hub.scale.set(0.6, 0.6, 0.6);+ hub.userData.entityId = object.entityId;+ node.add(hub);+ const rotor = new Group();+ for (let i = 0; i < 3; i += 1) {+ const blade = new Mesh(geo.blade, material);+ blade.rotation.y = (i * Math.PI * 2) / 3;+ blade.position.y = -0.04;+ rotor.add(blade);+ }+ node.add(rotor);+ record.rotor = rotor;+ break;+ }+ case 'lock': {+ const body = new Mesh(geo.panel, material);+ body.scale.set(0.2, 0.3, 0.1);+ body.userData.entityId = object.entityId;+ node.add(body);+ const shackle = new Mesh(geo.ring, material);+ shackle.scale.set(0.62, 0.9, 0.62);+ shackle.position.y = 0.2;+ node.add(shackle);+ record.shackle = shackle;+ break;+ }+ case 'door':+ case 'window': {+ const frame = new Mesh(geo.panel, new MeshStandardMaterial({ color: 0x394059, roughness: 0.8, transparent: true, opacity: 0.6 }));+ const wide = object.kind === 'door' ? 1.05 : 0.92;+ frame.scale.set(wide, object.kind === 'door' ? 1.9 : 1.1, 0.06);+ frame.position.y = object.kind === 'door' ? 0.35 : 0.1;+ node.add(frame);+ record.parts.push(frame.material);+ const leaf = new Mesh(geo.panel, material);+ leaf.scale.set(wide * 0.94, (object.kind === 'door' ? 1.9 : 1.1) * 0.94, 0.04);+ leaf.position.set(0, frame.position.y, 0.03);+ leaf.userData.entityId = object.entityId;+ node.add(leaf);+ record.leaf = leaf;+ record.leafSpan = wide * 0.94;+ record.leafHeight = (object.kind === 'door' ? 1.9 : 1.1) * 0.94;+ record.leafY = frame.position.y;+ break;+ }+ case 'thermostat': {+ const post = new Mesh(geo.post, new MeshStandardMaterial({ color: 0x3a3f52, roughness: 0.8 }));+ post.scale.y = 0.72;+ post.position.y = 0.31;+ node.add(post);+ record.parts.push(post.material);+ const dial = new Mesh(geo.ring, material);+ dial.rotation.x = Math.PI / 2;+ dial.position.y = 0.68;+ dial.scale.set(1.1, 1, 1.1);+ dial.userData.entityId = object.entityId;+ node.add(dial);+ break;+ }+ case 'screen': {+ const panel = new Mesh(geo.panel, material);+ panel.scale.set(0.92, 0.52, 0.05);+ panel.userData.entityId = object.entityId;+ node.add(panel);+ break;+ }+ case 'camera': {+ const lens = new Mesh(geo.cone, material);+ lens.rotation.x = Math.PI / 2;+ lens.userData.entityId = object.entityId;+ node.add(lens);+ break;+ }+ case 'alarm': {+ const box = new Mesh(geo.panel, material);+ box.scale.set(0.3, 0.42, 0.08);+ box.userData.entityId = object.entityId;+ node.add(box);+ break;+ }+ case 'puck': {+ const disc = new Mesh(geo.puck, material);+ disc.scale.set(1.5, 1, 1.5);+ disc.position.y = 0.05;+ disc.userData.entityId = object.entityId;+ node.add(disc);+ break;+ }+ default: {+ const plate = new Mesh(geo.panel, material);+ plate.scale.set(0.22, 0.22, 0.05);+ plate.userData.entityId = object.entityId;+ node.add(plate);+ }+ }++ // A device Home Assistant cannot reach is drawn, never omitted: a thing+ // that vanished from a house is information, and hiding it is how a scene+ // tells a comfortable lie.+ const missing = new Sprite(new SpriteMaterial({ color: 0xe05a4a, transparent: true, opacity: 0, depthWrite: false, depthTest: false }));+ missing.scale.set(0.34, 0.34, 1);+ missing.position.y = 0.42;+ node.add(missing);+ record.missing = missing;++ commitObject(record);+ return record;+ }++ // ── per-frame values ──────────────────────────────────────────────────────++ function commitRoom(record) {+ const room = record.source;+ const dim = 1 - staleAmount * 0.72;+ spare.color.copy(record.color);+ if (staleAmount > 0) spare.color.lerp(GREY, staleAmount * 0.85);++ if (record.light) {+ record.light.color.copy(spare.color);+ record.light.intensity = record.intensity * 3.4 * dim;+ }+ record.floorMat.emissive.copy(spare.color).multiplyScalar(record.intensity * 0.42 * dim);+ record.floorMat.color.setHex(SURFACE).lerp(spare.color, Math.min(0.22, record.intensity * 0.2));+ record.wallMat.opacity = 0.24 + record.intensity * 0.12 + record.highlight * 0.24;++ const alarmed = record.secure;+ record.edgeMat.color.setHex(alarmed > 0.5 ? OPEN : SECURE);+ record.edgeMat.opacity = (room.security ? 0.18 + alarmed * 0.5 : 0) + record.highlight * 0.4;+ record.label.material.opacity = 0.92 * (1 - staleAmount * 0.4);+ }++ function commitObject(record) {+ const object = record.source;+ const room = rooms.get(record.roomId);+ const on = record.activity;+ const available = record.availability;+ const dim = 1 - staleAmount * 0.7;++ spare.target.setHex(0x6f7690);+ let emissiveStrength = 0;++ switch (object.kind) {+ case 'lamp': {+ const roomColor = room ? room.color : spare.color.setHex(0xffe0b0);+ spare.target.copy(roomColor);+ emissiveStrength = on * 1.5;+ if (record.halo) record.halo.material.opacity = on * 0.4 * dim * available;+ if (record.halo) record.halo.material.color.copy(roomColor);+ break;+ }+ case 'lock': {+ spare.target.setHex(on > 0.5 ? ALERT : SECURE);+ emissiveStrength = on > 0.5 ? 0.85 : 0.22;+ if (record.shackle) record.shackle.position.y = 0.2 + on * 0.12;+ break;+ }+ case 'door':+ case 'window': {+ spare.target.setHex(on > 0.02 ? OPEN : 0x5a6178);+ emissiveStrength = on * 0.5;+ if (record.leaf) {+ // Openness is a real position: a cover at 40% is 40% open, not a+ // colour change standing in for one.+ record.leaf.scale.x = Math.max(0.02, record.leafSpan * (1 - on * 0.94));+ record.leaf.position.x = -(record.leafSpan * on * 0.47);+ }+ break;+ }+ case 'thermostat': {+ const tint = room?.source?.climate?.tint ?? 0;+ spare.target.setHex(0x4f88d8).lerp(WARM, Math.max(0, tint)).lerp(COOL, Math.max(0, -tint));+ emissiveStrength = on * 0.7;+ break;+ }+ case 'screen':+ spare.target.setHex(0x8fa6ff);+ emissiveStrength = on * 1.15;+ break;+ case 'alarm':+ spare.target.setHex(on > 0.5 ? ALERT : 0x5a6178);+ emissiveStrength = on * 0.9;+ break;+ case 'camera':+ spare.target.setHex(0x7c5cff);+ emissiveStrength = 0.3;+ break;+ case 'fan':+ spare.target.setHex(on > 0.5 ? 0x8fa6ff : 0x6f7690);+ emissiveStrength = on * 0.4;+ break;+ default:+ spare.target.setHex(on > 0.5 ? 0x8fa6ff : 0x6f7690);+ emissiveStrength = on * 0.6;+ }++ if (staleAmount > 0) spare.target.lerp(GREY, staleAmount * 0.85);+ record.material.color.copy(spare.target);+ record.material.emissive.copy(spare.target).multiplyScalar(emissiveStrength * dim * available);+ // Unreachable reads as a ghost of itself plus a live marker, so "the lamp+ // is off" and "the lamp is gone" can never look the same.+ record.material.opacity = 0.24 + available * 0.76;+ for (const part of record.parts) part.opacity = 0.3 + available * 0.7;+ if (record.missing) record.missing.material.opacity = (1 - available) * 0.9;+ record.node.scale.setScalar(1 + record.select * 0.18);+ }++ // ── loop ──────────────────────────────────────────────────────────────────++ function damp(current, target, dt) {+ // Framerate-independent exponential approach: the same visual speed at+ // 30 fps and at 144.+ return current + (target - current) * (1 - Math.exp(-dt / EASE));+ }++ let last = 0;+ let raf = 0;+ let staleMoving = false;+ function tick(now) {+ if (disposed) return;+ raf = requestAnimationFrame(tick);+ // A wall display is the real deployment: an unfocused tab and a+ // power-saver phone both step down to 30, and the governor keeps the+ // average honest on a 120Hz panel instead of quantizing it to 40.+ const cap = powerSaver ? FPS_SAVER : focus.focused ? FPS_ACTIVE : FPS_IDLE;+ if (!governor.shouldRun(now, cap)) return;+ const dt = last ? Math.min(0.1, (now - last) / 1000) : 0.016;+ last = now;++ const staleTarget = stale ? 1 : 0;+ staleMoving = Math.abs(staleAmount - staleTarget) > 0.002;+ staleAmount = damp(staleAmount, staleTarget, dt);+ if (acting && now > actingUntil) acting = null;++ for (const record of rooms.values()) {+ const wasHighlight = record.highlight;+ record.highlight = damp(record.highlight, acting?.roomId === record.id ? 1 : 0, dt);+ const before = record.intensity;+ record.intensity = damp(record.intensity, record.targetIntensity, dt);+ record.secure = damp(record.secure, record.targetSecure, dt);+ const moved = Math.abs(before - record.intensity) > 0.0005 || Math.abs(wasHighlight - record.highlight) > 0.001;+ if (moved || !record.color.equals(record.targetColor) || staleMoving) {+ record.color.lerp(record.targetColor, 1 - Math.exp(-dt / EASE));+ commitRoom(record);+ }+ }++ for (const record of objects.values()) {+ const before = record.activity;+ record.activity = damp(record.activity, record.targetActivity, dt);+ record.availability = damp(record.availability, record.targetAvailable, dt);+ const wanted = selected === record.entityId ? 1 : 0;+ const beforeSelect = record.select;+ record.select = damp(record.select, wanted, dt);+ if (record.rotor && record.activity > 0.02) record.rotor.rotation.y += dt * (2 + record.activity * 16);+ if (+ Math.abs(before - record.activity) > 0.0008 ||+ Math.abs(beforeSelect - record.select) > 0.002 ||+ Math.abs(record.availability - record.targetAvailable) > 0.002 ||+ staleMoving+ ) {+ commitObject(record);+ }+ }++ if (agent) agent.update(dt, now);+ controls.update();+ renderer.render(scene, camera);++ frames += 1;+ if (!fpsWindowStart) fpsWindowStart = now;+ if (now - fpsWindowStart >= 1000) {+ fps = Math.round((frames * 1000) / (now - fpsWindowStart));+ frames = 0;+ fpsWindowStart = now;+ }+ if (!firstFrameSent) {+ firstFrameSent = true;+ options.onFirstFrame?.();+ }+ }++ // ── camera, agent, labels, picking ────────────────────────────────────────++ function frameCamera(m) {+ const b = m.bounds;+ const cx = (b.minX + b.maxX) / 2;+ const cz = (b.minZ + b.maxZ) / 2;+ const span = Math.max(b.width, b.depth, 8);+ controls.target.set(cx, Math.min(b.maxY * 0.35, 3), cz);+ camera.position.set(cx + span * 0.62, span * 0.66 + 4, cz + span * 0.86);+ camera.updateProjectionMatrix();+ controls.update();+ }++ function focusRoom(roomId) {+ const record = rooms.get(roomId);+ if (!record || !model) return;+ const room = record.source;+ controls.target.set(room.x, room.y + 1.1, room.z);+ const distance = Math.max(room.w, room.d) * 1.9;+ camera.position.set(room.x + distance * 0.55, room.y + distance * 0.72, room.z + distance);+ controls.update();+ options.onFocusRoom?.(roomId);+ }++ function makeLabel() {+ const canvas = document.createElement('canvas');+ canvas.width = 512;+ canvas.height = 128;+ const texture = new CanvasTexture(canvas);+ texture.minFilter = LinearFilter;+ const sprite = new Sprite(new SpriteMaterial({ map: texture, transparent: true, depthWrite: false, depthTest: false }));+ sprite.scale.set(4.4, 1.1, 1);+ sprite.userData.canvas = canvas;+ sprite.userData.texture = texture;+ return sprite;+ }++ function labelFor(room) {+ const bits = [room.name];+ if (room.climate) bits.push(room.climate.label);+ if (room.light.total) bits.push(`${room.light.count}/${room.light.total} lit`);+ return bits.join(' ');+ }++ function paintLabel(record) {+ const canvas = record.label.userData.canvas;+ const ctx = canvas.getContext('2d');+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ ctx.font = '600 46px "Inter", system-ui, sans-serif';+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.fillStyle = 'rgba(8, 9, 14, 0.72)';+ const width = Math.min(canvas.width - 8, ctx.measureText(record.labelText).width + 56);+ roundRect(ctx, (canvas.width - width) / 2, 26, width, 76, 22);+ ctx.fill();+ ctx.fillStyle = '#eef1ff';+ ctx.fillText(record.labelText, canvas.width / 2, 64);+ record.label.userData.texture.needsUpdate = true;+ }++ function roundRect(ctx, x, y, w, h, r) {+ ctx.beginPath();+ ctx.moveTo(x + r, y);+ ctx.arcTo(x + w, y, x + w, y + h, r);+ ctx.arcTo(x + w, y + h, x, y + h, r);+ ctx.arcTo(x, y + h, x, y, r);+ ctx.arcTo(x, y, x + w, y, r);+ ctx.closePath();+ }++ function placeAgent(stand) {+ if (!stand) return;+ if (!agent) {+ agent = createAgentBody(scene, renderer);+ }+ agent.moveTo(stand.x, stand.y, stand.z, stand.facing);+ }++ function onPointerDown(event) {+ const rect = renderer.domElement.getBoundingClientRect();+ pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;+ pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;+ raycaster.setFromCamera(pointer, camera);+ const hits = raycaster.intersectObjects(world.children, true);+ for (const hit of hits) {+ const entityId = hit.object.userData.entityId;+ if (entityId) {+ selected = entityId;+ options.onSelect?.(entityId, objects.get(entityId)?.source || null);+ return;+ }+ const roomId = hit.object.userData.roomId;+ if (roomId) {+ selected = null;+ options.onSelect?.(null, null);+ options.onFocusRoom?.(roomId);+ return;+ }+ }+ selected = null;+ options.onSelect?.(null, null);+ }+ renderer.domElement.addEventListener('pointerdown', onPointerDown);++ function resize() {+ const w = container.clientWidth || 1;+ const h = container.clientHeight || 1;+ renderer.setSize(w, h, false);+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ }+ const observer = new ResizeObserver(resize);+ observer.observe(container);+ resize();+ raf = requestAnimationFrame(tick);++ function clearWorld() {+ for (const record of objects.values()) {+ record.material.dispose();+ for (const part of record.parts) part.dispose();+ record.halo?.material.dispose();+ record.missing?.material.dispose();+ }+ objects.clear();+ for (const record of rooms.values()) {+ record.floorMat.dispose();+ record.wallMat.dispose();+ record.edgeMat.dispose();+ record.label.material.map?.dispose();+ record.label.material.dispose();+ }+ rooms.clear();+ world.clear();+ }++ return {+ setModel,+ focusRoom,+ select(entityId) {+ selected = entityId;+ },+ setStale(next) {+ stale = Boolean(next);+ },+ /** Highlight the room an action is happening in, for a short beat. */+ setActing(next, holdMs = 2600) {+ acting = next;+ actingUntil = performance.now() + holdMs;+ if (next?.roomId) agent?.moveToRoom(rooms.get(next.roomId)?.source);+ agent?.act();+ },+ stats() {+ return {+ fps,+ objects: objects.size,+ rooms: rooms.size,+ drawCalls: renderer.info.render.calls,+ geometries: renderer.info.memory.geometries,+ textures: renderer.info.memory.textures,+ };+ },+ dispose() {+ if (disposed) return;+ disposed = true;+ cancelAnimationFrame(raf);+ stopPowerSaver();+ observer.disconnect();+ renderer.domElement.removeEventListener('pointerdown', onPointerDown);+ clearWorld();+ agent?.dispose();+ for (const value of Object.values(geo)) value.dispose();+ controls.dispose();+ renderer.dispose();+ renderer.domElement.remove();+ },+ };+}++/**+ * The agent's body, standing in the house.+ *+ * The platform's default rigged body driven by the canonical clip library, the+ * same pair `/walk`, `/play` and Docs World use, so a rig that animates+ * anywhere on three.ws animates here. A rig that cannot be skeleton-driven, or+ * a load that fails outright, falls back to a lit capsule: the house stays+ * fully usable, it just loses the face.+ */+function createAgentBody(scene, renderer) {+ const root = new Group();+ scene.add(root);+ let anim = null;+ let disposed = false;+ const target = new Vector3();+ let bob = 0;+ let gesture = 0;+ let placeholder = null;++ const glow = new PointLight(0x8fa6ff, 1.4, 6, 2);+ glow.position.y = 1.2;+ root.add(glow);++ placeholder = new Mesh(+ new CylinderGeometry(0.26, 0.3, 1.5, 12),+ new MeshStandardMaterial({ color: 0x2a2444, roughness: 0.5, metalness: 0.3, emissive: 0x7c5cff, emissiveIntensity: 0.45 }),+ );+ placeholder.position.y = 0.75;+ root.add(placeholder);++ (async () => {+ try {+ const [{ gltfLoader }, { AnimationManager }] = await Promise.all([+ import('../loaders/gltf.js'),+ import('../animation-manager.js'),+ ]);+ const gltf = await new Promise((resolve, reject) => gltfLoader(renderer).load('/avatars/default.glb', resolve, undefined, reject));+ if (disposed) return;+ const model = gltf.scene;+ model.traverse((node) => {+ if (node.isMesh) node.frustumCulled = false;+ });+ root.add(model);+ placeholder.visible = false;+ anim = new AnimationManager();+ anim.attach(model, { avatarUrl: '/avatars/default.glb' });+ anim.relaxUndrivenArms?.();+ const defs = await fetch('/animations/manifest.json').then((r) => (r.ok ? r.json() : []));+ if (Array.isArray(defs) && defs.length && anim.supportsCanonicalClips?.() !== false) {+ anim.setAnimationDefs(defs);+ if (await anim.ensureLoaded('idle')) await anim.crossfadeTo('idle', 0);+ }+ } catch {+ // The capsule is already standing; the house does not need the body.+ }+ })();++ return {+ moveTo(x, y, z, facing) {+ target.set(x, y, z);+ root.position.copy(target);+ root.rotation.y = facing;+ },+ moveToRoom(room) {+ if (!room) return;+ this.moveTo(room.x - room.w * 0.22, room.y, room.z + room.d * 0.2, 0);+ },+ /** A short lift as the agent performs an action, so it is clearly the actor. */+ act() {+ gesture = 1;+ },+ update(dt) {+ bob += dt;+ gesture = Math.max(0, gesture - dt * 0.8);+ root.position.y = target.y + Math.sin(bob * 1.6) * 0.012 + gesture * 0.14;+ glow.intensity = 1.1 + Math.sin(bob * 2.2) * 0.2 + gesture * 1.6;+ anim?.update?.(dt);+ },+ dispose() {+ disposed = true;+ anim?.dispose?.();+ scene.remove(root);+ placeholder?.geometry.dispose();+ placeholder?.material.dispose();+ },+ };+}diff --git a/src/voice/wake-word.js b/src/voice/wake-word.jsindex 857026cae..0ed867fcc 100644--- a/src/voice/wake-word.js+++ b/src/voice/wake-word.js@@ -186,6 +186,7 @@ export class WakeWordDetector {this._featureRing = new RowRing(PREDICTION_EMBEDDINGS, EMBEDDING_DIMS);this._inflight = false;+ this._needsPrime = false;this._lastWakeAt = 0;this._above = false;/**@@ -230,6 +231,35 @@ export class WakeWordDetector {this._mel = mel;this._embed = embed;this._model = model;+ await this._prime();+ this._needsPrime = false;+ }++ /**+ * Run the chain over two seconds of digital silence so the ring buffers are+ * full before the first real frame arrives.+ *+ * Without this the detector is deaf for its first 2.04 s (76 mel frames plus+ * 16 embeddings), and a user who says the wake word the instant the indicator+ * lights up is simply not heard. openWakeWord primes upstream for the same+ * reason, with random noise; silence is the better choice here because it is+ * deterministic and cannot itself score. Measured: 26 chunks, 119 ms of work,+ * peak score 0.0000, and detection afterwards is bit-identical to a detector+ * that warmed up on live audio.+ */+ async _prime() {+ const silence = new Float32Array(CHUNK_SAMPLES);+ const chunks = Math.ceil((EMBEDDING_WINDOW_FRAMES * MEL_HOP_SAMPLES + PREDICTION_EMBEDDINGS * CHUNK_SAMPLES) / CHUNK_SAMPLES);+ for (let i = 0; i < chunks; i++) {+ this._appendRaw(silence);+ if (this._rawFilled < this._raw.length) continue;+ const melFrames = await this._melspectrogram(this._raw);+ for (let j = 0; j < melFrames.length; j += MEL_BINS) {+ this._melRing.push(melFrames.subarray(j, j + MEL_BINS));+ }+ if (!this._melRing.full) continue;+ this._featureRing.push(await this._embedding(this._melRing.snapshot()));+ }}/**@@ -287,6 +317,11 @@ export class WakeWordDetector {this._above = false;this.lastScore = 0;this.suppressedPeak = 0;+ // Re-prime rather than leave the detector deaf for two seconds after every+ // wake, mute or barge-in. Silence is what the buffers held anyway. The+ // work happens on the next chunk, inside the single-flight guard, so it+ // can never interleave with an inference already in progress.+ this._needsPrime = true;}/** Release the sessions. Idempotent. */@@ -309,6 +344,10 @@ export class WakeWordDetector {this._inflight = true;const chunkAt = this._lastFrameAt;try {+ if (this._needsPrime) {+ this._needsPrime = false;+ await this._prime();+ }this._appendRaw(chunk);if (this._rawFilled < this._raw.length) return;