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.

feat(home): draw all seven states of pairing a house that cannot be dialed

nirholas39785613bf43
diff --git a/api/_lib/home/entitlements.js b/api/_lib/home/entitlements.js
index a2a32ec47..c7ec7281d 100644
--- a/api/_lib/home/entitlements.js
+++ b/api/_lib/home/entitlements.js
@@ -857,6 +857,10 @@ export function describeEntitlements(entitlements, usage = {}, { now = new Date(
percent: unlimited ? 0 : limit === 0 ? 100 : Math.min(100, Math.round((used / limit) * 100)),
exceeded: !unlimited && used > limit,
source: entitlements.sources[id],
+ // A ceiling dimension is not consumed: sitting at it is the normal,
+ // healthy state (the retention default IS the free ceiling), so the
+ // surface must not paint it as "you are out of something".
+ ceilingOnly: Boolean(meta.ceilingOnly),
resetsAt: meta.period === 'month' ? period.endIso : null,
costPerUnitUsd: meta.costPerUnitUsd,
costBasis: meta.costBasis,
diff --git a/api/chat.js b/api/chat.js
index 0860957f1..fdeaf423c 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -445,8 +445,16 @@ const HOME_OPENAI_TOOLS = HOME_ANTHROPIC_TOOLS.map(toOpenAiTool);
/** The tool set a route sends when the caller has no home connected. */
const DEFAULT_TOOL_SET = Object.freeze({ anthropic: ACTION_TOOLS, openai: OPENAI_TOOLS });
-/** One round of server-side home tools per turn: enough to read and act, never a loop. */
-const HOME_TOOL_ROUNDS = 1;
+/**
+ * Server-side home rounds per turn.
+ *
+ * Two, because the shape a person actually asks for is "check the house, then do
+ * the thing": read the state, act on what it said. One round produced an agent
+ * that answered "I don't have a tool for that" after reading the house, which is
+ * both useless and untrue. The last round is offered no home tools at all, so
+ * the ceiling is a hard stop rather than a heuristic.
+ */
+const HOME_TOOL_ROUNDS = 2;
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -1024,63 +1032,66 @@ export default wrap(async (req, res) => {
//
// So home tools run HERE, on the server, through the same handler module the
// MCP surface uses, and their results go back to the model for one more pass.
- // Exactly one round: enough to read the house and act on it, never a loop, and
- // the second pass is offered no home tools at all.
+ // Two rounds at most: read the house, act on what it said. The final pass is
+ // offered no home tools at all, which is what bounds the loop mechanically.
//
// Nothing in this block can approve anything. `runHomeTool` returns a
// `pending_confirmation` for a guarded action and the browser renders it as a
// card; the approval happens at /api/home/:id/confirm, which this file never
// calls and no model can reach.
- const homeCalls = (result.toolCalls || []).filter((c) => isHomeTool(c.name));
let homeResults = [];
- /**
- * The home this turn touched, stamped into the usage row below.
- *
- * This is what makes a home agent turn countable WITHOUT a second counter:
- * the row the chat meter already writes (priced, with the real token counts)
- * is the same row the Home lane's quota reads, distinguished only by this
- * key. See api/_lib/home/usage.js.
- */
- let homeTouched = null;
- if (homeCalls.length && auth?.userId) {
- homeResults = await runHomeRound(homeCalls, auth.userId);
- for (const entry of homeResults) {
- // Streamed immediately, ahead of the model's second pass, so a
- // confirmation card is on screen while the model is still composing the
- // sentence that explains it.
- const touchedId = entry.result.structured?.home?.id || entry.call.input?.home_id || null;
- if (touchedId) homeTouched = touchedId;
- sendSSE({
- type: 'home_tool',
- tool: entry.call.name,
- status: entry.result.kind,
- home_id: touchedId,
- data: entry.result.structured,
+ if (auth?.userId && (result.toolCalls || []).some((c) => isHomeTool(c.name))) {
+ let pass = result;
+ let workingHistory = history;
+ for (let round = 0; round < HOME_TOOL_ROUNDS; round++) {
+ const calls = (pass.toolCalls || []).filter((c) => isHomeTool(c.name));
+ if (!calls.length) break;
+
+ const roundResults = await runHomeRound(calls, auth.userId);
+ homeResults = [...homeResults, ...roundResults];
+ for (const entry of roundResults) {
+ // Streamed immediately, ahead of the model's next pass, so a
+ // confirmation card is on screen while the model is still composing
+ // the sentence that explains it.
+ sendSSE({
+ type: 'home_tool',
+ tool: entry.call.name,
+ status: entry.result.kind,
+ home_id: entry.result.structured?.home?.id || entry.call.input?.home_id || null,
+ data: entry.result.structured,
+ });
+ }
+
+ const followUp = await runFollowUpPass({
+ route,
+ systemPrompt,
+ sys,
+ history: workingHistory,
+ maxTokens,
+ assistantText: pass.reply,
+ toolCalls: pass.toolCalls,
+ homeResults: roundResults,
+ // The last round hands over no home tools, which is what bounds this
+ // loop mechanically rather than by hoping the model stops asking.
+ toolSet: round === HOME_TOOL_ROUNDS - 1 ? DEFAULT_TOOL_SET : toolSet,
+ sendSSE,
});
- }
+ if (!followUp) break;
- const followUp = await runFollowUpPass({
- route,
- systemPrompt,
- sys,
- history,
- maxTokens,
- assistantText: result.reply,
- toolCalls: result.toolCalls,
- homeResults,
- sendSSE,
- });
- if (followUp) {
result.reply = [result.reply.trim(), followUp.reply.trim()].filter(Boolean).join('\n\n');
result.actions = [...result.actions, ...followUp.actions];
result.inputTokens += followUp.inputTokens || 0;
result.outputTokens += followUp.outputTokens || 0;
result.cacheWriteTokens = (result.cacheWriteTokens || 0) + (followUp.cacheWriteTokens || 0);
result.cacheReadTokens = (result.cacheReadTokens || 0) + (followUp.cacheReadTokens || 0);
- } else if (!result.reply.trim()) {
- // The second pass could not run (a provider blip, a spent time budget).
- // The tools still ran and the user still deserves the answer, so speak
- // the handler's own sentences rather than returning an empty turn.
+ workingHistory = followUp.history;
+ pass = followUp;
+ }
+
+ if (!result.reply.trim()) {
+ // No pass could speak (a provider blip, a spent time budget). The tools
+ // still ran and the user still deserves the answer, so speak the
+ // handler's own sentences rather than returning an empty turn.
result.reply = homeResults.map((entry) => entry.result.text).join('\n\n');
}
}
@@ -1243,14 +1254,15 @@ async function runHomeRound(calls, userId) {
* included. Both wire formats reject an assistant turn with an unanswered
* tool call, and the honest answer for a viewer action is "the browser is
* doing it", which is exactly what the model should believe.
- * 2. The second pass is offered NO home tools. That is what makes this one
- * round rather than a loop, and it is why a model that just received a
- * pending confirmation cannot respond by asking to unlock the door again.
+ * 2. The caller decides which tools this pass may use. The final round is
+ * handed none of the home tools, which is what bounds the loop
+ * mechanically, and is why a model that just received a pending
+ * confirmation cannot answer by asking to unlock the door again.
*
* Returns null on any failure. The caller falls back to the tool text, so a
* provider blip costs the turn its prose, never its truth.
*/
-async function runFollowUpPass({ route, systemPrompt, sys, history, maxTokens, assistantText, toolCalls, homeResults, sendSSE }) {
+async function runFollowUpPass({ route, systemPrompt, sys, history, maxTokens, assistantText, toolCalls, homeResults, toolSet, sendSSE }) {
if (route.style === 'orchestrate') return null;
const resultText = new Map(homeResults.map((entry) => [entry.call.id, entry.result]));
@@ -1309,7 +1321,7 @@ async function runFollowUpPass({ route, systemPrompt, sys, history, maxTokens, a
history: nextHistory,
maxTokens,
includeTools: true,
- toolSet: DEFAULT_TOOL_SET,
+ toolSet: toolSet || DEFAULT_TOOL_SET,
}),
),
signal: ctrl.signal,
@@ -1322,7 +1334,9 @@ async function runFollowUpPass({ route, systemPrompt, sys, history, maxTokens, a
return null;
}
const followUp = anthropic ? await streamAnthropic(upstream, sendSSE) : await streamOpenAI(upstream, sendSSE);
- return followUp.error ? null : followUp;
+ // The history this pass was built on rides back out, so a second round
+ // continues the same conversation instead of rebuilding it from the top.
+ return followUp.error ? null : { ...followUp, history: nextHistory };
} catch (err) {
captureException(err, { route: 'chat', stage: 'home-follow-up', provider: route.name });
return null;
diff --git a/packages/home-bridge/src/bridge.js b/packages/home-bridge/src/bridge.js
index ebea2d42a..8730bd200 100644
--- a/packages/home-bridge/src/bridge.js
+++ b/packages/home-bridge/src/bridge.js
@@ -34,6 +34,7 @@ export class HomeBridge {
#graph = { floors: [], rooms: [], unassigned: [], temperatureUnit: null };
#listeners = new Map();
#rebuildTimer = null;
+ #registryTimer = null;
#closed = false;
/**
@@ -174,6 +175,7 @@ export class HomeBridge {
this.#scheduleRebuild();
}),
);
+ await this.#watchRegistries();
await this.#waitForFirstStates();
this.#rebuild();
@@ -193,6 +195,56 @@ export class HomeBridge {
});
}
+ /**
+ * Keep the registries live.
+ *
+ * They were loaded once, at connect, and never again. Everything the room
+ * graph is made of lives in them: which room an entity is in, what a room is
+ * called, which floor it is on. So renaming a room, creating one, or filing a
+ * device into an area changed nothing on screen until the pooled socket
+ * happened to be recycled, which is minutes later or never. A user who just
+ * assigned their kitchen light to the kitchen watched nothing happen.
+ *
+ * Home Assistant announces every one of those changes on the same socket. We
+ * listen, reload the four lists once per burst, and rebuild.
+ *
+ * The reload is coalesced because assigning ten entities to an area emits ten
+ * events, and each reload is four round trips.
+ */
+ async #watchRegistries() {
+ const events = [
+ 'area_registry_updated',
+ 'device_registry_updated',
+ 'entity_registry_updated',
+ 'floor_registry_updated',
+ ];
+ for (const event_type of events) {
+ try {
+ const stop = await this.#connection.subscribeEvents(() => this.#scheduleRegistryReload(), event_type);
+ this.#unsubscribers.push(stop);
+ } catch {
+ // An instance too old to know one of these events is not broken; it
+ // just keeps the connect-time registries for that dimension.
+ }
+ }
+ }
+
+ #scheduleRegistryReload() {
+ if (this.#registryTimer) return;
+ this.#registryTimer = setTimeout(async () => {
+ this.#registryTimer = null;
+ if (this.#closed || !this.#connection) return;
+ try {
+ this.#registries = await this.#loadRegistries();
+ } catch {
+ // A failed reload keeps the last good registries rather than emptying
+ // the house, which is the rule everywhere else in this file too.
+ return;
+ }
+ this.#rebuild();
+ }, this.#options.registryReloadDelayMs ?? 400);
+ }
+
async #loadRegistries() {
// floor_registry landed after the other three. An instance without it is
// not broken, it just has no floors, so a failure here degrades to [].
@@ -318,6 +370,8 @@ export class HomeBridge {
this.#closed = true;
if (this.#rebuildTimer) clearTimeout(this.#rebuildTimer);
this.#rebuildTimer = null;
+ if (this.#registryTimer) clearTimeout(this.#registryTimer);
+ this.#registryTimer = null;
for (const stop of this.#unsubscribers) {
try {
stop();
diff --git a/packages/home-bridge/tests/fixtures/home.json b/packages/home-bridge/tests/fixtures/home.json
index c12fbbb40..b78354d2d 100644
--- a/packages/home-bridge/tests/fixtures/home.json
+++ b/packages/home-bridge/tests/fixtures/home.json
@@ -20,7 +20,7 @@
"area_id": "kitchen",
"name": "Kitchen",
"icon": "mdi:stove",
- "floor_id": null,
+ "floor_id": "ground_floor",
"aliases": []
},
{
@@ -40,312 +40,312 @@
],
"devices": [
{
- "id": "5484402f49ec4c5a5cc3057f0042aaf3",
+ "id": "94cecee119273201ec961b0b80dfd8da",
"area_id": null,
"name": "Sun"
},
{
- "id": "e29b44b4f0268dd69b5c576e5b0d8604",
+ "id": "bba9f82bb8b9772016a1b6cfd0d89315",
"area_id": null,
"name": "Basement Floor Wet"
},
{
- "id": "715267e1932503f69a7cf98760381723",
+ "id": "ad1f20d95f681ec6c991c0e63db9ba92",
"area_id": null,
"name": "Movement Backyard"
},
{
- "id": "12992da36230b887d704adef59daecf7",
+ "id": "1a4631ab6e55dcfc8d204d1e6bb24331",
"area_id": null,
"name": "Outside Temperature"
},
{
- "id": "f6945939e4c8fdf23ef322128a03cb20",
+ "id": "8a0bd43b6a83fbcbc84cc5a436ec0c01",
"area_id": null,
"name": "Push"
},
{
- "id": "b39ea500b282b16f384c208e39235f41",
+ "id": "4767e3783bad038a71f76cba841a1a78",
"area_id": null,
"name": "HeatPump"
},
{
- "id": "c90c8f080bcea0227f67ffa0c7bcbdf8",
+ "id": "2b87fde685cdd3e3be3978f844e9810e",
"area_id": null,
"name": "Hvac"
},
{
- "id": "e9f4028288367ff1173fab481d8016fd",
+ "id": "8ac6c21e55881123c6e2aae8cd88da26",
"area_id": null,
"name": "Ecobee"
},
{
- "id": "b8d215b824f80d9cc24ceb0e262b8d11",
+ "id": "26070b9958d456eeaa08d43acd887b21",
"area_id": null,
"name": "Kitchen Window"
},
{
- "id": "6a690f56c69b29c98f59712e5f096d20",
+ "id": "ee620da2eb601cc167ac762a3afeb426",
"area_id": null,
"name": "Hall Window"
},
{
- "id": "83a4887330f7eecc3d8ba0d5784f48f7",
+ "id": "70972ac0a8c760d3aba2da5e94875fd6",
"area_id": null,
"name": "Living Room Window"
},
{
- "id": "4f5cf01ee3ad1ceffe4bdcc124ee478b",
+ "id": "b43e691d23b1c4550dacf1fc9bc14562",
"area_id": null,
"name": "Garage Door"
},
{
- "id": "94bf640e8ec1028854943d80acb4b4b8",
+ "id": "8479e3f07440dcf30928b545bedacb29",
"area_id": null,
"name": "Pergola Roof"
},
{
- "id": "40c98dc7c0157b7dde6b4b4fa063b8ca",
+ "id": "cb8a87626d169b071b456b603c5e77d4",
"area_id": null,
"name": "Date"
},
{
- "id": "cf85a7db8415915e58da43c462d69002",
+ "id": "5202aa8d76008f11ec4df773106d0c3d",
"area_id": null,
"name": "Date and Time"
},
{
- "id": "0ddd1624681cc5919bfdbeb55e800864",
+ "id": "d226184082bc1596f8c99d61181c069f",
"area_id": null,
"name": "Bed Light"
},
{
- "id": "8e54d5e186357e7b8adc5122a791619a",
+ "id": "fe3d511118b2e467c0e88b494272428e",
"area_id": null,
"name": "Ceiling Lights"
},
{
- "id": "1886460066d589499d4182a5b45e84f5",
+ "id": "59d9032003ad8f9d15127352958db651",
"area_id": null,
"name": "Kitchen Lights"
},
{
- "id": "6093410db516b385aa1436573da46f77",
+ "id": "981fb226ba4e2da0c1566a4700a53905",
"area_id": null,
"name": "Office RGBW Lights"
},
{
- "id": "7a83cb511b02f2f1d0268b9f812e5e73",
+ "id": "b74ca6046798267939798bfe98cb47bd",
"area_id": null,
"name": "Living Room RGBWW Lights"
},
{
- "id": "819228fc4201ea4b70283a57975e6e80",
+ "id": "f0e7af5265bee3c2b53bf1903ab7f530",
"area_id": null,
"name": "Entrance Color + White Lights"
},
{
- "id": "92e093e68d39e13f6fede07a403743ce",
+ "id": "92eb4bfacb8bb68a6cf2f648d51c878b",
"area_id": null,
"name": "Notifier"
},
{
- "id": "5ee8e1423827244bdbd0544f5282032c",
+ "id": "96e1041f27e9c06d71a7f18fb8f7e66b",
"area_id": null,
"name": "volume"
},
{
- "id": "e44481c528e6c5ce7a3d91f84704b8d1",
+ "id": "195ea0050487052de280ab1ee5d46cd0",
"area_id": null,
"name": "PWM 1"
},
{
- "id": "5128fa189aa813e1bebf9b00ed65c306",
+ "id": "4f859ac1e349ffc44efb1630af95f06f",
"area_id": null,
"name": "Large Range"
},
{
- "id": "4ff4968e3164ae74a1d9fcbf36a9eef3",
+ "id": "2359bfd45af8b6b66ceb302caf436385",
"area_id": null,
"name": "Small Range"
},
{
- "id": "47b49b13725c1006f87e44ff6428f53f",
+ "id": "064de809931066c70f81a1a3f4e66d4d",
"area_id": null,
"name": "Temperature setting"
},
{
- "id": "b8a6e4972335c21d7621052dd069fed5",
+ "id": "dfe7283f029cf479f93d8783795e2d21",
"area_id": null,
"name": "Speed"
},
{
- "id": "aa73f012671c477334864b69b79ee726",
+ "id": "99f70dcd6eec10d948c507308cba0c2c",
"area_id": null,
"name": "Outside Humidity"
},
{
- "id": "36b429ca62ecc499285067801a95a450",
+ "id": "6234e144de623dbd09a34c50d4f7a951",
"area_id": null,
"name": "Carbon monoxide"
},
{
- "id": "468e6e9a23a2d081a37ad528c1acdb5d",
+ "id": "eaee0da93e958829abcc5722e22dd455",
"area_id": null,
"name": "Carbon dioxide"
},
{
- "id": "7929487cb712d773e6cece3119d54632",
+ "id": "8f4bf3d51a45dda9739bb17ce0f3d269",
"area_id": null,
"name": "Power consumption"
},
{
- "id": "62daf1a9d71fc9d9579e661ff7f4b160",
+ "id": "ce3a92dcacc7bd3f230f490d1b21e931",
"area_id": null,
"name": "Total energy 1"
},
{
- "id": "12107b6d5dea0a941d72b4fc482eeaff",
+ "id": "34dc89c6b83cb50eeb6a01b487959771",
"area_id": null,
"name": "Total energy 2"
},
{
- "id": "dfdbfd602df8b459a370c929206c8bbb",
+ "id": "44f7a8b42fb918d0010d421ff7de3a0c",
"area_id": null,
"name": "Total gas 1"
},
{
- "id": "18d0f0b1d479074511b9eb6718bbdff9",
+ "id": "d24d20cc44f9ce1034381d108adfb550",
"area_id": null,
"name": "Total gas 2"
},
{
- "id": "842aad627d7cdc9f66e32e60090212a6",
+ "id": "91f6d7b9b5fe37417e09e40420de8393",
"area_id": null,
"name": "Thermostat"
},
{
- "id": "ac0ae15a92c89ca1a494eee128bf2881",
+ "id": "486c6f889ce496d4befee96dc89064eb",
"area_id": null,
"name": "Decorative Lights"
},
{
- "id": "b1545fbbeca14c284393debbbc771e94",
+ "id": "a5e3d50225ed01528dbbda022b7bf84c",
"area_id": null,
"name": "AC"
},
{
- "id": "51bb841e1f14d69c5efce4a2941277db",
+ "id": "82449bdb950061d3c14719dd34d669b2",
"area_id": null,
"name": "Text"
},
{
- "id": "79b793feaa0e16c8e3d6cb0be88e3563",
+ "id": "0f9d2b1616f579a5d1e62452fd02d283",
"area_id": null,
"name": "Password"
},
{
- "id": "f7d4a7073eef079dc47da7137e7dd9da",
+ "id": "90943cc66f72153c4b9f018e5d015b21",
"area_id": null,
"name": "Text with 1 to 5 characters"
},
{
- "id": "30c3c3e7354ce1dbec7a6b2f20533059",
+ "id": "3222dea7c1c91480400f1d992243a62c",
"area_id": null,
"name": "Text with only lower case characters"
},
{
- "id": "52dca23c9108bef6fd2457a7f233846f",
+ "id": "1a7d61b8b062cc06ed21800d1b29d22d",
"area_id": null,
"name": "Time"
},
{
- "id": "c2c50216f8278849f7bc79730a1756e5",
+ "id": "ab90b48d3e735c2e5d71825708f5ff92",
"area_id": null,
"name": "Demo Update No Install"
},
{
- "id": "fd35fbf460eb37a34440d1ea5dc00dee",
+ "id": "5d429d3d4ac447af2cf848884e757a51",
"area_id": null,
"name": "Demo No Update"
},
{
- "id": "ade7ec8c284365ab32c48cf3f456bc31",
+ "id": "65dafb538a490253dc5372ba97f1458e",
"area_id": null,
"name": "Demo add-on"
},
{
- "id": "9e67d30e6912dc0c84f25cdd39d39b91",
+ "id": "0f279e6223749515466335f829f17a51",
"area_id": null,
"name": "Demo Living Room Bulb Update"
},
{
- "id": "5a64169cd4f1bbe3109f2c075c5df686",
+ "id": "3945fdca83ae2080620221035a3e190e",
"area_id": null,
"name": "Demo Update with Progress"
},
{
- "id": "29a1c0a8860dd896c3738444523e5c5e",
+ "id": "f377e062dcaf36d245d1ff19b383301e",
"area_id": null,
"name": "Demo Update with Decimal Progress"
},
{
- "id": "16a220034976bd546dbeec4537cb185f",
+ "id": "24d408937cb89b9841648e5643f2a02f",
"area_id": null,
"name": "Demo vacuum 0 ground floor"
},
{
- "id": "b5f6ce92dffbd7ea527d486a906274cf",
+ "id": "1bcc09218132dbe0c05c5140ee64308a",
"area_id": null,
"name": "Demo vacuum 1 first floor"
},
{
- "id": "8fdd09d86a5afadf92664fec5cb7674a",
+ "id": "c90af629ae23f534b42abf0a44c3180f",
"area_id": null,
"name": "Demo vacuum 2 second floor"
},
{
- "id": "8f74b2893c2c0f39be3ded258fec8123",
+ "id": "d19186ff89b769838e0f7ca0c09c8c51",
"area_id": null,
"name": "Demo vacuum 3 third floor"
},
{
- "id": "0963ec135ac366cfa49cde5ae1825b2d",
+ "id": "9e757506127d048e62077f0872c93309",
"area_id": null,
"name": "Demo vacuum 4 fourth floor"
},
{
- "id": "737bd08b0a954fbe4a2d8c0d006708e1",
+ "id": "10cfa53c86cccd20edb8e8183734b9cc",
"area_id": null,
"name": "Front Garden"
},
{
- "id": "75eb3e661e401cfa340ffe59e2166e14",
+ "id": "aed25af8b1df3f0c6d5139645edcbcbf",
"area_id": null,
"name": "Orchard"
},
{
- "id": "735d5d94311e3fbfb8b19135f8cfa3ad",
+ "id": "20f9eaf9b4e6069dc0d2f03b763e0468",
"area_id": null,
"name": "Back Garden"
},
{
- "id": "00882bfe8abb6239f456c82bb12339b1",
+ "id": "9d3c34c4b54a908d257ab46bda5d6535",
"area_id": null,
"name": "Trees"
},
{
- "id": "0e36c445cfab64d2f73a0e149790b716",
+ "id": "db38ac1de1d771f15b6c6d2d7ae84f71",
"area_id": null,
"name": "Google Translate en com"
},
{
- "id": "dd1fc1a8b955673a16ea8d3efa1adfe4",
+ "id": "ccc6ebc301b813a9fbbf1585d731e3d3",
"area_id": null,
"name": "Forecast"
},
{
- "id": "1081ed6e901efaca4514d148e6fe187d",
+ "id": "4ba33a8705dc87fe3b8efe4ff0774bfa",
"area_id": null,
"name": "Backup"
}
@@ -363,8 +363,8 @@
},
{
"entity_id": "binary_sensor.basement_floor_wet",
- "device_id": "e29b44b4f0268dd69b5c576e5b0d8604",
- "area_id": null,
+ "device_id": "bba9f82bb8b9772016a1b6cfd0d89315",
+ "area_id": "front_door",
"name": null,
"original_name": null,
"original_device_class": null,
@@ -373,7 +373,7 @@
},
{
"entity_id": "binary_sensor.movement_backyard",
- "device_id": "715267e1932503f69a7cf98760381723",
+ "device_id": "ad1f20d95f681ec6c991c0e63db9ba92",
"area_id": null,
"name": null,
"original_name": null,
@@ -383,7 +383,7 @@
},
{
"entity_id": "binary_sensor.outside_temperature_battery_charging",
- "device_id": "12992da36230b887d704adef59daecf7",
+ "device_id": "1a4631ab6e55dcfc8d204d1e6bb24331",
"area_id": null,
"name": null,
"original_name": "Battery Charging",
@@ -393,7 +393,7 @@
},
{
"entity_id": "climate.heatpump",
- "device_id": "b39ea500b282b16f384c208e39235f41",
+ "device_id": "4767e3783bad038a71f76cba841a1a78",
"area_id": "living_room",
"name": null,
"original_name": null,
@@ -403,8 +403,8 @@
},
{
"entity_id": "climate.hvac",
- "device_id": "c90c8f080bcea0227f67ffa0c7bcbdf8",
- "area_id": null,
+ "device_id": "2b87fde685cdd3e3be3978f844e9810e",
+ "area_id": "bedroom",
"name": null,
"original_name": null,
"original_device_class": null,
@@ -413,7 +413,7 @@
},
{
"entity_id": "climate.ecobee",
- "device_id": "e9f4028288367ff1173fab481d8016fd",
+ "device_id": "8ac6c21e55881123c6e2aae8cd88da26",
"area_id": null,
"name": null,
"original_name": null,
@@ -423,8 +423,8 @@
},
{
"entity_id": "cover.kitchen_window",
- "device_id": "b8d215b824f80d9cc24ceb0e262b8d11",
- "area_id": null,
+ "device_id": "26070b9958d456eeaa08d43acd887b21",
+ "area_id": "living_room",
"name": null,
"original_name": null,
"original_device_class": null,
@@ -433,8 +433,8 @@
},
{
"entity_id": "cover.hall_window",
- "device_id": "6a690f56c69b29c98f59712e5f096d20",
- "area_id": null,
+ "device_id": "ee620da2eb601cc167ac762a3afeb426",
+ "area_id": "kitchen",
"name": null,
"original_name": null,
"original_device_class": null,
@@ -443,8 +443,8 @@
},
{
"entity_id": "cover.living_room_window",
- "device_id": "83a4887330f7eecc3d8ba0d5784f48f7",
- "area_id": null,
+ "device_id": "70972ac0a8c760d3aba2da5e94875fd6",
+ "area_id": "front_door",
"name": null,
"original_name": null,
"original_device_class": null,
@@ -453,7 +453,7 @@
},
{
"entity_id": "cover.garage_door",
- "device_id": "4f5cf01ee3ad1ceffe4bdcc124ee478b",
+ "device_id": "b43e691d23b1c4550dacf1fc9bc14562",
"area_id": null,
"name": null,
"original_name": null,
@@ -463,7 +463,7 @@
},
{
"entity_id": "cover.pergola_roof",
- "device_id": "94bf640e8ec1028854943d80acb4b4b8",
+ "device_id": "8479e3f07440dcf30928b545bedacb29",
"area_id": null,
"name": null,
"original_name": null,
@@ -474,7 +474,7 @@
{
"entity_id": "fan.living_room_fan",
"device_id": null,
- "area_id": null,
+ "area_id": "kitchen",
"name": null,
"original_name": "Living Room Fan",
"original_device_class": null,
@@ -484,7 +484,7 @@
{
"entity_id": "fan.ceiling_fan",
"device_id": null,
- "area_id": null,
+ "area_id": "bedroom",
"name": null,
"original_name": "Ceiling Fan",
"original_device_class": null,
@@ -523,7 +523,7 @@
},
{
"entity_id": "light.bed_light",
- "device_id": "0ddd1624681cc5919bfdbeb55e800864",
+ "device_id": "d226184082bc1596f8c99d61181c069f",
"area_id": "living_room",
"name": null,
"original_name": null,
@@ -533,8 +533,8 @@
},
{
"entity_id": "light.ceiling_lights",
- "device_id": "8e54d5e186357e7b8adc5122a791619a",
- "area_id": "bedroom",
+ "device_id": "fe3d511118b2e467c0e88b494272428e",
+ "area_id": "kitchen",
"name": null,
"original_name": null,
"original_device_class": null,
@@ -543,8 +543,8 @@
},
{
"entity_id": "light.kitchen_lights",
- "device_id": "1886460066d589499d4182a5b45e84f5",
- "area_id": "front_door",
+ "device_id": "59d9032003ad8f9d15127352958db651",
+ "area_id": "bedroom",
"name": null,
"original_name": null,
"original_device_class": null,
@@ -553,8 +553,8 @@
},
{
"entity_id": "light.office_rgbw_lights",
- "device_id": "6093410db516b385aa1436573da46f77",
- "area_id": null,
+ "device_id": "981fb226ba4e2da0c1566a4700a53905",
+ "area_id": "front_door",
"name": null,
"original_name": null,
"original_device_class": null,
@@ -563,7 +563,7 @@
},
{
"entity_id": "light.living_room_rgbww_lights",
- "device_id": "7a83cb511b02f2f1d0268b9f812e5e73",
+ "device_id": "b74ca6046798267939798bfe98cb47bd",
"area_id": null,
"name": null,
"original_name": null,
@@ -573,7 +573,7 @@
},
{
"entity_id": "light.entrance_color_white_lights",
- "device_id": "819228fc4201ea4b70283a57975e6e80",
+ "device_id": "f0e7af5265bee3c2b53bf1903ab7f530",
"area_id": null,
"name": null,
"original_name": null,
@@ -583,7 +583,7 @@
},
{
"entity_id": "sensor.outside_temperature",
- "device_id": "12992da36230b887d704adef59daecf7",
+ "device_id": "1a4631ab6e55dcfc8d204d1e6bb24331",
"area_id": null,
"name": null,
"original_name": null,
@@ -593,7 +593,7 @@
},
{
"entity_id": "sensor.outside_temperature_battery",
- "device_id": "12992da36230b887d704adef59daecf7",
+ "device_id": "1a4631ab6e55dcfc8d204d1e6bb24331",
"area_id": null,
"name": null,
"original_name": "Battery",
@@ -603,8 +603,8 @@
},
{
"entity_id": "switch.decorative_lights",
- "device_id": "ac0ae15a92c89ca1a494eee128bf2881",
- "area_id": null,
+ "device_id": "486c6f889ce496d4befee96dc89064eb",
+ "area_id": "living_room",
"name": null,
"original_name": null,
"original_device_class": null,
@@ -613,7 +613,7 @@
},
{
"entity_id": "switch.ac",
- "device_id": "b1545fbbeca14c284393debbbc771e94",
+ "device_id": "a5e3d50225ed01528dbbda022b7bf84c",
"area_id": null,
"name": null,
"original_name": null,
@@ -623,7 +623,7 @@
},
{
"entity_id": "valve.front_garden",
- "device_id": "737bd08b0a954fbe4a2d8c0d006708e1",
+ "device_id": "10cfa53c86cccd20edb8e8183734b9cc",
"area_id": null,
"name": null,
"original_name": null,
@@ -633,7 +633,7 @@
},
{
"entity_id": "valve.orchard",
- "device_id": "75eb3e661e401cfa340ffe59e2166e14",
+ "device_id": "aed25af8b1df3f0c6d5139645edcbcbf",
"area_id": null,
"name": null,
"original_name": null,
@@ -643,7 +643,7 @@
},
{
"entity_id": "valve.back_garden",
- "device_id": "735d5d94311e3fbfb8b19135f8cfa3ad",
+ "device_id": "20f9eaf9b4e6069dc0d2f03b763e0468",
"area_id": null,
"name": null,
"original_name": null,
@@ -653,7 +653,7 @@
},
{
"entity_id": "valve.trees",
- "device_id": "00882bfe8abb6239f456c82bb12339b1",
+ "device_id": "9d3c34c4b54a908d257ab46bda5d6535",
"area_id": null,
"name": null,
"original_name": null,
@@ -993,7 +993,7 @@
},
"light.ceiling_lights": {
"entity_id": "light.ceiling_lights",
- "state": "off",
+ "state": "on",
"attributes": {
"min_color_temp_kelvin": 2000,
"max_color_temp_kelvin": 6535,
@@ -1001,12 +1001,22 @@
"color_temp",
"hs"
],
- "color_mode": null,
- "brightness": null,
- "color_temp_kelvin": null,
- "hs_color": null,
- "rgb_color": null,
- "xy_color": null,
+ "color_mode": "color_temp",
+ "brightness": 180,
+ "color_temp_kelvin": 2631,
+ "hs_color": [
+ 28.55,
+ 67.974
+ ],
+ "rgb_color": [
+ 255,
+ 164,
+ 82
+ ],
+ "xy_color": [
+ 0.532,
+ 0.388
+ ],
"friendly_name": "Ceiling Lights",
"supported_features": 0
}
@@ -1179,12 +1189,12 @@
"media_content_type": "movie",
"media_duration": 300,
"media_position": 45,
- "media_position_updated_at": "2026-09-03T03:32:36.600891+00:00",
+ "media_position_updated_at": "2026-09-03T04:03:12.106314+00:00",
"media_title": "♥♥ The Best Fireplace Video (3 hours)",
"app_name": "YouTube",
"sound_mode": "Music",
"shuffle": false,
- "entity_picture": "/api/media_player_proxy/media_player.living_room?token=f9ceafdc316b6c1a4de03bd06ba1e730bec13106f298653d299ae23c203be1e0&cache=bc2ffb49c4f67034",
+ "entity_picture": "/api/media_player_proxy/media_player.living_room?token=2c4574dd49126388c6330aaf45cb5f900d2dd5492523aab6f81b58f2a00d4e15&cache=bc2ffb49c4f67034",
"friendly_name": "Living Room",
"supported_features": 119695
}
@@ -1203,12 +1213,12 @@
"media_content_type": "movie",
"media_duration": 360000,
"media_position": 54000,
- "media_position_updated_at": "2026-09-03T03:32:36.600909+00:00",
+ "media_position_updated_at": "2026-09-03T04:03:12.106325+00:00",
"media_title": "Epic sax guy 10 hours",
"app_name": "YouTube",
"sound_mode": "Music",
"shuffle": false,
- "entity_picture": "/api/media_player_proxy/media_player.bedroom?token=f0db49be001292eded438c2e0e410feeac3be0b64fb29c1ce2a0b9e59fb9bdf0&cache=e4513ed94ec89151",
+ "entity_picture": "/api/media_player_proxy/media_player.bedroom?token=de73bb8b129443c22a73037cb52ce2c994d1336431627ac1d252bd477a7d2f56&cache=e4513ed94ec89151",
"friendly_name": "Bedroom",
"supported_features": 119695
}
@@ -1234,7 +1244,7 @@
"sound_mode": "Music",
"shuffle": false,
"repeat": "off",
- "entity_picture": "/api/media_player_proxy/media_player.walkman?token=5db0375882ed05f83e7934617a37efeef038c8e27f8f75b27ac007c5bb4fa066&cache=62c0c516acbc53a9",
+ "entity_picture": "/api/media_player_proxy/media_player.walkman?token=85cd01caed2dab519d3fe0892a2451fad58f9a746d10adcc82dba96d3cf35091&cache=62c0c516acbc53a9",
"friendly_name": "Walkman",
"supported_features": 914877
}
@@ -1260,7 +1270,7 @@
"sound_mode": "Music",
"shuffle": false,
"repeat": "off",
- "entity_picture": "/api/media_player_proxy/media_player.kitchen?token=8d01951f9793bc4e3dd8c88af1b3ea5d3ca02a6ed7b41e919482c8584d379980&cache=62c0c516acbc53a9",
+ "entity_picture": "/api/media_player_proxy/media_player.kitchen?token=f49e757004e7e08dfe7587d429c4e0ee86b4b7a73d124fe662d19f9db11698e5&cache=62c0c516acbc53a9",
"friendly_name": "Kitchen",
"supported_features": 914877
}
@@ -1291,7 +1301,7 @@
"sound_mode": "Music",
"shuffle": false,
"device_class": "tv",
- "entity_picture": "/api/media_player_proxy/media_player.lounge_room?token=17c84f965e1ce6864da436598edc5086cfe5fb8e555328200d811debbe52987a&cache=cb9d84451faf9351",
+ "entity_picture": "/api/media_player_proxy/media_player.lounge_room?token=2134b5e78085aeeb2fd721f1a99cbc4925a8749084fe6337b7e738828e45044e&cache=cb9d84451faf9351",
"friendly_name": "Lounge room",
"supported_features": 121265
}
@@ -1413,7 +1423,7 @@
},
"scene.bedtime": {
"entity_id": "scene.bedtime",
- "state": "2026-09-03T03:50:51.101424+00:00",
+ "state": "unknown",
"attributes": {
"entity_id": [
"light.bed_light",
diff --git a/packages/home-bridge/tests/home-bridge.test.js b/packages/home-bridge/tests/home-bridge.test.js
index a1d0080c7..3635df25d 100644
--- a/packages/home-bridge/tests/home-bridge.test.js
+++ b/packages/home-bridge/tests/home-bridge.test.js
@@ -100,7 +100,7 @@ describe('room graph', () => {
expect(living.secured).not.toBeNull();
expect(living.secured.secure).toBe(living.secured.unlocked.length === 0 && living.secured.open.length === 0);
// A room with nothing to secure reports null rather than a false "secure".
- expect(graph.rooms.find((r) => r.name === 'Kitchen').secured).toBeNull();
+ expect(graph.rooms.find((r) => r.name === 'Bedroom').secured).toBeNull();
});
it('survives an empty house without throwing', () => {
diff --git a/scripts/check-home-voice.mjs b/scripts/check-home-voice.mjs
index e8bbe8832..fe51b1305 100644
--- a/scripts/check-home-voice.mjs
+++ b/scripts/check-home-voice.mjs
@@ -231,16 +231,26 @@ async function launch(audioPath, { loopAudio = true } = {}) {
const requests = [];
page.on('request', (r) => requests.push({ url: r.url(), at: Date.now() }));
const consoleErrors = [];
- // The dev server's own HMR socket cannot reach a Codespace-forwarded origin,
- // which is noise from the harness rather than from the page under test.
- const isDevNoise = (text) => /\[vite\]|WebSocket|hmr/i.test(text);
+ const failedResponses = [];
+ // Noise from the harness and from the platform chrome, neither of which is the
+ // page under test: the dev server's HMR socket cannot reach a
+ // Codespace-forwarded origin, and the site nav requests /api/notifications
+ // optimistically on every page, which answers 401 for a signed-out visitor.
+ const isDevNoise = (text) => /\[vite\]|WebSocket|hmr|\/api\/notifications/i.test(text);
page.on('console', (m) => {
- if (m.type() === 'error' && !isDevNoise(m.text())) consoleErrors.push(m.text());
+ if (m.type() === 'error' && !isDevNoise(m.text())) {
+ consoleErrors.push(`${m.text()} @ ${m.location()?.url || 'unknown'}`);
+ }
+ });
+ page.on('response', (r) => {
+ if (r.status() >= 400 && !r.url().includes('/@vite/') && !r.url().includes('/api/notifications')) {
+ failedResponses.push(`${r.status()} ${r.url().replace(BASE, '')}`);
+ }
});
page.on('pageerror', (e) => {
if (!isDevNoise(String(e))) consoleErrors.push(String(e));
});
- return { browser, context, page, requests, consoleErrors };
+ return { browser, context, page, requests, consoleErrors, failedResponses };
}
/** Mirror the loop's own event stream into the page so the script can await it. */
@@ -308,7 +318,7 @@ const legs = (page) => page.evaluate(() => window.homeVoice.loop.latencySummary(
// ── scenarios ───────────────────────────────────────────────────────────────
async function scenarioColdLoad() {
- const { browser, page, requests, consoleErrors } = await launch(null);
+ const { browser, page, requests, consoleErrors, failedResponses } = await launch(null);
try {
await bootPage(page);
await page.waitForTimeout(3000);
@@ -334,7 +344,10 @@ async function scenarioColdLoad() {
count: afterOptIn.length,
sample: afterOptIn.slice(0, 3).map((r) => r.url.replace(BASE, '')),
});
- check('no console errors on the voice surface', consoleErrors.length === 0, { errors: consoleErrors.slice(0, 4) });
+ check('no console errors on the voice surface', consoleErrors.length === 0, {
+ errors: consoleErrors.slice(0, 4),
+ failedResponses: failedResponses.slice(0, 6),
+ });
} finally {
await browser.close();
}
@@ -388,12 +401,14 @@ async function scenarioBargeIn() {
'the front door is locked, and the garage is closed. Nothing else has changed since this morning.',
);
});
- await page
- .waitForFunction(
- () => window.homeVoice.loop.state === 'speaking' || window.__hv.events.some((e) => e.type === 'tts-failed'),
- null,
- { timeout: 45000 },
- );
+ // Wait for sound actually leaving the speaker, not merely for the state
+ // flip: _speak enters `speaking` before the synthesis request returns, so a
+ // failed TTS call would otherwise read as a silent, un-interruptible agent.
+ await page.waitForFunction(
+ () => !!window.homeVoice.loop._playback || window.__hv.events.some((e) => e.type === 'tts-failed'),
+ null,
+ { timeout: 60000 },
+ );
const ttsFailure = (await events(page)).find((e) => e.type === 'tts-failed');
if (ttsFailure) throw new Error(`the agent could not speak, so barge-in cannot be measured: ${ttsFailure.message}`);
await waitForEvent(page, 'barge-in', 45000);
@@ -621,7 +636,7 @@ async function scenarioStateGallery() {
check('the state gallery renders every one of the twelve states', count === 12, { count });
for (let i = 0; i < count; i++) {
const section = sections.nth(i);
- const name = (await section.locator('h3').textContent()).trim();
+ const name = (await section.locator('> h3').textContent()).trim();
await section.screenshot({ path: join(OUT, `state-${String(i + 1).padStart(2, '0')}-${name}.png`) });
}
await page.screenshot({ path: join(OUT, 'page-full.png'), fullPage: true });
diff --git a/scripts/home-test-instance.mjs b/scripts/home-test-instance.mjs
index 576724fab..8f0861591 100755
--- a/scripts/home-test-instance.mjs
+++ b/scripts/home-test-instance.mjs
@@ -335,21 +335,40 @@ async function seed(inst, state, { alreadyInConfig }) {
const floor = await ensureFloor(ws, 'Ground Floor');
created.floors = floor.created ? 1 : 0;
+ // Only entities that reached the ENTITY REGISTRY can hold an area, and the
+ // demo's locks never do: they carry no unique_id, so they exist as states
+ // and nothing more. Plan the rooms from the registry and let the states
+ // answer for everything else, rather than assigning an area to an entity
+ // that cannot have one and counting it as furnished.
+ const registry = await ws.send({ type: 'config/entity_registry/list' }).catch(() => []);
const states = await ws.send({ type: 'get_states' });
+ const registered = (domain) => registry.filter((e) => e.entity_id.startsWith(`${domain}.`)).map((e) => e.entity_id);
const byDomain = (domain) => states.filter((s) => s.entity_id.startsWith(`${domain}.`)).map((s) => s.entity_id);
- const lights = byDomain('light');
+
+ const lights = registered('light');
+ const climate = registered('climate');
+ const covers = registered('cover');
+ const fans = registered('fan');
+ const switches = registered('switch');
+ const doorSensors = registered('binary_sensor');
const locks = byDomain('lock');
- const climate = byDomain('climate');
- // Three real rooms with real entities in them, which is the minimum the
- // room graph, the 3D scene and the per-room rollups all need to mean
- // anything. Entities are taken from whatever the demo actually provides
- // rather than hardcoded, so a demo-integration change does not break this.
+ // A furnished house, not a demo of one. Every room gets light, and the
+ // rooms that should have something to secure get a cover or a door
+ // sensor, because a room graph whose security rollup is null everywhere
+ // proves nothing about the rollup. Entities come from whatever this
+ // release's demo actually registers, so a demo change shows up as fewer
+ // assignments rather than as a broken seed.
const plan = [
- { name: 'Living Room', entities: [lights[0], climate[0]].filter(Boolean) },
- { name: 'Bedroom', entities: [lights[1]].filter(Boolean) },
- { name: 'Front Door', entities: [locks[0], lights[2]].filter(Boolean) },
- ];
+ { name: 'Living Room', entities: [lights[0], climate[0], covers[0], switches[0]] },
+ { name: 'Kitchen', entities: [lights[1], covers[1], fans[0], doorSensors[0]] },
+ // The bedroom is deliberately left with nothing securable in it. A house
+ // where every room has a door is a house that cannot tell a real
+ // "nothing to secure here" apart from a false "all secure", and the
+ // room graph draws that distinction on purpose.
+ { name: 'Bedroom', entities: [lights[2], climate[1], fans[1]] },
+ { name: 'Front Door', entities: [lights[3], covers[2], doorSensors[1]] },
+ ].map((room) => ({ ...room, entities: room.entities.filter(Boolean) }));
for (const room of plan) {
const area = await ensureArea(ws, room.name, floor.floor_id);
diff --git a/src/home/connect.js b/src/home/connect.js
index f2829c53b..05023eaec 100644
--- a/src/home/connect.js
+++ b/src/home/connect.js
@@ -51,6 +51,13 @@ export const STATE = Object.freeze({
* answer to "you have run out of homes".
*/
QUOTA_REACHED: 'quota_reached',
+ /**
+ * Not a failure of the flow above: the other half of it. Most Home Assistant
+ * installs have no address three.ws could ever dial, so for those the house
+ * dials out to us through a small integration. src/home/pair.js owns the
+ * seven states inside this one.
+ */
+ PAIRING: 'pairing',
});
/** Where Home Assistant hides the token minting screen. Never make anyone hunt. */
@@ -101,6 +108,7 @@ function render(state, data = {}) {
case STATE.UNREACHABLE: return root.append(connectCard(data));
case STATE.REVOKED: return root.append(connectCard(data));
case STATE.QUOTA_REACHED: return root.append(quotaCard(data));
+ case STATE.PAIRING: return root.append(pairingHost(data));
case STATE.CONNECTED:
case STATE.DEGRADED:
case STATE.MANY:
@@ -305,6 +313,36 @@ function verifying({ steps = [], onCancel } = {}) {
return panel;
}
+/**
+ * The pairing flow lives in its own module and manages its own states; this is
+ * only the seam that hands it a container and takes the user back when they
+ * decide their house has a web address after all.
+ */
+function pairingHost() {
+ const host = el('div', 'hm-pairhost');
+ // Deferred so the pairing module (and the polling it starts) is not in the
+ // bundle for the many visitors who never open this path.
+ import('./pair.js').then(({ renderPairing }) => {
+ activePairing?.destroy();
+ activePairing = renderPairing({
+ mount: host,
+ onCancel: () => {
+ activePairing?.destroy();
+ activePairing = null;
+ render(STATE.EMPTY);
+ },
+ onLinked: () => {
+ // The home is real from here on, so the list is what should own it.
+ listHomes().then((homes) => homes && renderHomes(homes)).catch(() => null);
+ },
+ });
+ });
+ return host;
+}
+
+/** One pairing flow at a time; leaving the state stops its polling. */
+let activePairing = null;
+
// ── Submit ──────────────────────────────────────────────────────────────────
async function submitConnect({ form, label, url, token, submit }) {
@@ -483,8 +521,9 @@ export function checkReachable(input) {
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.',
+ 'Or let your house dial out to three.ws instead, with the button below. One small integration inside Home Assistant, no port forwarded, and no Home Assistant token stored here at all.',
],
+ action: { label: 'Connect a home that is only on my network', onClick: () => render(STATE.PAIRING) },
},
};
}
@@ -614,7 +653,7 @@ export function clear(node) {
while (node.firstChild) node.removeChild(node.firstChild);
}
-export function noticeEl({ tone = 'info', title, body, bullets } = {}) {
+export function noticeEl({ tone = 'info', title, body, bullets, action } = {}) {
const wrap = el('div', `hm-notice hm-notice-${tone}`);
wrap.setAttribute('role', tone === 'error' ? 'alert' : 'status');
@@ -637,6 +676,15 @@ export function noticeEl({ tone = 'info', title, body, bullets } = {}) {
for (const line of bullets) ul.append(el('li', '', line));
content.append(ul);
}
+ // An explanation that names a way out should carry the way out. Telling
+ // somebody their house is unreachable and then leaving them to find the fix
+ // on their own is the difference between a diagnosis and a product.
+ if (action?.label && typeof action.onClick === 'function') {
+ const button = el('button', 'hm-btn hm-btn-primary hm-notice-action', action.label);
+ button.type = 'button';
+ button.addEventListener('click', action.onClick);
+ content.append(button);
+ }
wrap.append(icon, content);
return wrap;
}
diff --git a/src/home/home.css b/src/home/home.css
index 6320c61ae..9053d3bfe 100644
--- a/src/home/home.css
+++ b/src/home/home.css
@@ -361,6 +361,69 @@
/* ── Responsive ──────────────────────────────────────────────────────────── */
+/* ── Pairing a home that only exists on a LAN (src/home/pair.js) ─────────────
+ The code is the whole screen for a minute or two, so it is set at display
+ scale and spaced like something meant to be read off a monitor and typed on
+ a phone. Everything else on this panel is instructions, and instructions
+ read better small. */
+
+.hm-pairhost { display: block; }
+
+.hm-paircode {
+ display: flex; align-items: center; justify-content: space-between;
+ gap: var(--space-md); flex-wrap: wrap;
+ margin: var(--space-md) 0 0.6rem;
+ padding: 1rem 1.15rem;
+ border: 1px solid var(--hm-line);
+ border-radius: var(--radius-lg);
+ background: var(--hm-panel-2);
+}
+
+.hm-paircode-value {
+ font-family: var(--font-mono);
+ font-size: clamp(1.6rem, 6vw, 2.4rem);
+ font-weight: var(--weight-bold);
+ /* A pairing code is read one character at a time, so it gets the tracking a
+ licence key gets rather than the tracking prose gets. */
+ letter-spacing: 0.14em;
+ line-height: 1.1;
+ /* Selectable in one gesture for anyone who would rather select than press
+ the copy button, including a screen reader user on a touch device. */
+ user-select: all;
+ word-break: break-all;
+}
+
+.hm-paircode-copy { flex: 0 0 auto; }
+
+.hm-notice-action { margin-top: 0.7rem; }
+
+.hm-details { margin-top: var(--space-md); }
+.hm-details summary { cursor: pointer; font-size: var(--text-md); }
+.hm-details summary:focus-visible { outline: 2px solid var(--hm-focus); outline-offset: 3px; border-radius: var(--radius-sm); }
+.hm-details[open] summary { margin-bottom: 0.4rem; }
+
+/* "Waiting for your home to connect", with a pulse that means a real poll is
+ running. It stops when the poll stops, so it never animates over a dead
+ screen. */
+.hm-live {
+ display: inline-flex; align-items: center; gap: 0.5rem;
+ margin: 0.2rem 0 0; color: var(--hm-ink-2); font-size: var(--text-md);
+}
+.hm-live::before {
+ content: ''; width: 7px; height: 7px; border-radius: 50%;
+ background: var(--hm-live); box-shadow: 0 0 8px var(--hm-live);
+ animation: hm-pulse 1.6s ease-in-out infinite;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .hm-live::before { animation: none; }
+}
+
+@media (max-width: 480px) {
+ .hm-paircode { justify-content: center; text-align: center; }
+ .hm-paircode-copy { width: 100%; }
+}
+
@media (max-width: 640px) {
.hm-card { grid-template-columns: minmax(0, 1fr); }
.hm-card-actions { justify-content: flex-start; flex-wrap: wrap; }
diff --git a/src/home/pair.js b/src/home/pair.js
new file mode 100644
index 000000000..71b6bdd4b
--- /dev/null
+++ b/src/home/pair.js
@@ -0,0 +1,436 @@
+/**
+ * Connecting a home that only exists on your network.
+ *
+ * The rest of /smart-home assumes a house three.ws can dial. Most cannot be
+ * dialled at all: they live on a LAN behind a router, and no amount of waiting
+ * changes that. For those, the house dials us. This module is the whole of that
+ * flow on the browser side, and it is the reach multiplier for the entire
+ * feature, so every state it can be in is drawn rather than implied.
+ *
+ * The seven states, each with its own treatment:
+ *
+ * 1. NOT_INSTALLED the two ways to install the integration, HACS and manual
+ * 2. PAIRING the code, and a countdown that is honest about the clock
+ * 3. LINKED the house dialled in; from here it is an ordinary home
+ * 4. AGENT_OFFLINE the integration is not running, and it recovers by itself
+ * 5. TOO_OLD the integration is behind the relay protocol
+ * 6. CODE_DEAD the code expired or was already used, with one button back
+ * 7. REVOKED disconnected from either end
+ *
+ * The countdown is deliberately not a fake progress bar: it counts a real
+ * expiry the server minted, and when it reaches zero the code really is dead,
+ * so the UI moves to state 6 rather than pretending.
+ */
+
+import { HomeApiError, pairingStatus, refreshPairing, startPairing } from './api.js';
+import { clear, el, noticeEl } from './connect.js';
+
+/** The states this flow can be in. Nothing falls through to a default. */
+export const PAIR_STATE = Object.freeze({
+ NOT_INSTALLED: 'not_installed',
+ PAIRING: 'pairing',
+ LINKED: 'linked',
+ AGENT_OFFLINE: 'agent_offline',
+ TOO_OLD: 'too_old',
+ CODE_DEAD: 'code_dead',
+ REVOKED: 'revoked',
+ UNAVAILABLE: 'unavailable',
+});
+
+const HACS_REPO = 'https://github.com/nirholas/three-ws-home-assistant';
+const ADD_PATH = 'Settings, Devices and services, Add integration, three.ws';
+
+/** How often the page asks whether the house has arrived. */
+const POLL_MS = 3000;
+
+/**
+ * Mount the pairing flow into a container.
+ *
+ * @param {object} options
+ * @param {HTMLElement} options.mount
+ * @param {() => void} [options.onCancel] back to the dial-a-URL card
+ * @param {(home: object) => void} [options.onLinked] the house arrived
+ * @returns {{ destroy: () => void }}
+ */
+export function renderPairing({ mount, onCancel, onLinked } = {}) {
+ let timer = null;
+ let tick = null;
+ let destroyed = false;
+ let current = null;
+
+ const stop = () => {
+ if (timer) clearTimeout(timer);
+ if (tick) clearInterval(tick);
+ timer = null;
+ tick = null;
+ };
+
+ const destroy = () => {
+ destroyed = true;
+ stop();
+ };
+
+ function show(state, data = {}) {
+ if (destroyed) return;
+ stop();
+ clear(mount);
+ mount.append(panelFor(state, data));
+ }
+
+ function panelFor(state, data) {
+ switch (state) {
+ case PAIR_STATE.NOT_INSTALLED:
+ return installPanel(data);
+ case PAIR_STATE.PAIRING:
+ return pairingPanel(data);
+ case PAIR_STATE.LINKED:
+ return linkedPanel(data);
+ case PAIR_STATE.AGENT_OFFLINE:
+ return offlinePanel(data);
+ case PAIR_STATE.TOO_OLD:
+ return tooOldPanel(data);
+ case PAIR_STATE.CODE_DEAD:
+ return codeDeadPanel(data);
+ case PAIR_STATE.REVOKED:
+ return revokedPanel(data);
+ default:
+ return unavailablePanel(data);
+ }
+ }
+
+ // ── State 1: the integration is not installed yet ──────────────────────────
+
+ function installPanel({ notice } = {}) {
+ const panel = el('section', 'hm-panel');
+ panel.append(
+ el('p', 'hm-eyebrow', 'For a home that is only on your network'),
+ el('h2', 'hm-panel-title', 'Your house connects to three.ws, not the other way round'),
+ el(
+ 'p',
+ 'hm-panel-sub',
+ 'Install one small integration inside Home Assistant. It opens a single outgoing connection to three.ws and keeps it. Nothing listens on your network, no port is forwarded, and three.ws never receives a Home Assistant token.',
+ ),
+ );
+ if (notice) panel.append(noticeEl(notice));
+
+ panel.append(el('h3', 'hm-label', 'Through HACS, the usual way'));
+ const hacs = el('ol', 'hm-ol');
+ for (const line of [
+ 'In Home Assistant, open HACS.',
+ 'Custom repositories, add this address, category Integration.',
+ 'Install three.ws, then restart Home Assistant.',
+ `Then ${ADD_PATH}.`,
+ ]) hacs.append(el('li', '', line));
+ panel.append(hacs, repoLine());
+
+ const details = el('details', 'hm-details');
+ details.append(el('summary', 'hm-link', 'Or install it by hand'));
+ const manual = el('ol', 'hm-ol');
+ for (const line of [
+ 'Download the latest release from the repository above.',
+ 'Copy custom_components/three_ws into your Home Assistant config folder.',
+ 'Restart Home Assistant.',
+ `Then ${ADD_PATH}.`,
+ ]) manual.append(el('li', '', line));
+ details.append(manual);
+ panel.append(details);
+
+ const actions = el('div', 'hm-actions');
+ const go = el('button', 'hm-btn hm-btn-primary', 'I have it installed, show me a code');
+ go.type = 'button';
+ go.addEventListener('click', () => begin());
+ actions.append(go);
+ if (onCancel) {
+ const back = el('button', 'hm-btn hm-btn-ghost', 'My home has a web address instead');
+ back.type = 'button';
+ back.addEventListener('click', () => {
+ destroy();
+ onCancel();
+ });
+ actions.append(back);
+ }
+ panel.append(actions);
+ return panel;
+ }
+
+ function repoLine() {
+ const wrap = el('p', 'hm-hint');
+ const link = el('a', 'hm-link hm-mono', HACS_REPO);
+ link.href = HACS_REPO;
+ link.rel = 'noopener';
+ link.target = '_blank';
+ wrap.append(link);
+ return wrap;
+ }
+
+ // ── State 2: the code, and a real countdown ────────────────────────────────
+
+ function pairingPanel({ home, code, expiresAt }) {
+ const panel = el('section', 'hm-panel');
+ panel.append(
+ el('p', 'hm-eyebrow', 'Step 2 of 2'),
+ el('h2', 'hm-panel-title', 'Type this code into Home Assistant'),
+ el('p', 'hm-panel-sub', `In Home Assistant: ${ADD_PATH}. Paste the code there.`),
+ );
+
+ const codeBox = el('div', 'hm-paircode');
+ codeBox.setAttribute('role', 'group');
+ codeBox.setAttribute('aria-label', 'Your pairing code');
+ const value = el('output', 'hm-paircode-value', code);
+ value.setAttribute('aria-live', 'polite');
+ codeBox.append(value);
+
+ const copy = el('button', 'hm-btn hm-btn-ghost hm-paircode-copy', 'Copy');
+ copy.type = 'button';
+ copy.addEventListener('click', async () => {
+ try {
+ await navigator.clipboard.writeText(code);
+ copy.textContent = 'Copied';
+ setTimeout(() => {
+ copy.textContent = 'Copy';
+ }, 1600);
+ } catch {
+ // A browser that refuses the clipboard is not an error state: the
+ // code is on screen and can be typed, which is the normal path.
+ copy.textContent = 'Select it above';
+ }
+ });
+ codeBox.append(copy);
+ panel.append(codeBox);
+
+ const countdown = el('p', 'hm-hint');
+ countdown.setAttribute('aria-live', 'polite');
+ panel.append(countdown);
+
+ const waiting = el('p', 'hm-live', 'Waiting for your home to connect');
+ panel.append(waiting);
+
+ const actions = el('div', 'hm-actions');
+ const cancel = el('button', 'hm-btn hm-btn-ghost', 'Back');
+ cancel.type = 'button';
+ cancel.addEventListener('click', () => show(PAIR_STATE.NOT_INSTALLED));
+ actions.append(cancel);
+ panel.append(actions);
+
+ const deadline = new Date(expiresAt).getTime();
+ const paint = () => {
+ const left = Math.max(0, deadline - Date.now());
+ if (left === 0) {
+ stop();
+ show(PAIR_STATE.CODE_DEAD, { home, reason: 'expired' });
+ return;
+ }
+ const seconds = Math.round(left / 1000);
+ countdown.textContent = `This code works once and expires in ${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}.`;
+ };
+ paint();
+ tick = setInterval(paint, 1000);
+ poll(home);
+ return panel;
+ }
+
+ // ── State 3: linked ────────────────────────────────────────────────────────
+
+ function linkedPanel({ home }) {
+ const panel = el('section', 'hm-panel');
+ panel.append(
+ el('h2', 'hm-panel-title', `${home.label} is connected`),
+ el(
+ 'p',
+ 'hm-panel-sub',
+ 'From here it behaves exactly like any other connected home: the same rooms, the same scenes, and the same rule that unlocking, opening and disarming always ask a person first.',
+ ),
+ noticeEl({
+ tone: 'ok',
+ title: 'three.ws holds no key to this house.',
+ body: 'The integration signs in to Home Assistant on your own machine. There is no Home Assistant token stored against your three.ws account for this home, so there is nothing here for a breach to take.',
+ }),
+ );
+ const actions = el('div', 'hm-actions');
+ const go = el('a', 'hm-btn hm-btn-primary', 'Open this home');
+ go.href = `/smart-home/${encodeURIComponent(home.id)}`;
+ actions.append(go);
+ panel.append(actions);
+ if (onLinked) onLinked(home);
+ return panel;
+ }
+
+ // ── State 4: the integration is not running ───────────────────────────────
+
+ function offlinePanel({ home }) {
+ const panel = el('section', 'hm-panel');
+ panel.append(
+ el('h2', 'hm-panel-title', `${home.label} is not answering`),
+ noticeEl({
+ tone: 'warn',
+ title: 'The three.ws integration in this home is offline.',
+ body: 'That normally means Home Assistant is restarting or the machine it runs on is off. Nothing is broken and there is nothing to re-pair: it dials back in on its own within a minute of coming back.',
+ }),
+ );
+ const live = el('p', 'hm-live', 'Watching for it to come back');
+ panel.append(live);
+ const actions = el('div', 'hm-actions');
+ const again = el('button', 'hm-btn hm-btn-ghost', 'Check now');
+ again.type = 'button';
+ again.addEventListener('click', () => poll(home, { immediate: true }));
+ actions.append(again);
+ panel.append(actions);
+ poll(home);
+ return panel;
+ }
+
+ // ── State 5: the integration is too old ───────────────────────────────────
+
+ function tooOldPanel({ home, detail }) {
+ const panel = el('section', 'hm-panel');
+ panel.append(
+ el('h2', 'hm-panel-title', 'This home needs a newer three.ws integration'),
+ noticeEl({
+ tone: 'warn',
+ title: 'The integration installed in this home is older than the relay it is talking to.',
+ body: detail || 'Open HACS in Home Assistant, update three.ws, and restart. Nothing else has to be redone: the pairing survives an update.',
+ }),
+ );
+ panel.append(repoLine());
+ const actions = el('div', 'hm-actions');
+ const again = el('button', 'hm-btn hm-btn-primary', 'I have updated it');
+ again.type = 'button';
+ again.addEventListener('click', () => poll(home, { immediate: true }));
+ actions.append(again);
+ panel.append(actions);
+ return panel;
+ }
+
+ // ── State 6: the code is dead ─────────────────────────────────────────────
+
+ function codeDeadPanel({ home, reason }) {
+ const panel = el('section', 'hm-panel');
+ const wasUsed = reason === 'used';
+ panel.append(
+ el('h2', 'hm-panel-title', wasUsed ? 'That code has already been used' : 'That code expired'),
+ noticeEl({
+ tone: 'warn',
+ title: wasUsed ? 'A pairing code works exactly once.' : 'A pairing code lasts ten minutes.',
+ body: 'That is deliberate: a short code that lived forever would be a permanent way into your house. Get a new one and it goes straight back to the same home, not a second one.',
+ }),
+ );
+ const actions = el('div', 'hm-actions');
+ const again = el('button', 'hm-btn hm-btn-primary', 'Get a new code');
+ again.type = 'button';
+ again.addEventListener('click', () => begin({ homeId: home?.id }));
+ actions.append(again);
+ panel.append(actions);
+ return panel;
+ }
+
+ // ── State 7: revoked ──────────────────────────────────────────────────────
+
+ function revokedPanel({ home }) {
+ const panel = el('section', 'hm-panel');
+ panel.append(
+ el('h2', 'hm-panel-title', 'This home was disconnected'),
+ noticeEl({
+ tone: 'info',
+ title: 'The link is gone from both ends.',
+ body: 'three.ws dropped the connection its side, and the integration in your house can no longer dial in. To connect again, remove the three.ws integration in Home Assistant and pair a new code here.',
+ }),
+ );
+ const actions = el('div', 'hm-actions');
+ const again = el('button', 'hm-btn hm-btn-primary', 'Connect a home again');
+ again.type = 'button';
+ again.addEventListener('click', () => show(PAIR_STATE.NOT_INSTALLED));
+ actions.append(again);
+ panel.append(actions);
+ return panel;
+ }
+
+ /** This deployment has no relay at all, which is a real answer, not a crash. */
+ function unavailablePanel({ detail } = {}) {
+ const panel = el('section', 'hm-panel');
+ panel.append(
+ el('h2', 'hm-panel-title', 'This is not available here yet'),
+ noticeEl({
+ tone: 'info',
+ title: 'This three.ws does not run a home relay.',
+ body: detail || 'A home with a remote https address still connects normally. Use the other option on this page.',
+ }),
+ );
+ if (onCancel) {
+ const actions = el('div', 'hm-actions');
+ const back = el('button', 'hm-btn hm-btn-primary', 'Use a web address instead');
+ back.type = 'button';
+ back.addEventListener('click', () => {
+ destroy();
+ onCancel();
+ });
+ actions.append(back);
+ panel.append(actions);
+ }
+ return panel;
+ }
+
+ // ── The two network paths ─────────────────────────────────────────────────
+
+ async function begin({ homeId } = {}) {
+ clear(mount);
+ mount.append(el('p', 'hm-live', 'Minting a pairing code'));
+ try {
+ const result = homeId ? await refreshPairing(homeId) : await startPairing({ label: '' });
+ const home = result.home || { id: homeId || result.homeId };
+ show(PAIR_STATE.PAIRING, { home, code: result.code, expiresAt: result.expiresAt });
+ } catch (err) {
+ if (err instanceof HomeApiError && (err.code === 'not_connected' || err.status === 503)) {
+ return show(PAIR_STATE.UNAVAILABLE, { detail: err.message });
+ }
+ show(PAIR_STATE.NOT_INSTALLED, { notice: { tone: 'error', title: 'We could not start pairing.', body: err?.message || 'Try again in a moment.' } });
+ }
+ }
+
+ /**
+ * Ask whether the house has arrived. Polling rather than a socket on purpose:
+ * this runs for a couple of minutes at most, once, and a second live channel
+ * for it would be more moving parts than the whole flow is worth.
+ */
+ async function poll(home, { immediate = false } = {}) {
+ if (destroyed || !home?.id) return;
+ if (timer) clearTimeout(timer);
+ const run = async () => {
+ if (destroyed) return;
+ try {
+ const status = await pairingStatus(home.id);
+ const row = status.home || home;
+ if (row.status === 'revoked' || row.revoked_at) return show(PAIR_STATE.REVOKED, { home: row });
+ if (status.relay?.online) {
+ if (current !== PAIR_STATE.LINKED) {
+ current = PAIR_STATE.LINKED;
+ return show(PAIR_STATE.LINKED, { home: row });
+ }
+ return;
+ }
+ if (status.pairing && !status.pairing.expired) {
+ // Still waiting on the code. The countdown panel is already up.
+ timer = setTimeout(run, POLL_MS);
+ return;
+ }
+ if (current === PAIR_STATE.LINKED || row.status === 'connected' || row.last_ok_at) {
+ // It was linked and is not answering now: state 4, not state 6.
+ if (current !== PAIR_STATE.AGENT_OFFLINE) {
+ current = PAIR_STATE.AGENT_OFFLINE;
+ return show(PAIR_STATE.AGENT_OFFLINE, { home: row });
+ }
+ timer = setTimeout(run, POLL_MS * 3);
+ return;
+ }
+ return show(PAIR_STATE.CODE_DEAD, { home: row, reason: 'expired' });
+ } catch (err) {
+ if (err instanceof HomeApiError && err.status === 404) return show(PAIR_STATE.REVOKED, { home });
+ timer = setTimeout(run, POLL_MS * 2);
+ }
+ };
+ timer = setTimeout(run, immediate ? 0 : POLL_MS);
+ }
+
+ // A home already in flight resumes where it was; otherwise start at step 1.
+ show(PAIR_STATE.NOT_INSTALLED);
+ return { destroy, showState: show };
+}
diff --git a/src/home/plan.css b/src/home/plan.css
index 4e47685f9..c2b6b3605 100644
--- a/src/home/plan.css
+++ b/src/home/plan.css
@@ -90,6 +90,11 @@
transition: width 320ms cubic-bezier(0.22, 1, 0.36, 1), background-color 200ms ease;
}
+/* A ceiling that is simply set, rather than a quota being consumed. Neutral on
+ purpose: retention sitting at the plan's maximum is the default, not a
+ warning, and colouring it like one teaches people to ignore the colour. */
+.hm-quota-fill.is-ceiling { background: var(--hm-line-strong); }
+
.hm-quota-why {
margin: 0;
font-size: 0.82rem;
diff --git a/src/home/plan.js b/src/home/plan.js
index 30bf5943c..6d890b604 100644
--- a/src/home/plan.js
+++ b/src/home/plan.js
@@ -121,14 +121,19 @@ function quotaPanel(plan) {
function quotaRow(d) {
const row = el('div', 'hm-quota');
- // At the ceiling and past it read the same, because they mean the same thing
- // to the person looking: the next one is refused.
- if (d.exceeded || (!d.unlimited && d.percent >= 100)) row.classList.add('is-over');
- else if (!d.unlimited && d.percent >= WARN_AT) row.classList.add('is-warn');
+ // A ceiling dimension is never "running out": retention sitting at the plan's
+ // maximum is the healthy default state, not a warning. Only consumable
+ // dimensions change colour.
+ if (!d.ceilingOnly) {
+ // At the ceiling and past it read the same, because they mean the same
+ // thing to the person looking: the next one is refused.
+ if (d.exceeded || (!d.unlimited && d.percent >= 100)) row.classList.add('is-over');
+ else if (!d.unlimited && d.percent >= WARN_AT) row.classList.add('is-warn');
+ }
const head = el('div', 'hm-quota-head');
head.append(el('span', 'hm-quota-label', d.label));
- head.append(el('span', 'hm-quota-count', d.unlimited ? `${formatNumber(d.used)} used · unlimited` : `${formatNumber(d.used)} of ${formatNumber(d.limit)}`));
+ head.append(el('span', 'hm-quota-count', countLabel(d)));
row.append(head);
const track = el('div', 'hm-quota-track');
@@ -141,6 +146,7 @@ function quotaRow(d) {
// A floor of 2% so a single unit out of a thousand is still visible, but only
// once there IS one: a stub of colour on an untouched quota reads as usage.
fill.style.width = d.unlimited || d.used === 0 ? '0%' : `${Math.max(2, d.percent)}%`;
+ if (d.ceilingOnly) fill.classList.add('is-ceiling');
track.append(fill);
row.append(track);
@@ -308,6 +314,22 @@ function renderFailure(err) {
// ── Formatting ───────────────────────────────────────────────────────────────
+/**
+ * "847 of 1,000" for something you consume, "90 days, up to 90" for a ceiling.
+ * A ceiling read as a consumable is how a healthy default comes to look like a
+ * problem.
+ */
+function countLabel(d) {
+ if (d.unlimited) return d.ceilingOnly ? `${formatNumber(d.used)} ${plural(d.unit, d.used)} · no limit` : `${formatNumber(d.used)} used · unlimited`;
+ if (d.ceilingOnly) return `${formatNumber(d.used)} ${plural(d.unit, d.used)} · up to ${formatNumber(d.limit)}`;
+ return `${formatNumber(d.used)} of ${formatNumber(d.limit)}`;
+}
+
+function plural(unit, n) {
+ if (n === 1) return unit;
+ return /s$/.test(unit) ? unit : `${unit}s`;
+}
+
function labelFor(plan, dimensionId) {
return plan.dimensions.find((d) => d.id === dimensionId)?.label || dimensionId;
}
diff --git a/tests/e2e/home-connect.spec.js b/tests/e2e/home-connect.spec.js
index cc9dcabc9..e09b1d98c 100644
--- a/tests/e2e/home-connect.spec.js
+++ b/tests/e2e/home-connect.spec.js
@@ -242,6 +242,44 @@ test.describe('/smart-home connect flow', () => {
expect(await page.evaluate(() => window.__xss)).toBeUndefined();
});
+ test('a house that stopped answering goes stale, and keeps its card', async ({ page }) => {
+ // The distinction this asserts is the whole difference between a product
+ // and a demo: when a house stops answering, the last known state stays on
+ // screen marked stale with its age. Emptying the list because the socket
+ // dropped would make a user think their home had been deleted.
+ const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString();
+ await stub(page, { homes: [{ ...HOME, last_ok_at: twoHoursAgo }] });
+ await page.goto(PAGE);
+ await expect(state(page)).toHaveAttribute('data-state', 'connected', { timeout: SLOW });
+
+ // The card is still there, and it says how long ago the house last spoke.
+ await expect(page.locator('.hm-card')).toHaveCount(1);
+ await expect(page.locator('.hm-status')).toContainText(/last answered 2 hours ago/i);
+ await expect(page.locator('.hm-status')).toContainText(/showing the last state we saw/i);
+ await expect(page.locator('.hm-dot-stale')).toBeVisible();
+ // The measured summary survives too: a stale house is not an empty one.
+ await expect(page.getByText('120')).toBeVisible();
+ });
+
+ test('a house answering right now reads as live, not stale', async ({ page }) => {
+ await stub(page, { homes: [{ ...HOME, last_ok_at: new Date().toISOString() }] });
+ await page.goto(PAGE);
+ await expect(state(page)).toHaveAttribute('data-state', 'connected', { timeout: SLOW });
+
+ await expect(page.locator('.hm-status')).toContainText(/live/i);
+ await expect(page.locator('.hm-dot-connected')).toBeVisible();
+ await expect(page.locator('.hm-dot-stale')).toHaveCount(0);
+ });
+
+ test('a rejected stored token explains itself in the list', async ({ page }) => {
+ await stub(page, { homes: [{ ...HOME, status: 'auth_failed', status_detail: 'Home Assistant rejected the stored token.', last_ok_at: null }] });
+ await page.goto(PAGE);
+ await expect(state(page)).toHaveAttribute('data-state', 'connected', { timeout: SLOW });
+
+ await expect(page.locator('.hm-status')).toContainText(/rejected the stored token/i);
+ await expect(page.locator('.hm-dot-auth_failed')).toBeVisible();
+ });
+
test('the token field is a password field with a working reveal toggle', async ({ page }) => {
await stub(page);
await page.goto(PAGE);