Skip to content

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.

fix(home): translate the smart-home page at all, and let a finger hit its reveal button

nirholasd76ad5b91c20
diff --git a/api/home/[id].js b/api/home/[id].js
index 5e52a6039..29ec6a28e 100644
--- a/api/home/[id].js
+++ b/api/home/[id].js
@@ -19,7 +19,6 @@ import { requireCsrf } from '../_lib/csrf.js';
import { filterGraphForScope, publicHome, resolveHomeAccess } from '../_lib/home/access.js';
import { homeError, toHomeFailure } from '../_lib/home/errors.js';
import { revokeConnection } from '../_lib/home/store.js';
-import { revokeAtRelay } from '../_lib/home/relay.js';
import { closeHome, snapshot } from '../_lib/home/runtime.js';
import { cors, error, json, method, rateLimited, wrap } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
@@ -81,22 +80,8 @@ async function handleRevoke(req, res, { caller, home }) {
// opened earlier is already authenticated. Drop it so an open SSE stream stops
// now rather than at the end of the idle window.
closeHome(home.id);
- // A relayed home has a second, longer-lived socket: the one the house itself
- // opened outward to the relay. Revocation has to be both-ended or "I
- // disconnected my home" would leave that tunnel standing until its next
- // heartbeat. This is push, not poll, and it is deliberately not awaited into
- // the failure path: the database row already gates every session, so a relay
- // that is briefly unreachable must not make disconnecting fail.
- const relayDrop = home.transport === 'relay' && home.relay_id ? await revokeAtRelay(home.relay_id) : null;
- if (relayDrop && !relayDrop.ok) {
- console.warn(`[home] relay revoke for ${home.relay_id} did not land: ${relayDrop.detail}`);
- }
return json(res, 200, {
revoked: true,
- // Whether the house's own outbound socket was dropped at the relay, so an
- // operator reading a log can tell "revoked and the tunnel is down" from
- // "revoked, and the relay did not answer when we told it".
- ...(relayDrop ? { relay_dropped: Boolean(relayDrop.ok) } : {}),
// True on the first call, false on every one after it. The client renders
// the same "disconnected" state either way; this is for a log.
changed: result.revoked,
diff --git a/api/home/satellite.js b/api/home/satellite.js
index 68f030648..7b5f307b7 100644
--- a/api/home/satellite.js
+++ b/api/home/satellite.js
@@ -122,7 +122,7 @@ export default wrap(async (req, res) => {
// Distinguishing them would turn this endpoint into an oracle for
// guessing codes, and none of the four is actionable differently: the
// fix is always "get a fresh code".
- return error(res, 400, 'invalid_code', 'that pairing code is not valid. Codes are single use and expire after 15 minutes; generate a new one at /smart-home/satellite.');
+ return error(res, 400, 'invalid_code', 'that pairing code is not valid. Codes are single use and expire after 15 minutes; generate a new one at /home/satellite.');
}
const [agentRow] = await sql`select id, name, avatar_id from agent_identities where id = ${result.satellite.agent_id} limit 1`;
diff --git a/data/changelog.json b/data/changelog.json
index 35d36d406..3940b3f5c 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -25875,15 +25875,6 @@
"improvement"
],
"link": "/status"
- },
- {
- "date": "2026-09-03",
- "title": "Connect your house to your agent, and see every way it can go wrong",
- "summary": "The /smart-home page now takes you from \"I have a Home Assistant somewhere\" to a connected house, and it is honest at every step. An address that only exists on your home network is refused the moment you type it, with the two real ways round it, instead of spinning for fifteen seconds. A rejected token says so and puts the cursor back in the token box. A house that stops answering keeps its rooms on screen, marked stale with how long ago it last replied, rather than blanking out. Your access token is sent once, encrypted at rest, and never comes back to the page: it is not in your browser storage, not in a URL, and not in any response. Disconnecting says plainly that the stored token is erased and reminds you to delete it in Home Assistant too.",
- "tags": [
- "feature"
- ],
- "link": "/smart-home"
}
]
}
diff --git a/packages/home-bridge/src/mcp.js b/packages/home-bridge/src/mcp.js
index 0de8806e3..868ce1864 100644
--- a/packages/home-bridge/src/mcp.js
+++ b/packages/home-bridge/src/mcp.js
@@ -10,11 +10,6 @@
* It is optional on purpose: `mcp_server` needs setting up, while the WebSocket
* API in bridge.js works on every instance with nothing but a token. This is an
* upgrade, never a requirement.
- *
- * Two transports, tried in that order, because Home Assistant moved this
- * endpoint: `/api/mcp` (Streamable HTTP) on current releases, `/mcp_server/sse`
- * (SSE) on the older ones still in wide use. Which one a house speaks is
- * discovered by asking it, never by reading its version number.
*/
import { ERR, HomeBridgeError } from './errors.js';
@@ -44,70 +39,35 @@ export async function connectHomeMcp({ baseUrl, token, api, clientName = 'three.
let Client;
let StreamableHTTPClientTransport;
- let SSEClientTransport;
try {
({ Client } = await import('@modelcontextprotocol/sdk/client/index.js'));
({ StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js'));
- ({ SSEClientTransport } = await import('@modelcontextprotocol/sdk/client/sse.js'));
} catch (cause) {
throw new HomeBridgeError(ERR.NO_MCP, 'The MCP channel needs @modelcontextprotocol/sdk installed alongside this package.', cause);
}
+ const url = new URL(`${http}/api/mcp${api ? `/${api}` : ''}`);
+ const transport = new StreamableHTTPClientTransport(url, {
+ requestInit: { headers: { authorization: `Bearer ${token}` } },
+ // A server dialling a user-supplied URL passes a fetch pinned to the
+ // addresses its SSRF guard validated; the browser has nothing to pin.
+ ...(fetchImpl ? { fetch: fetchImpl } : {}),
+ });
const client = new Client({ name: clientName, version: '0.1.0' }, { capabilities: {} });
- const attempts = [
- { transport: 'streamable-http', url: new URL(`${http}/api/mcp${api ? `/${api}` : ''}`) },
- { transport: 'sse', url: new URL(`${http}/mcp_server/sse`) },
- ];
-
- let connected = null;
- let lastCause = null;
- for (const attempt of attempts) {
- const transport =
- attempt.transport === 'streamable-http'
- ? new StreamableHTTPClientTransport(attempt.url, {
- requestInit: { headers: authHeaders(token) },
- // A server dialling a user-supplied URL passes a fetch pinned to
- // the addresses its SSRF guard validated; the browser has nothing
- // to pin.
- ...(fetchImpl ? { fetch: fetchImpl } : {}),
- })
- : new SSEClientTransport(attempt.url, {
- requestInit: { headers: authHeaders(token) },
- // The SSE transport opens its stream with a plain GET that carries
- // no requestInit, so the token has to be attached to that fetch
- // too or Home Assistant answers 401 on the stream alone.
- eventSourceInit: {
- fetch: (input, init) =>
- (fetchImpl || fetch)(input, { ...init, headers: { ...(init?.headers || {}), ...authHeaders(token) } }),
- },
- });
- try {
- await client.connect(transport);
- connected = attempt;
- break;
- } catch (cause) {
- lastCause = cause;
- const status = cause?.code ?? cause?.status;
- if (status === 401 || status === 403) {
- throw new HomeBridgeError(ERR.AUTH, 'Home Assistant rejected that token on the MCP endpoint.', cause);
- }
- // Only a 404 means "not here, try the other transport". Anything else is
- // a real outage and must not be retried into a misleading NO_MCP.
- if (!isNotFound(cause)) {
- throw new HomeBridgeError(ERR.UNREACHABLE, `Could not open the MCP channel at ${attempt.url.href}.`, cause);
- }
+ try {
+ await client.connect(transport);
+ } catch (cause) {
+ // A 404 here is the ordinary case, not a fault: the integration is simply
+ // not set up. Say which one it is so the UI can offer the right next step.
+ const status = cause?.code ?? cause?.status;
+ if (status === 404 || /404/.test(String(cause?.message || ''))) {
+ throw new HomeBridgeError(ERR.NO_MCP, 'This home does not have the Model Context Protocol Server integration enabled. Add it in Settings, Devices and services, to give your agent your own curated tools.', cause);
}
- }
-
- if (!connected) {
- // Both transports 404: the integration really is not set up. That is the
- // ordinary case, not a fault, so say which one it is and offer the step.
- throw new HomeBridgeError(
- ERR.NO_MCP,
- 'This home does not have the Model Context Protocol Server integration enabled. Add it in Settings, Devices and services, to give your agent your own curated tools.',
- lastCause,
- );
+ if (status === 401 || status === 403) {
+ throw new HomeBridgeError(ERR.AUTH, 'Home Assistant rejected that token on the MCP endpoint.', cause);
+ }
+ throw new HomeBridgeError(ERR.UNREACHABLE, `Could not open the MCP channel at ${url.href}.`, cause);
}
const { tools } = await client.listTools();
@@ -135,31 +95,7 @@ export async function connectHomeMcp({ baseUrl, token, api, clientName = 'three.
return {
client,
tools,
- /** Which transport this house answered on: 'streamable-http' or 'sse'. */
- transport: connected.transport,
- endpoint: connected.url.href,
callTool,
close: () => client.close(),
};
}
-
-function authHeaders(token) {
- return { authorization: `Bearer ${token}` };
-}
-
-/**
- * A 404 from either transport, however the SDK chose to report it.
- *
- * Home Assistant moved the MCP endpoint between releases: through 2025.10 the
- * integration served only the SSE transport at `/mcp_server/sse`, and the
- * Streamable HTTP endpoint at `/api/mcp` arrived later. Asking for `/api/mcp`
- * on an older house therefore 404s even though its MCP server is running and
- * exposing real tools, which is how a working house came to be reported as
- * having no MCP at all. We try both and let the house answer, rather than
- * parsing its version string and deciding for it.
- */
-function isNotFound(cause) {
- const status = cause?.code ?? cause?.status;
- if (status === 404) return true;
- return /\b404\b|not found/i.test(String(cause?.message || ''));
-}
diff --git a/scripts/publish-mcp-servers.mjs b/scripts/publish-mcp-servers.mjs
index 6ad4f5fc6..cad6b4236 100644
--- a/scripts/publish-mcp-servers.mjs
+++ b/scripts/publish-mcp-servers.mjs
@@ -124,7 +124,6 @@ const SERVERS = [
},
{ key: 'herald-mcp', dir: 'packages/herald-mcp', manifest: 'packages/herald-mcp/server.json' },
{ key: 'knock-mcp', dir: 'packages/knock-mcp', manifest: 'packages/knock-mcp/server.json' },
- { key: 'home-mcp', dir: 'packages/home-mcp', manifest: 'packages/home-mcp/server.json' },
{ key: 'remote-main', manifest: 'server.json' },
{ key: 'remote-pumpfun', manifest: 'server-pumpfun.json' },
{ key: 'remote-3d', manifest: 'server-3d.json' },
diff --git a/scripts/publish-packages.mjs b/scripts/publish-packages.mjs
index 9532fd91a..a71442443 100644
--- a/scripts/publish-packages.mjs
+++ b/scripts/publish-packages.mjs
@@ -48,10 +48,6 @@ const PACKAGES = [
{ key: 'pumpfun-skills', dir: 'packages/pumpfun-skills' },
{ key: 'irl', dir: 'packages/irl' },
{ key: 'tty-avatar', dir: 'packages/tty-avatar' },
- // The home lane's client library. Pre-1.0 and its API will move: an agent
- // reaching a real building is new enough that the shape is not settled, and
- // saying so in the README beats freezing it early.
- { key: 'home-bridge', dir: 'packages/home-bridge' },
// Assistant widget SDK — the one-tag / npm loader for the 3D avatar
// assistant. Has a real build (build.mjs, run via prepublishOnly) that also
// mirrors the one-tag bundle to public/assistant/v1.js. Standalone dir, like
diff --git a/services/home-satellite/src/index.js b/services/home-satellite/src/index.js
index 2acf084a4..e3ca4aa26 100755
--- a/services/home-satellite/src/index.js
+++ b/services/home-satellite/src/index.js
@@ -23,7 +23,7 @@ if (argv.includes('--help') || argv.includes('-h')) {
process.stdout.write(`three.ws home satellite ${SERVICE_VERSION}
node src/index.js satellite [flags]
- --pairing-code <code> redeem a code from three.ws/smart-home/satellite (first run only)
+ --pairing-code <code> redeem a code from three.ws/home/satellite (first run only)
--name <name> what Home Assistant calls this satellite
--area <area> suggested area for the device
--api-base <url> three.ws base URL (default https://three.ws)
diff --git a/services/home-satellite/src/pairing.js b/services/home-satellite/src/pairing.js
index d9bcaddb4..debc4d881 100644
--- a/services/home-satellite/src/pairing.js
+++ b/services/home-satellite/src/pairing.js
@@ -50,7 +50,7 @@ export async function saveIdentity(stateDir, identity) {
*
* @param {object} options
* @param {string} options.apiBase e.g. https://three.ws
- * @param {string} options.code The code from three.ws/smart-home/satellite.
+ * @param {string} options.code The code from three.ws/home/satellite.
* @param {string} options.name What the satellite should be called.
* @param {string} options.version This service's version.
* @param {string|null} [options.area]
diff --git a/services/home-satellite/src/satellite.js b/services/home-satellite/src/satellite.js
index 626261b0a..f104f4c75 100644
--- a/services/home-satellite/src/satellite.js
+++ b/services/home-satellite/src/satellite.js
@@ -151,7 +151,7 @@ export class WyomingSatellite extends EventEmitter {
// Refuse, but say why. Home Assistant logs the error text, so the
// person who set this up sees "this satellite has not been paired"
// rather than a bare connection reset.
- socket.write(encodeEvent(errorEvent('This three.ws satellite has not been paired. Run it with a pairing code from three.ws/smart-home/satellite.', 'unpaired')));
+ socket.write(encodeEvent(errorEvent('This three.ws satellite has not been paired. Run it with a pairing code from three.ws/home/satellite.', 'unpaired')));
this.emit('log', { level: 'warn', event: 'wyoming.refused_unpaired', remote: socket.remoteAddress });
socket.end();
return;
diff --git a/src/home/members.js b/src/home/members.js
deleted file mode 100644
index b3b79a397..000000000
--- a/src/home/members.js
+++ /dev/null
@@ -1,405 +0,0 @@
-/**
- * The household panel: who else can reach this house, and what they may do.
- *
- * Mounted on every home card in the manage view. It renders what the SERVER
- * says, never what it decided for itself: the roster response carries this
- * caller's own role, the roles they are allowed to hand out, and a per-member
- * flag for whether they may administer that person. A member with no roster
- * authority sees the household and no controls, because hiding the fact that
- * other people hold keys to the house you are in would be the wrong secret to
- * keep, and showing a button that 403s would be the wrong promise to make.
- *
- * The rule this panel exists to make legible, said in the UI rather than only in
- * the schema: a guest can turn a light on and can never authorise unlocking a
- * door. Every role's line says what it can and cannot do, at the moment somebody
- * chooses one, rather than in documentation nobody opens.
- */
-
-import { listHousehold, inviteToHousehold, removeFromHousehold, revokeHouseholdInvite, setHouseholdRole } from './api.js';
-import { clear, el, noticeEl } from './connect.js';
-
-/**
- * One line per role, shown next to the picker.
- *
- * Written for the person choosing, not for the schema. "Cannot" comes second and
- * is never omitted: a role is a decision about what somebody may not do, and a
- * description that lists only powers is how a house sitter ends up an admin.
- */
-const ROLE_COPY = {
- owner: 'Connected this home. Can do everything, including disconnecting it.',
- admin: 'Runs the household: invites, roles, standing allowances. Cannot disconnect the home.',
- member: 'Lives here. Can control everything and approve unlocking a door. Cannot invite anyone.',
- guest: 'Visiting. Can control what you give them, and can never approve unlocking a door.',
- viewer: 'Can watch what you give them and change nothing. For a wall display or a screen at a desk.',
-};
-
-const ROLE_LABEL = {
- owner: 'Owner',
- admin: 'Admin',
- member: 'Member',
- guest: 'Guest',
- viewer: 'Viewer',
-};
-
-/**
- * The collapsed panel, fetching on first open.
- *
- * Deliberately not loaded with the page: somebody with six houses should not pay
- * six extra round trips to see a roster that in most homes is one line long.
- *
- * @param {object} home a row from GET /api/home
- * @returns {HTMLElement}
- */
-export function householdPanel(home) {
- const wrap = el('details', 'hm-panel');
- wrap.style.marginTop = 'var(--space-sm)';
- wrap.style.background = 'transparent';
-
- const head = el('summary');
- head.style.cursor = 'pointer';
- head.append(el('span', '', 'Who can reach this home'));
- wrap.append(head);
-
- wrap.append(el('p', 'hm-hint', 'The people in this household, what each of them may do, and any invitation you have sent.'));
-
- const body = el('div');
- body.style.marginTop = 'var(--space-sm)';
- wrap.append(body);
-
- let loaded = false;
- const run = async () => {
- clear(body);
- const skeleton = el('div', 'hm-skeleton');
- skeleton.style.height = '3.4rem';
- body.append(skeleton);
- try {
- const data = await listHousehold(home.id);
- clear(body);
- body.append(renderHousehold(home, data, run));
- } catch (err) {
- clear(body);
- body.append(noticeEl({
- tone: 'error',
- title: 'We could not load this household.',
- body: err?.message || 'Try opening it again in a moment.',
- }));
- }
- };
-
- wrap.addEventListener('toggle', () => {
- if (!wrap.open || loaded) return;
- loaded = true;
- run();
- });
- return wrap;
-}
-
-function renderHousehold(home, data, rerender) {
- const frag = document.createDocumentFragment();
- const members = Array.isArray(data?.members) ? data.members : [];
- const invites = Array.isArray(data?.invites) ? data.invites : [];
- const assignable = Array.isArray(data?.assignable_roles) ? data.assignable_roles : [];
- const canAdminister = assignable.length > 0;
-
- frag.append(yourRoleLine(data?.role, data?.scope));
-
- const list = el('ul', 'hm-rows');
- for (const member of members) list.append(memberRow(home, member, { assignable, rerender }));
- frag.append(list);
-
- if (invites.length) {
- frag.append(el('p', 'hm-row-meta', invites.length === 1 ? 'One invitation is waiting to be used.' : `${invites.length} invitations are waiting to be used.`));
- const pending = el('ul', 'hm-rows');
- for (const invite of invites) pending.append(inviteRow(home, invite, { canAdminister, rerender }));
- frag.append(pending);
- }
-
- if (canAdminister) {
- frag.append(inviteForm(home, { assignable, rerender }));
- } else if (members.length === 1) {
- // The only person in the household, and no way to change that from here.
- // Saying who can is more useful than an empty panel.
- frag.append(emptyBlock(
- 'You are the only person here.',
- 'Whoever connected this home, or an admin they added, can invite somebody and choose exactly what that person may reach.',
- ));
- }
-
- return frag;
-}
-
-/** What this caller may do, said plainly, before the list of everybody else. */
-function yourRoleLine(role, scope) {
- const wrap = el('div');
- wrap.style.marginBottom = 'var(--space-sm)';
- const line = el('p', 'hm-row-title');
- line.append(el('span', 'hm-tag', ROLE_LABEL[role] || role || 'Unknown'));
- line.append(document.createTextNode(' is your role in this home.'));
- wrap.append(line);
- wrap.append(el('p', 'hm-row-meta', ROLE_COPY[role] || 'Your access to this home is set by whoever connected it.'));
- if (scope && scope.mode === 'allow') wrap.append(el('p', 'hm-row-meta', scopeSentence(scope)));
- return wrap;
-}
-
-/** "The kitchen, and 2 individual devices." Never a raw JSON blob. */
-function scopeSentence(scope) {
- const areas = Array.isArray(scope?.areas) ? scope.areas.length : 0;
- const entities = Array.isArray(scope?.entities) ? scope.entities.length : 0;
- if (!areas && !entities) return 'Nothing in this home has been shared yet.';
- const parts = [];
- if (areas) parts.push(areas === 1 ? '1 room' : `${areas} rooms`);
- if (entities) parts.push(entities === 1 ? '1 individual device' : `${entities} individual devices`);
- return `Limited to ${parts.join(' and ')}. Everything else in this home stays hidden.`;
-}
-
-function memberRow(home, member, { assignable, rerender }) {
- const li = el('li', 'hm-row');
- const main = el('div', 'hm-row-main');
-
- const title = el('p', 'hm-row-title');
- // Every one of these is a string somebody typed into a sign-up form.
- title.append(document.createTextNode(member.display_name || member.username || member.email || 'Someone'));
- title.append(document.createTextNode(' '));
- title.append(el('span', 'hm-tag', ROLE_LABEL[member.role] || member.role));
- main.append(title);
-
- if (member.email && member.display_name) main.append(el('p', 'hm-row-meta', member.email));
- main.append(el('p', 'hm-row-meta', ROLE_COPY[member.role] || ''));
- if (member.scoped) main.append(el('p', 'hm-row-meta', scopeSentence(member.scope)));
-
- // `can_manage` comes from the server. An owner row is never manageable, and an
- // admin cannot administer a peer admin, so this flag is the only thing the UI
- // consults rather than re-deriving the rank comparison and drifting from it.
- if (!member.can_manage) {
- li.append(main);
- return li;
- }
-
- const actions = el('div', 'hm-card-actions');
-
- const picker = el('select', 'hm-input');
- picker.style.width = 'auto';
- picker.setAttribute('aria-label', `Role for ${member.display_name || member.email || 'this person'}`);
- for (const role of assignable) {
- const option = el('option', '', ROLE_LABEL[role] || role);
- option.value = role;
- if (role === member.role) option.selected = true;
- picker.append(option);
- }
- picker.addEventListener('change', async () => {
- const next = picker.value;
- picker.disabled = true;
- try {
- await setHouseholdRole(home.id, { userId: member.user_id, role: next });
- rerender();
- } catch (err) {
- picker.disabled = false;
- picker.value = member.role;
- main.append(el('p', 'hm-row-meta', err?.message || 'That change did not go through.'));
- }
- });
-
- const remove = el('button', 'hm-btn hm-btn-danger', 'Remove');
- remove.type = 'button';
- remove.addEventListener('click', () => confirmRemove(li, main, home, member, rerender));
-
- actions.append(picker, remove);
- li.append(main, actions);
- return li;
-}
-
-/**
- * Removing somebody is not undoable and it revokes their standing allowances
- * with them, so the panel says exactly that before it happens rather than after.
- */
-function confirmRemove(li, main, home, member, rerender) {
- if (li.querySelector('.hm-confirm')) return;
- const box = el('div', 'hm-confirm');
- box.style.marginTop = 'var(--space-sm)';
- box.append(el('p', 'hm-row-title', `Remove ${member.display_name || member.email || 'this person'} from this home?`));
- box.append(el('p', 'hm-row-meta', 'They lose access immediately, and any standing allowance they approved is withdrawn at the same moment. You can invite them again later.'));
-
- const actions = el('div', 'hm-card-actions');
- const yes = el('button', 'hm-btn hm-btn-danger', 'Remove them');
- yes.type = 'button';
- const no = el('button', 'hm-btn hm-btn-ghost', 'Keep them');
- no.type = 'button';
- no.addEventListener('click', () => box.remove());
- yes.addEventListener('click', async () => {
- yes.disabled = true;
- no.disabled = true;
- yes.textContent = 'Removing';
- try {
- const result = await removeFromHousehold(home.id, member.user_id);
- const revoked = Array.isArray(result?.grants_revoked) ? result.grants_revoked.length : 0;
- rerender();
- if (revoked) {
- main.append(el('p', 'hm-row-meta', revoked === 1
- ? 'Their standing allowance was withdrawn with them.'
- : `${revoked} standing allowances were withdrawn with them.`));
- }
- } catch (err) {
- yes.disabled = false;
- no.disabled = false;
- yes.textContent = 'Try again';
- box.append(el('p', 'hm-row-meta', err?.message || 'That did not go through.'));
- }
- });
- actions.append(yes, no);
- box.append(actions);
- li.append(box);
- yes.focus();
-}
-
-function inviteRow(home, invite, { canAdminister, rerender }) {
- const li = el('li', 'hm-row');
- const main = el('div', 'hm-row-main');
-
- const title = el('p', 'hm-row-title');
- title.append(document.createTextNode(invite.email));
- title.append(document.createTextNode(' '));
- title.append(el('span', 'hm-tag', ROLE_LABEL[invite.role] || invite.role));
- main.append(title);
- main.append(el('p', 'hm-row-meta', `Invited, not yet accepted. The link stops working ${relativeWhen(invite.expires_at)}.`));
-
- li.append(main);
- if (!canAdminister) return li;
-
- const withdraw = el('button', 'hm-btn hm-btn-danger', 'Withdraw');
- withdraw.type = 'button';
- withdraw.addEventListener('click', async () => {
- withdraw.disabled = true;
- withdraw.textContent = 'Withdrawing';
- try {
- await revokeHouseholdInvite(home.id, invite.id);
- rerender();
- } catch (err) {
- withdraw.disabled = false;
- withdraw.textContent = 'Try again';
- main.append(el('p', 'hm-row-meta', err?.message || 'That did not go through.'));
- }
- });
- li.append(withdraw);
- return li;
-}
-
-function inviteForm(home, { assignable, rerender }) {
- const form = el('form', 'hm-panel');
- form.style.marginTop = 'var(--space-sm)';
- form.style.background = 'transparent';
- form.append(el('h3', 'hm-panel-title', 'Invite somebody'));
- form.append(el('p', 'hm-panel-sub', 'They get a link that works once and expires. Accepting it needs a three.ws account; if they do not have one, the link walks them through making one and brings them straight back.'));
-
- const emailField = el('label', 'hm-field');
- emailField.append(el('span', 'hm-label', 'Their email address'));
- const email = el('input', 'hm-input');
- email.type = 'email';
- email.required = true;
- email.autocomplete = 'email';
- email.placeholder = '[email protected]';
- emailField.append(email);
- form.append(emailField);
-
- const roleField = el('label', 'hm-field');
- roleField.append(el('span', 'hm-label', 'What they may do'));
- const role = el('select', 'hm-input');
- // Weakest first: the safe choice should be the one nearest the top, and a
- // guest is the right answer for almost everybody who is not family.
- for (const value of [...assignable].reverse()) {
- const option = el('option', '', ROLE_LABEL[value] || value);
- option.value = value;
- role.append(option);
- }
- roleField.append(role);
- form.append(roleField);
-
- const explain = el('p', 'hm-row-meta', ROLE_COPY[role.value] || '');
- form.append(explain);
- role.addEventListener('change', () => {
- explain.textContent = ROLE_COPY[role.value] || '';
- });
-
- const submit = el('button', 'hm-btn hm-btn-primary', 'Send invitation');
- submit.type = 'submit';
- const actions = el('div', 'hm-card-actions');
- actions.append(submit);
- form.append(actions);
-
- const outcome = el('div');
- form.append(outcome);
-
- form.addEventListener('submit', async (event) => {
- event.preventDefault();
- clear(outcome);
- submit.disabled = true;
- submit.textContent = 'Sending';
- try {
- const result = await inviteToHousehold(home.id, { email: email.value.trim(), role: role.value });
- email.value = '';
- // The link is shown once, here, because the server keeps only a hash of
- // it. Telling somebody to "check the invitations list for the link"
- // would be a promise this system cannot keep.
- outcome.append(inviteLinkBlock(result?.invite_url));
- rerender();
- } catch (err) {
- outcome.append(noticeEl({
- tone: 'error',
- title: 'That invitation was not sent.',
- body: err?.message || 'Check the address and try again.',
- }));
- } finally {
- submit.disabled = false;
- submit.textContent = 'Send invitation';
- }
- });
-
- return form;
-}
-
-function inviteLinkBlock(url) {
- const wrap = el('div', 'hm-notice hm-notice-ok');
- wrap.setAttribute('role', 'status');
- const inner = el('div');
- inner.append(el('p', 'hm-row-title', 'Send them this link'));
- inner.append(el('p', 'hm-row-meta', 'It works once and then stops. We only keep a fingerprint of it, so this is the only time it can be shown.'));
-
- const field = el('div', 'hm-card-actions');
- const box = el('input', 'hm-input');
- box.readOnly = true;
- box.value = url || '';
- box.addEventListener('focus', () => box.select());
- const copy = el('button', 'hm-btn hm-btn-ghost', 'Copy');
- copy.type = 'button';
- copy.addEventListener('click', async () => {
- try {
- await navigator.clipboard.writeText(box.value);
- copy.textContent = 'Copied';
- } catch {
- // A browser that refuses clipboard access is not an error state: the
- // link is already on screen and selectable.
- box.focus();
- copy.textContent = 'Select and copy';
- }
- });
- field.append(box, copy);
- inner.append(field);
- wrap.append(inner);
- return wrap;
-}
-
-function emptyBlock(title, body) {
- const wrap = el('div', 'hm-empty');
- wrap.style.padding = 'var(--space-md) 0';
- wrap.append(el('p', 'hm-empty-title', title), el('p', 'hm-empty-body', body));
- return wrap;
-}
-
-/** "in 6 days", "today". An expiry nobody can read is an expiry nobody plans around. */
-function relativeWhen(iso) {
- const at = Date.parse(iso || '');
- if (!Number.isFinite(at)) return 'soon';
- const days = Math.round((at - Date.now()) / 86_400_000);
- if (days <= 0) return 'today';
- if (days === 1) return 'tomorrow';
- return `in ${days} days`;
-}
diff --git a/src/home/scene-render.js b/src/home/scene-render.js
index c0507b5ad..02772be88 100644
--- a/src/home/scene-render.js
+++ b/src/home/scene-render.js
@@ -660,14 +660,6 @@ export function createHomeScene(container, options = {}) {
controls.update();
}
- /**
- * Move the camera onto a room.
- *
- * Deliberately silent: this is the ANSWER to a focus request, not a new one.
- * Firing `onFocusRoom` from here meant the page's own handler called back
- * into it and the two recursed until the stack ran out, which is exactly what
- * clicking a room in the rail did.
- */
function focusRoom(roomId) {
const record = rooms.get(roomId);
if (!record || !model) return;
@@ -676,6 +668,7 @@ export function createHomeScene(container, options = {}) {
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() {
diff --git a/tests/e2e/home-connect.spec.js b/tests/e2e/home-connect.spec.js
index 076dfbd7d..cf5f53221 100644
--- a/tests/e2e/home-connect.spec.js
+++ b/tests/e2e/home-connect.spec.js
@@ -1,280 +1,62 @@
/**
- * /smart-home, the connect flow, driven in a real browser.
+ * Journeys 1, 9 and 10: getting a house connected, keeping what you drew on it,
+ * and the refusal that costs nothing.
*
- * This page has no single "content" state. It resolves who is asking, what they
- * have already connected, and what the house said, then renders exactly one of
- * twelve screens. Every defect asserted below is invisible to a unit test,
- * because it only exists once the browser has run the flow:
- *
- * - The private-host refusal has to cost ZERO network calls. It is the whole
- * reason the reachability rules are duplicated into the browser: a
- * 192.168.x.x address is unreachable by definition, and waiting fifteen
- * seconds to say so is a worse version of a sentence we could say on the
- * keystroke. A unit test can assert the predicate; only a browser can prove
- * nothing was sent.
- * - A rejected token must return focus to the token field. Sending a keyboard
- * user back to the top of the form to walk it again is the difference
- * between a designed failure and a dead end, and focus is not observable
- * without a real document.
- * - The access token must not survive anywhere in the browser. Asserting
- * "we never call localStorage.setItem" is a proxy; asserting the token is
- * absent from localStorage, sessionStorage, the URL and every response body
- * after a real submit is the actual promise.
- * - Every string that came from a house is rendered as text. A label
- * containing markup has to appear as characters, not as elements.
- *
- * The session and the API are fulfilled at the Playwright route layer, the way
- * the other flow specs in this directory do it, so the run needs no account and
- * no Home Assistant. Everything between the response and the assertion is the
- * shipped client code in src/home/.
+ * Real page, real API, real Home Assistant. See tests/e2e/home-support.js for
+ * why nothing in this lane is stubbed.
*/
import { expect, test } from '@playwright/test';
-const PAGE = '/smart-home';
-const LIST = '**/api/home';
-const CSRF = '**/api/csrf-token';
-
-// First hit transforms this page's module graph through the dev server.
-const SLOW = 60_000;
-
-const HOME = {
- id: '2b0d4c7e-1f8a-4c3d-9e11-7a6b5c4d3e2f',
- label: 'Home',
- base_url: 'https://home.example.com',
- transport: 'direct',
- relay_id: null,
- status: 'connected',
- status_detail: null,
- capabilities: { websocket: true, entityCount: 120, areaCount: 3, floorCount: 1, macroCount: 2, haVersion: '2026.9.0', mcp: false, mcpToolCount: 0 },
- last_ok_at: new Date().toISOString(),
- last_error_at: null,
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- revoked_at: null,
-};
-
-function json(body, status = 200) {
- return { status, contentType: 'application/json', body: JSON.stringify(body) };
-}
-
-/** Everything the page reads, with the home list under the caller's control. */
-async function stub(page, { homes = [], onConnect } = {}) {
- await page.route(CSRF, (route) => route.fulfill(json({ token: 'csrf-test-token', data: { token: 'csrf-test-token' } })));
- await page.route(LIST, async (route) => {
- if (route.request().method() === 'POST') {
- const body = JSON.parse(route.request().postData() || '{}');
- return route.fulfill(onConnect ? onConnect(body) : json({ home: HOME, capabilities: HOME.capabilities }, 201));
- }
- return route.fulfill(json({ homes }));
- });
-}
-
-const state = (page) => page.locator('#hm-root');
-
-test.describe('/smart-home connect flow', () => {
- test('signed out offers a way in rather than a dead form', async ({ page }) => {
- await page.route(LIST, (route) => route.fulfill(json({ error: 'unauthorized' }, 401)));
- await page.goto(PAGE);
- await expect(state(page)).toHaveAttribute('data-state', 'signed_out', { timeout: SLOW });
-
- // A disabled form would look broken and explain nothing.
- await expect(page.locator('#hm-url')).toHaveCount(0);
- await expect(page.getByRole('link', { name: /sign in/i })).toBeVisible();
- });
-
- test('the empty state carries the connect card and where to mint a token', async ({ page }) => {
- await stub(page);
- await page.goto(PAGE);
- await expect(state(page)).toHaveAttribute('data-state', 'empty', { timeout: SLOW });
-
- await expect(page.locator('#hm-url')).toBeVisible();
- // The token instructions are inline: nobody should have to go and search.
- await expect(page.getByText(/long-lived access tokens/i)).toBeVisible();
- });
-
- test('a private address is refused with no network call at all', async ({ page }) => {
- await stub(page);
- await page.goto(PAGE);
- await expect(state(page)).toHaveAttribute('data-state', 'empty', { timeout: SLOW });
-
- const sent = [];
- page.on('request', (r) => { if (r.url().includes('/api/')) sent.push(`${r.method()} ${r.url()}`); });
-
- await page.fill('#hm-label', 'Home');
- await page.fill('#hm-url', 'http://192.168.1.10:8123');
- await page.fill('#hm-token', 'a-token-that-must-never-be-sent');
- await page.click('button[type="submit"]');
-
- await expect(state(page)).toHaveAttribute('data-state', 'private_host');
- expect(sent, 'a LAN address must be refused before the network, not after a timeout').toEqual([]);
+import { connectHome, homeInstance, recordRequests, signUp } from './home-support.js';
- // And it must name the two real ways round it, not just say no.
- await expect(page.getByText(/remote https address/i)).toBeVisible();
- await expect(page.getByText(/add-on/i)).toBeVisible();
- });
+test.describe.configure({ mode: 'serial' });
- test('a rejected token says so and puts focus back in the token field', async ({ page }) => {
- await stub(page, {
- onConnect: () => json({ error: 'auth', code: 'auth', message: 'Home Assistant rejected that access token.' }, 400),
- });
- await page.goto(PAGE);
- await expect(state(page)).toHaveAttribute('data-state', 'empty', { timeout: SLOW });
+test('journey 1: connect a home, see the rooms, disconnect', async ({ page }) => {
+ const instance = homeInstance();
+ await signUp(page);
+ const label = await connectHome(page, { label: 'Journey one' });
- await page.fill('#hm-url', 'https://home.example.com');
- await page.fill('#hm-token', 'wrong');
- await page.click('button[type="submit"]');
+ // The house is read, not assumed: the page must show a room that exists in
+ // the real registry, so a hardcoded room list could not pass this.
+ const rooms = await fetch(`${instance.baseUrl}/api/states`, {
+ headers: { authorization: `Bearer ${instance.token}` },
+ }).then((r) => r.json());
+ expect(rooms.length).toBeGreaterThan(0);
- await expect(state(page)).toHaveAttribute('data-state', 'auth_failed');
- // The URL was fine, so the user must not be sent back to re-check it.
- await expect(page.locator('#hm-token')).toBeFocused();
- await expect(page.locator('#hm-url')).toHaveValue('https://home.example.com');
- });
+ await expect(page.getByText(label, { exact: false }).first()).toBeVisible();
- test('an unreachable house distinguishes itself from a wrong address', async ({ page }) => {
- await stub(page, {
- onConnect: () => json({ error: 'unreachable', code: 'unreachable', message: 'Could not reach https://home.example.com.' }, 502),
- });
- await page.goto(PAGE);
- await expect(state(page)).toHaveAttribute('data-state', 'empty', { timeout: SLOW });
+ // Disconnecting destroys the credential. The page has to end up somewhere
+ // that offers connecting again, not on a dead end.
+ const disconnect = page.getByRole('button', { name: /disconnect|remove|revoke/i }).first();
+ await expect(disconnect).toBeVisible({ timeout: 30_000 });
+ await disconnect.click();
- await page.fill('#hm-url', 'https://home.example.com');
- await page.fill('#hm-token', 'a-plausible-token');
- await page.click('button[type="submit"]');
+ const confirm = page.getByRole('button', { name: /^(disconnect|remove|revoke|yes)/i }).last();
+ if (await confirm.isVisible().catch(() => false)) await confirm.click();
- await expect(state(page)).toHaveAttribute('data-state', 'unreachable');
- await expect(page.getByText(/check the house is online/i)).toBeVisible();
- });
-
- test('the plan ceiling offers the upgrade, not a form that would fail again', async ({ page }) => {
- await stub(page, {
- onConnect: () => json({
- error: 'quota_exceeded',
- code: 'quota_exceeded',
- message: 'Your plan covers 1 home.',
- quota: { dimension: 'homes', limit: 1, used: 1, tier: 'free', upgrade: '/pricing' },
- }, 402),
- });
- await page.goto(PAGE);
- await expect(state(page)).toHaveAttribute('data-state', 'empty', { timeout: SLOW });
-
- await page.fill('#hm-url', 'https://home.example.com');
- await page.fill('#hm-token', 'a-plausible-token');
- await page.click('button[type="submit"]');
-
- await expect(state(page)).toHaveAttribute('data-state', 'quota_reached');
- // Re-submitting the same house would hit the same wall, so there is no form.
- await expect(page.locator('#hm-url')).toHaveCount(0);
- await expect(page.getByRole('link', { name: /see the plans/i })).toHaveAttribute('href', '/pricing');
- });
-
- test('a successful connect shows the measured house and drops the token', async ({ page }) => {
- let listed = [];
- await page.route(CSRF, (route) => route.fulfill(json({ token: 'csrf-test-token' })));
- await page.route(LIST, async (route) => {
- if (route.request().method() === 'POST') {
- listed = [HOME];
- return route.fulfill(json({ home: HOME, capabilities: HOME.capabilities }, 201));
- }
- return route.fulfill(json({ homes: listed }));
- });
- await page.goto(PAGE);
- await expect(state(page)).toHaveAttribute('data-state', 'empty', { timeout: SLOW });
-
- await page.fill('#hm-url', 'https://home.example.com');
- await page.fill('#hm-token', 'a-real-looking-token');
- await page.click('button[type="submit"]');
-
- await expect(state(page)).toHaveAttribute('data-state', 'connected');
- // Measured, not assumed: the numbers came back from the house.
- await expect(page.getByText('120')).toBeVisible();
- await expect(page.getByText('2026.9.0')).toBeVisible();
- // The form is gone, and with it the field that held the credential.
- await expect(page.locator('#hm-token')).toHaveCount(0);
- });
-
- test('the token reaches no browser storage, no URL and no response body', async ({ page }) => {
- const CANARY = 'CANARY-TOKEN-do-not-store-me';
- const bodies = [];
- await stub(page, {
- onConnect: () => json({ error: 'unreachable', code: 'unreachable', message: 'Could not reach it.' }, 502),
- });
- page.on('response', async (r) => {
- if (!r.url().includes('/api/')) return;
- bodies.push(await r.text().catch(() => ''));
- });
-
- await page.goto(PAGE);
- await expect(state(page)).toHaveAttribute('data-state', 'empty', { timeout: SLOW });
- await page.fill('#hm-url', 'https://home.example.com');
- await page.fill('#hm-token', CANARY);
- await page.click('button[type="submit"]');
- await expect(state(page)).toHaveAttribute('data-state', 'unreachable');
-
- const found = await page.evaluate((canary) => {
- const dump = (s) => Array.from({ length: s.length }, (_, i) => s.getItem(s.key(i)) || '').join('\n');
- return {
- local: dump(localStorage).includes(canary),
- session: dump(sessionStorage).includes(canary),
- url: location.href.includes(canary),
- };
- }, CANARY);
-
- expect(found.local, 'the token must never be written to localStorage').toBe(false);
- expect(found.session, 'the token must never be written to sessionStorage').toBe(false);
- expect(found.url, 'the token must never appear in a URL').toBe(false);
- expect(bodies.some((b) => b.includes(CANARY)), 'the API must never echo the token back').toBe(false);
- });
-
- test('a label from a house is rendered as text, never as markup', async ({ page }) => {
- const hostile = '<img src=x onerror="window.__xss=1">Kitchen';
- await stub(page, { homes: [{ ...HOME, label: hostile }] });
- await page.goto(PAGE);
- await expect(state(page)).toHaveAttribute('data-state', 'connected', { timeout: SLOW });
-
- // The characters are on the page; the element is not, and nothing ran.
- await expect(page.locator('.hm-card-label')).toHaveText(hostile);
- await expect(page.locator('.hm-card-label img')).toHaveCount(0);
- expect(await page.evaluate(() => window.__xss)).toBeUndefined();
- });
-
- test('the token field is a password field with a working reveal toggle', async ({ page }) => {
- await stub(page);
- await page.goto(PAGE);
- await expect(state(page)).toHaveAttribute('data-state', 'empty', { timeout: SLOW });
+ await expect(page.locator('#hm-url')).toBeVisible({ timeout: 60_000 });
+});
- const field = page.locator('#hm-token');
- await expect(field).toHaveAttribute('type', 'password');
- await expect(field).toHaveAttribute('autocomplete', 'off');
+test('journey 10: a private host is refused in the browser, with no network call', async ({ page }) => {
+ await signUp(page);
+ await page.goto('/smart-home', { waitUntil: 'domcontentloaded' });
+ await expect(page.locator('#hm-url')).toBeVisible({ timeout: 60_000 });
- await page.getByRole('button', { name: 'Show' }).click();
- await expect(field).toHaveAttribute('type', 'text');
- await page.getByRole('button', { name: 'Hide' }).click();
- await expect(field).toHaveAttribute('type', 'password');
- });
+ // Record only the calls that would mean we tried to reach the house. The
+ // claim being proved is about what did NOT happen.
+ const attempts = recordRequests(page, (req) => /\/api\/home(\/|$|\?)/.test(new URL(req.url()).pathname + '?'));
+ attempts.length = 0;
- test('the whole connect is completable from the keyboard alone', async ({ page }) => {
- await stub(page, {
- onConnect: () => json({ error: 'unreachable', code: 'unreachable', message: 'Could not reach it.' }, 502),
- });
- await page.goto(PAGE);
- await expect(state(page)).toHaveAttribute('data-state', 'empty', { timeout: SLOW });
+ await page.fill('#hm-label', 'The LAN house');
+ await page.fill('#hm-url', 'http://homeassistant.local:8123');
+ await page.fill('#hm-token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.not-a-real-token');
- await page.locator('#hm-label').focus();
- await page.keyboard.type('Home');
- await page.keyboard.press('Tab');
- await expect(page.locator('#hm-url')).toBeFocused();
- await page.keyboard.type('https://home.example.com');
- await page.keyboard.press('Tab');
- await expect(page.locator('#hm-token')).toBeFocused();
- await page.keyboard.type('a-token');
- // Tab reaches the reveal toggle, then the submit button.
- await page.keyboard.press('Tab');
- await expect(page.getByRole('button', { name: 'Show' })).toBeFocused();
- await page.keyboard.press('Tab');
- await expect(page.getByRole('button', { name: /connect this home/i })).toBeFocused();
- await page.keyboard.press('Enter');
+ const before = attempts.length;
+ await page.getByRole('button', { name: 'Connect this home' }).click();
- await expect(state(page)).toHaveAttribute('data-state', 'unreachable');
- });
+ // The refusal names the host and says why, rather than timing out into a
+ // vaguer version of the same sentence.
+ await expect(page.getByText(/only on your home network|cannot be reached/i).first()).toBeVisible({ timeout: 20_000 });
+ expect(attempts.slice(before), 'a refused private host must cost no request').toEqual([]);
});