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.

13.8 KB
Raw Blame
/**
 * Shared ground for the home lane's e2e journeys.
 *
 * Fidelity contract, and it is stricter than the rest of tests/e2e: NOTHING in
 * this lane is stubbed. No route interception, no synthetic wallet, no fixture
 * standing in for a device. The page is the real page, the API is the real
 * handler set, the house is a real Home Assistant, and every assertion about a
 * lock reads that lock's state back out of Home Assistant rather than believing
 * a card that says "unlocked". A confirmation dialog that renders perfectly
 * while the deadbolt moves anyway is the exact failure this lane exists to
 * catch, and only Home Assistant can tell us which happened.
 */

import fs from 'node:fs';

import { expect } from '@playwright/test';

import { readState, readStates, waitForState } from '../_helpers/home-instance.js';
import { STACK_FILE } from './home-global-setup.js';

export { readState, readStates, waitForState };

/**
 * One live session per role for this whole run, keyed by role.
 *
 * Process-scoped on purpose: it lives exactly as long as the Playwright run
 * that created it, so nothing leaks between runs and no credential is written
 * to disk.
 */
const SESSIONS = new Map();

/** The stack this run is driving, as global setup left it. */
function stack() {
	if (!fs.existsSync(STACK_FILE)) {
		throw new Error('No home e2e stack: run through playwright.home.config.js, which sets it up.');
	}
	return JSON.parse(fs.readFileSync(STACK_FILE, 'utf8'));
}

/** The house this run is driving. */
export function homeInstance() {
	return stack().home;
}

/**
 * The name of the lane this run is driving, as global setup recorded it.
 *
 * Read from the stack file rather than from the environment on purpose. The
 * lane name decides which container the harness acts on, and a spec that
 * stopped or started the wrong one would be taking a concurrent run's house
 * off the network. The stack file is the one place that name is written down
 * by the process that actually chose it.
 */
export function laneName() {
	return stack().lane || process.env.HOME_LIVE_NAME || 'lane';
}

/**
 * Sign in as one of the two accounts global setup provisioned.
 *
 * Signing in rather than signing up on every journey is not a shortcut: account
 * creation is rate limited to five per hour per IP, so a suite that registered
 * per journey would pass once and then spend an hour reporting the rate limiter
 * as a product failure. The accounts are real, made through the real signup
 * page, and this is the real login endpoint.
 *
 * @param {import('@playwright/test').Page} page
 * @param {'owner'|'guest'} role
 */
export async function signIn(page, role = 'owner') {
	const account = stack().accounts[role];
	if (!account) throw new Error(`no ${role} account in the e2e stack`);

	// Reuse the session this run already has, rather than minting another.
	//
	// Playwright gives every test a fresh browser context, so a per-test signIn
	// meant a fresh POST /api/auth/login for each of the 37 calls across this
	// lane's specs. The login limiter is shared by every concurrent agent on this
	// machine and it ESCALATES: measured at retry_after 14s early in a soak and
	// 125s four runs later, at which point runs fail on the sign-in before a
	// single journey step has executed. That is what stopped the ten consecutive
	// runs this order asks for, and no amount of waiting fixes it, because the
	// waiting is what provokes it.
	//
	// So the cookie from the first real login is carried into later contexts. The
	// session is still a real one issued by the real endpoint; it is simply not
	// re-issued for no reason. It is verified before use and a stale one falls
	// through to a fresh login, so this can never hand a test a dead session.
	const cached = SESSIONS.get(role);
	if (cached) {
		await page.context().addCookies(cached);
		const alive = await page.request.get('/api/home', { timeout: 60_000 }).catch(() => null);
		if (alive?.ok()) return account;
		SESSIONS.delete(role);
		await page.context().clearCookies();
	}

	// The limiter answers 429 with the seconds to wait. Waiting the interval the
	// server itself named is not retrying a test into passing: no assertion has
	// run yet and the wait is a documented Retry-After. Anything else fails loudly.
	for (let attempt = 0; ; attempt += 1) {
		const res = await page.request.post('/api/auth/login', {
			data: { email: account.email, password: account.password },
			headers: { 'content-type': 'application/json' },
			timeout: 60_000,
		});
		if (res.ok()) {
			SESSIONS.set(role, await page.context().cookies());
			return account;
		}

		const body = await res.text();
		const retryAfter = Number(JSON.parse(body || '{}')?.retry_after) || 0;
		if (res.status() !== 429 || attempt >= 3 || retryAfter <= 0 || retryAfter > 120) {
			throw new Error(`login as ${role} returned ${res.status()}: ${body.slice(0, 200)}`);
		}
		await new Promise((resolve) => setTimeout(resolve, (retryAfter + 1) * 1000));
	}
}

/**
 * A CSRF header, minted the way the real client mints one.
 *
 * Every state-changing route on this surface is CSRF-guarded, and
 * `page.request.post` carries the session cookie WITHOUT the header a browser's
 * fetch would add, so a raw post is refused with `403 csrf_missing` before it
 * reaches the gate the journey is about. That refusal is a 403 like a role
 * refusal is a 403, which is how a test that proves nothing looks green: the
 * guest in journey 7 was being turned away at the door for the wrong reason.
 *
 * So this walks the same path `src/home/api.js` walks: GET /api/csrf-token with
 * the session, then send what it returns. Tokens are single-use, so this is
 * called per request rather than cached.
 *
 * Prefer clicking the real control where one exists. This is for the setup a
 * journey needs before its assertion, and for the requests whose whole point is
 * that they come from a client the UI would never let you be.
 *
 * @param {import('@playwright/test').Page} page
 */
export async function csrfHeaders(page) {
	const res = await page.request.get('/api/csrf-token', { timeout: 60_000 });
	if (!res.ok()) throw new Error(`GET /api/csrf-token returned ${res.status()}`);
	const body = await res.json();
	if (!body?.token) throw new Error('/api/csrf-token returned no token');
	return { 'content-type': 'application/json', 'x-csrf-token': body.token };
}

/** Every home on the signed-in account, however the endpoint shapes its list. */
async function listHomes(page) {
	const list = await page.request.get('/api/home', { timeout: 60_000 });
	if (!list.ok()) return [];
	const body = await list.json().catch(() => null);
	return Array.isArray(body?.homes) ? body.homes : Array.isArray(body) ? body : [];
}

/** The base URL of a listed home, whichever spelling the payload uses. */
function homeBaseUrl(home) {
	return String(home?.baseUrl || home?.base_url || '').replace(/\/+$/, '');
}

/**
 * The homes on this account that point at THIS lane's Home Assistant.
 *
 * Concurrent agents share this worktree and this QA account, and more than one
 * home lane is routinely in flight at once. A helper that treated every home on
 * the account as its own deleted the house a peer run was mid-journey inside,
 * and then opened whichever house won the race, so both runs failed reporting
 * product bugs that were never there. Each lane owns exactly the houses on its
 * own container and leaves the rest alone.
 */
async function laneHomes(page) {
	const mine = homeBaseUrl(homeInstance());
	return (await listHomes(page)).filter((home) => homeBaseUrl(home) === mine);
}

/**
 * Take this lane's homes off the platform.
 *
 * Journeys grant standing permissions on locks, and a grant surviving into the
 * next journey would quietly disarm the gate that journey is trying to prove.
 * Each one therefore starts from an account with no houses of ITS OWN on it;
 * a concurrent lane's houses are none of its business.
 */
/**
 * THIS lane's home, the one the journeys are about.
 *
 * Not `(await listHomes(page))[0]`. That is "the first home on the account",
 * and it is a different thing: a run that recreated its container gets a new
 * port, so the previous run's rows no longer match this lane's base URL, are
 * not cleared by `resetHomes`, and stay at the front of the list. A journey
 * that then acted on `homes[0]` was acting on a home whose stored Home
 * Assistant token was sealed with an earlier run's per-run encryption key, and
 * the API answered `400 auth: the stored access token for this home could not
 * be read` from a route that was working perfectly.
 *
 * @param {import('@playwright/test').Page} page
 */
export async function laneHome(page) {
	const homes = await laneHomes(page);
	if (!homes.length) {
		throw new Error(`no connected home on this lane's house (${homeBaseUrl(homeInstance())})`);
	}
	return homes[0];
}

export async function resetHomes(page) {
	const homes = await laneHomes(page);
	for (const home of homes) {
		await page.request.delete(`/api/home/${home.id}`, { timeout: 60_000 }).catch(() => {});
	}
	return homes.length;
}

/**
 * Connect the seeded house through the real connect form, and wait until the
 * page says it is connected.
 *
 * @returns {Promise<string>} the home id, read from the page's own state
 */
export async function connectHome(page, { label = 'The lane house' } = {}) {
	const home = homeInstance();
	// Two agents running the SAME spec on this shared account would otherwise
	// both connect a house called "Journey nine" and each would then assert on
	// the other's. The lane name is already what separates their containers.
	const lane = stack().lane;
	const scoped = lane && lane !== 'e2e' ? `${label} ${lane}` : label;

	await page.goto('/smart-home', { waitUntil: 'domcontentloaded' });

	// An account with no houses opens on the form itself. One that already has a
	// house, which since resetHomes stopped deleting other lanes' houses is the
	// 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 another.click();
	}
	await expect(url).toBeVisible({ timeout: 60_000 });

	await page.fill('#hm-label', scoped);
	await page.fill('#hm-url', home.baseUrl);
	await page.fill('#hm-token', home.token);
	await page.getByRole('button', { name: 'Connect this home' }).click();

	// The connected state is the one that lists rooms. Waiting for the room list
	// rather than for a spinner to vanish means the assertion is about the house
	// having been read, not about an animation having finished.
	await expect(page.getByText(scoped, { exact: false }).first()).toBeVisible({ timeout: 120_000 });
	return scoped;
}

/**
 * Open the connected house's 3D page, in the 2D view.
 *
 * The 2D view is the one with named buttons. It renders the same model, calls
 * the same action endpoint and hits the same gate as the 3D view, so nothing
 * about what is under test changes; what changes is that a click lands on
 * "Unlock Front Door" instead of on a guessed pixel of a WebGL canvas.
 */
export async function openScene(page) {
	const homes = await laneHomes(page);
	if (!homes.length) {
		throw new Error(`no connected home on this lane's house (${homeBaseUrl(homeInstance())}) to open`);
	}

	await page.goto(`/smart-home/${homes[0].id}`, { waitUntil: 'domcontentloaded' });
	const flat = page.locator('#hs-view-2d');
	await expect(flat).toBeVisible({ timeout: 90_000 });
	await flat.click();
	await expect(flat).toHaveAttribute('aria-pressed', 'true', { timeout: 30_000 });

	// Wait for the house to have been read, not for a spinner to stop: the room
	// rail is only populated once the real registries have arrived.
	await expect(page.locator('#hs-rooms')).not.toHaveAttribute('aria-busy', 'true', { timeout: 120_000 });
	return homes[0].id;
}

/**
 * Every request the page makes, recorded. Journey 10 needs to prove a refusal
 * cost no network call at all, which is a claim about what did NOT happen.
 */
export function recordRequests(page, filter = () => true) {
	const seen = [];
	page.on('request', (req) => {
		if (filter(req)) seen.push(`${req.method()} ${req.url()}`);
	});
	return seen;
}

/** A lock in the house that is currently locked, chosen from the house itself. */
export async function lockedDoor(instance) {
	const states = await readStates(instance);
	const found = states.find((s) => s.entity_id.startsWith('lock.') && s.state === 'locked');
	if (!found) throw new Error('the seeded house has no locked door');
	return found.entity_id;
}

/** A light in the house, chosen from the house itself rather than hardcoded. */
export async function anyLight(instance) {
	const states = await readStates(instance);
	const found = states.find((s) => s.entity_id.startsWith('light.'));
	if (!found) throw new Error('the seeded house has no light');
	return { entityId: found.entity_id, state: found.state, name: found.attributes?.friendly_name };
}

/** Put a lock back the way the journey found it, whatever the journey did. */
export async function relock(instance, entityId) {
	await fetch(`${instance.baseUrl}/api/services/lock/lock`, {
		method: 'POST',
		headers: { authorization: `Bearer ${instance.token}`, 'content-type': 'application/json' },
		body: JSON.stringify({ entity_id: entityId }),
	}).catch(() => {});
	await waitForState(instance, entityId, ['locked', 'locking'], { timeout: 25_000 }).catch(() => {});
}