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.

test(home): let two home e2e lanes run at once, and prove the zero-area flow

nirholas08cdd82a0df7
diff --git a/docs/home-scene.md b/docs/home-scene.md
index eceea570b..2b0f59a06 100644
--- a/docs/home-scene.md
+++ b/docs/home-scene.md
@@ -239,3 +239,29 @@ The e2e journeys drive a real Home Assistant container: the scene renders the
real house, a real light changed in Home Assistant reaches the rendered scene,
the house survives its connection being killed, a browser with no WebGL can
still operate it, and a burst of twenty real service calls grows nothing.
+
+### Running two lanes at once
+
+Everything the lane keeps on disk is keyed by `HOME_LIVE_NAME`, so a second run
+on the same machine does not walk into the first one:
+
+```bash
+HOME_LIVE_NAME=mylane HOME_E2E_API_PORT=8141 HOME_E2E_WEB_PORT=3071 \
+ HOME_E2E_ROLES=owner \
+ npx playwright test --config playwright.home.config.js tests/e2e/home-floorplan.spec.js
+```
+
+- The Home Assistant container, `.ha-config-e2e-stack.<lane>.json` and
+ `.ha-config-e2e-accounts.<lane>.json` all carry the lane name.
+- `resetHomes` and `openScene` only ever touch homes pointed at **this lane's**
+ Home Assistant, so a concurrent run's house is never deleted underneath it.
+- Each lane needs its **own** account: a plan carries a fixed number of homes,
+ so two lanes sharing one account means the second is refused with "this
+ account is at its home limit" and the only way to make room is to evict the
+ house the other run is using.
+- `HOME_E2E_ROLES` provisions only the accounts a run signs in as. Registration
+ is capped at five per hour per IP, so a spec that only uses the owner should
+ not spend one of those five on a guest.
+- Ports must be free and are never reused: the shared `npm run dev` on :3000
+ proxies `/api` at **production**, so a run that borrowed it would silently
+ test the wrong API.
diff --git a/packages/home-bridge/README.md b/packages/home-bridge/README.md
index 2a10785db..abed27d2a 100644
--- a/packages/home-bridge/README.md
+++ b/packages/home-bridge/README.md
@@ -101,6 +101,23 @@ all reach the same place) and then through fuzzy matching on the scene names. A
matching scene returns `{ ran: false, match: null }` rather than firing the closest thing it
can find. Pass `{ dryRun: true }` to resolve without running.
+### Rooms the house does not have yet
+
+Most real Home Assistant setups have devices everywhere and not one area, so there is nothing to
+draw a room from. Make one and file devices into it, in the user's own registry:
+
+```js
+const area = await bridge.createArea('Kitchen'); // { id: 'kitchen', created: true }
+await bridge.assignEntityArea('light.bed_light', area.id);
+bridge.graph.rooms.find((r) => r.id === area.id); // already carries the light
+```
+
+Both write the user's own Home Assistant, so the room reaches their dashboards, their voice
+assistant and their automations too. Neither is a guarded action: nothing moves and nothing
+opens, and both are reversible in two clicks in their own UI. `createArea` with a name that
+already exists returns that area with `created: false` rather than failing, because the room the
+caller asked for is there either way.
+
## The physical-action gate
**Reads are free. Writes that open the house stop and ask.** The rule is asymmetric on
@@ -214,6 +231,7 @@ apart from "your house is offline".
| Export | What it does |
|---|---|
| `HomeBridge` | One live connection: `connect`, `call`, `activate`, `macros`, `graph`, `states`, `on`, `close` |
+| `HomeBridge` room organisation | `areas`, `createArea`, `assignEntityArea`, `refreshRegistries`: read the rooms, make one, and file a device into it, in the user's own registry |
| `connectHomeMcp` | The optional MCP capability channel, gated |
| `buildHomeGraph` | Registries plus states to the room graph. Pure |
| `flattenEntities` | The room graph to one flat entity list |
diff --git a/src/home/floorplan.js b/src/home/floorplan.js
index 350940606..226e968cd 100644
--- a/src/home/floorplan.js
+++ b/src/home/floorplan.js
@@ -310,7 +310,7 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
if (state.creating) return;
const thenFile = state.naming?.thenFile || null;
state.creating = true;
- state.naming = { error: null, thenFile };
+ state.naming = { error: null, thenFile, value: name };
render();
try {
const res = await createArea(homeId, { name });
@@ -335,10 +335,11 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
// rather than handing back a form and making them find it again.
if (thenFile) await fileEntity(thenFile, area.id);
} catch (err) {
- // The form stays open holding what they typed: a name that was refused
- // is a name to fix, not a reason to start over.
+ // The form stays open holding what they typed, and still remembers the
+ // device it was opened for: a name that was refused is a name to fix,
+ // not a reason to start over and go and find the device again.
state.creating = false;
- state.naming = { error: describeError(err).body };
+ state.naming = { error: describeError(err).body, thenFile, value: name };
render();
}
}
@@ -393,7 +394,7 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
/** Open the new-room form, optionally to hold a device that needs somewhere. */
function openNaming(thenFile = null) {
- state.naming = { error: null, thenFile };
+ state.naming = { error: null, thenFile, value: '' };
state.notice = null;
render();
view.querySelector('.hm-plan-naming input')?.focus();
@@ -425,6 +426,10 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
input.required = true;
input.autocomplete = 'off';
input.placeholder = 'Kitchen';
+ // Survives the re-render a refusal causes, so the name is theirs to fix
+ // rather than to retype.
+ input.value = state.naming.value || '';
+ input.addEventListener('input', () => { state.naming.value = input.value; });
form.append(input);
const actions = el('div', 'hm-plan-naming-actions');
@@ -450,7 +455,7 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
e.preventDefault();
const name = input.value.trim();
if (!name) {
- state.naming = { ...state.naming, error: 'Give the room a name, like Kitchen.' };
+ state.naming = { ...state.naming, error: 'Give the room a name, like Kitchen.', value: input.value };
return render();
}
createRoom(name);
diff --git a/tests/e2e/home-floorplan.spec.js b/tests/e2e/home-floorplan.spec.js
index 82ff61185..3d1655162 100644
--- a/tests/e2e/home-floorplan.spec.js
+++ b/tests/e2e/home-floorplan.spec.js
@@ -316,18 +316,27 @@ test('journey 9e: a house with no areas at all reaches a full floorplan from the
for (const area of leftover) {
await session.send({ type: 'config/area_registry/delete', area_id: area.area_id }).catch(() => {});
}
+ // Home Assistant derives an area id from the name, and usually gives back
+ // the same one. Usually is not good enough to re-file a house on, so the
+ // old id is mapped to whatever id the recreated area actually got.
+ const remap = new Map();
for (const area of originalAreas) {
- await session.send({
+ const made = await session.send({
type: 'config/area_registry/create',
name: area.name,
...(area.floor_id ? { floor_id: area.floor_id } : {}),
- }).catch(() => {});
+ }).catch(() => null);
+ if (made?.area_id) remap.set(area.area_id, made.area_id);
}
for (const device of deviceAreas) {
- await session.send({ type: 'config/device_registry/update', device_id: device.id, area_id: device.areaId }).catch(() => {});
+ const areaId = remap.get(device.areaId);
+ if (!areaId) continue;
+ await session.send({ type: 'config/device_registry/update', device_id: device.id, area_id: areaId }).catch(() => {});
}
for (const entity of entityAreas) {
- await session.send({ type: 'config/entity_registry/update', entity_id: entity.id, area_id: entity.areaId }).catch(() => {});
+ const areaId = remap.get(entity.areaId);
+ if (!areaId) continue;
+ await session.send({ type: 'config/entity_registry/update', entity_id: entity.id, area_id: areaId }).catch(() => {});
}
session.close();
}
diff --git a/tests/e2e/home-global-setup.js b/tests/e2e/home-global-setup.js
index aae26e6bb..b4ce16da0 100644
--- a/tests/e2e/home-global-setup.js
+++ b/tests/e2e/home-global-setup.js
@@ -42,8 +42,27 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '.
*/
export const LANE = process.env.HOME_LIVE_NAME || 'e2e';
export const STACK_FILE = path.join(ROOT, `.ha-config-e2e-stack${LANE === 'e2e' ? '' : `.${LANE}`}.json`);
-/** The reusable QA accounts. Gitignored: real credentials for a real account. */
-const ACCOUNTS_FILE = path.join(ROOT, '.ha-config-e2e-accounts.json');
+/**
+ * The reusable QA accounts, one file per lane.
+ *
+ * Sharing one account across concurrent lanes cannot work: a plan carries a
+ * fixed number of homes (one, on the account tier these are created at), so the
+ * second lane to connect is refused with "this account is at its home limit"
+ * and the only way to make room is to evict the house a peer run is mid-journey
+ * inside. Each lane gets its own account, reused for every later run of that
+ * lane, so the registration cost is paid once and never again.
+ */
+const ACCOUNTS_FILE = path.join(ROOT, `.ha-config-e2e-accounts${LANE === 'e2e' ? '' : `.${LANE}`}.json`);
+
+/**
+ * Which accounts to provision. Registration is capped at five per hour per IP,
+ * so a run that only signs in as the owner should not spend one of five on a
+ * guest it will never use.
+ */
+const ROLES = (process.env.HOME_E2E_ROLES || 'owner,guest')
+ .split(',')
+ .map((role) => role.trim())
+ .filter(Boolean);
export default async function globalSetup(config) {
process.env.HOME_LIVE = process.env.HOME_LIVE || '1';
@@ -59,7 +78,7 @@ export default async function globalSetup(config) {
STACK_FILE,
`${JSON.stringify({ home, accounts, origin, lane: LANE, startedAt: new Date().toISOString() }, null, '\t')}\n`,
);
- console.log(`[home-e2e] accounts ready: ${accounts.owner.username}, ${accounts.guest.username}`);
+ console.log(`[home-e2e] accounts ready: ${ROLES.map((role) => accounts[role]?.username).filter(Boolean).join(', ')}`);
}
/**
@@ -73,7 +92,7 @@ async function ensureAccounts(origin) {
const stored = readJson(ACCOUNTS_FILE) || {};
const accounts = { ...stored };
- for (const role of ['owner', 'guest']) {
+ for (const role of ROLES) {
if (accounts[role] && (await loginWorks(origin, accounts[role]))) continue;
accounts[role] = await register(origin, role);
// Write after EVERY account, not once at the end. Registration is limited
@@ -85,14 +104,37 @@ async function ensureAccounts(origin) {
return accounts;
}
+/**
+ * Whether a stored account still logs in.
+ *
+ * The distinction between "this account is gone" and "the server would not
+ * answer me just now" is worth money here. Registration is capped at five per
+ * hour per IP, and concurrent agents on this box all log in as the same QA
+ * account, so a login can come back 429 or 5xx while the account is perfectly
+ * fine. Treating that as gone re-registers, burns the hour's budget, and the
+ * NEXT run then fails at setup reporting the rate limiter as a product bug.
+ * Only an outright rejection counts as gone.
+ */
async function loginWorks(origin, account) {
- const res = await fetch(`${origin}/api/auth/login`, {
- method: 'POST',
- headers: { 'content-type': 'application/json', origin },
- body: JSON.stringify({ email: account.email, password: account.password }),
- signal: AbortSignal.timeout(30_000),
- }).catch(() => null);
- return Boolean(res?.ok);
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ const res = await fetch(`${origin}/api/auth/login`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', origin },
+ body: JSON.stringify({ email: account.email, password: account.password }),
+ signal: AbortSignal.timeout(30_000),
+ }).catch(() => null);
+
+ if (res?.ok) return true;
+ // 401/403: the credentials really are no good, so re-provision.
+ if (res && res.status !== 429 && res.status < 500) return false;
+ // Anything else is the server being busy or unreachable. Back off and ask
+ // again rather than spending one of five registrations on a guess.
+ await new Promise((resolve) => setTimeout(resolve, 2_000 * (attempt + 1)));
+ }
+ // Still no clear answer after three tries. Keeping the account is the safe
+ // side of this bet: if it really is dead, the journeys fail with a plain 401
+ // that says so, which is cheaper than an hour of rate-limited setups.
+ return true;
}
/**
diff --git a/tests/e2e/home-support.js b/tests/e2e/home-support.js
index 10b7f6058..712bc86d6 100644
--- a/tests/e2e/home-support.js
+++ b/tests/e2e/home-support.js
@@ -125,9 +125,16 @@ export async function connectHome(page, { label = 'The lane house' } = {}) {
// normal case here, opens on the list instead, and the form is behind
// "Connect another". Waiting for the form without that click is how every
// home journey started failing at connect the moment two lanes ran at once.
+ // isVisible() is an instantaneous read, not a wait, and this page renders its
+ // form from a module after domcontentloaded. Asking before that lands sees
+ // neither state, decides it must be the list, and then waits out the whole
+ // test timeout clicking for a button that a zero-home account never shows.
+ // Wait for whichever of the two states this account actually has first.
const url = page.locator('#hm-url');
+ const another = page.getByRole('button', { name: 'Connect another' });
+ await expect(url.or(another).first()).toBeVisible({ timeout: 60_000 });
if (!(await url.isVisible().catch(() => false))) {
- await page.getByRole('button', { name: 'Connect another' }).click();
+ await another.click();
}
await expect(url).toBeVisible({ timeout: 60_000 });
diff --git a/tests/home-layout.test.js b/tests/home-layout.test.js
index 87cb87cc9..da57b467d 100644
--- a/tests/home-layout.test.js
+++ b/tests/home-layout.test.js
@@ -348,9 +348,42 @@ liveHome('the area write-back, against a real Home Assistant', () => {
await bridge.assignEntityArea(unfiled, area.id);
const entry = (bridge.registries.entities || []).find((e) => e.entity_id === unfiled);
expect(entry.area_id).toBe(area.id);
+
+ // Take the room away again. The lane's house is shared by every live test
+ // and reused across runs, so a test that leaves rooms behind quietly
+ // changes the house every later assertion is made against.
+ await bridge.assignEntityArea(unfiled, originalArea);
+ await removeArea(bridge, area.id);
}, 60_000);
it('refuses a nameless room rather than making an unnamed one', async () => {
await expect(bridge.createArea(' ')).rejects.toThrow(/needs a name/i);
});
});
+
+/**
+ * Delete an area straight through Home Assistant's own websocket.
+ *
+ * The bridge deliberately has no delete: making a room is the flow the product
+ * needs, and removing one is a decision that belongs in the user's own Home
+ * Assistant rather than in a library we ship. A test that creates rooms still
+ * has to clean up after itself, so it opens its own socket for the one message.
+ */
+async function removeArea(bridge, areaId) {
+ const socket = new WebSocket(`${haUrl.replace(/^http/, 'ws')}/api/websocket`);
+ try {
+ await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('area delete timed out')), 20_000);
+ socket.onerror = () => { clearTimeout(timer); reject(new Error('websocket failed')); };
+ socket.onmessage = (event) => {
+ const msg = JSON.parse(event.data);
+ if (msg.type === 'auth_required') return socket.send(JSON.stringify({ type: 'auth', access_token: haToken }));
+ if (msg.type === 'auth_ok') return socket.send(JSON.stringify({ id: 1, type: 'config/area_registry/delete', area_id: areaId }));
+ if (msg.type === 'result') { clearTimeout(timer); resolve(); }
+ };
+ });
+ } finally {
+ socket.close();
+ }
+ await bridge.refreshRegistries();
+}