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.

30.5 KB
Raw Blame
/**
 * The manage view: states 6 (connected), 9 (degraded) and 11 (many homes).
 *
 * One list that scales from one house to many without a redesign, a measured
 * summary per house rather than an assumed one, the standing allowances with a
 * revoke on each, the action log, and a disconnect that says plainly what it
 * does to the stored token.
 *
 * State 9 is the one that separates a product from a demo: when a house stops
 * answering, the last known room list stays on screen, visibly marked stale with
 * its age. A user watching their home should see it go grey, not watch it vanish.
 */

import { clear, el, noticeEl } from './connect.js';
import { householdPanel } from './members.js';
// Every string a person reads on this page goes through here. The name they
// gave their house, the address they pasted and anything their own Home
// Assistant said are interpolated as values, never baked into a source string.
import { formatNumber, locale, plural, relativeAge, t } from './i18n-home.js';

/** Past this, "moments ago" stops being honest. */
const STALE_AFTER_MS = 90_000;

/**
 * The question every person asks when their home stops answering, and the one
 * they cannot answer alone: is it my house, or is it you?
 *
 * three.ws already computes that verdict across every connected home
 * (api/_lib/ops/home-health.js) and publishes it on the public status feed. So
 * the answer is told here, unprompted, instead of leaving somebody to power-cycle
 * a router during an outage that was ours. It is read once per render, it never
 * blocks the page, and a status feed that does not answer simply says nothing
 * rather than adding a second failure to the one they already have.
 */
const PLATFORM_STATUS_URL = '/api/status';

export function renderManage({ homes, notice, onDisconnect, onReconnect, focused = false }) {
	const frag = document.createDocumentFragment();
	if (notice) frag.append(noticeEl(notice));

	// Filled in asynchronously, and only when there is something to say.
	const platform = el('div');
	frag.append(platform);

	const panel = el('section', 'hm-panel');
	const head = el('div', 'hm-panel-head');
	const heading = el('div');
	heading.append(
		// The focused heading is the user's own name for their house, shown as
		// they typed it. Only the fallback for an unnamed one is ours.
		el('h2', 'hm-panel-title', focused
			? (homes[0]?.label || t('home_manage.this_home', 'This home'))
			: homes.length === 1
				? t('home_manage.your_home', 'Your home')
				: plural('home_manage.your_homes_n', homes.length, 'Your home ({{count}})', 'Your homes ({{count}})')),
		el('p', 'hm-panel-sub', t('home_manage.sub', 'Your agent can read everything here. Anything that unlocks, opens or disarms still stops and asks, unless you have granted it below.')),
	);
	head.append(heading);

	const headActions = el('div', 'hm-card-actions');
	// The plan surface, reachable from the place a person is when they wonder how
	// many of these they are allowed. A limit that can only be found after it
	// refuses you was never shown to you.
	const plan = el('a', 'hm-btn hm-btn-ghost', t('home_manage.plan_and_usage', 'Plan and usage'));
	plan.href = '/smart-home/plan';
	headActions.append(plan);

	// The privacy centre, from the place a person is when they wonder what we are
	// actually keeping. A data-deletion control nobody can find is a promise
	// nobody can exercise, so it sits next to the homes it is about rather than
	// three levels down a settings tree.
	const privacy = el('a', 'hm-btn hm-btn-ghost', t('home_manage.your_data', 'Your data'));
	privacy.href = '/smart-home/privacy';
	headActions.append(privacy);

	if (focused) {
		// A deep link is often the first page someone lands on, so it has to offer
		// a way up rather than assuming they arrived from the list.
		const all = el('a', 'hm-btn hm-btn-ghost', t('home_manage.all_your_homes', 'All your homes'));
		all.href = '/smart-home';
		headActions.append(all);
	} else {
		const add = el('button', 'hm-btn hm-btn-ghost', t('home_manage.connect_another', 'Connect another'));
		add.type = 'button';
		add.addEventListener('click', () => onReconnect && onReconnect());
		headActions.append(add);
	}
	head.append(headActions);
	panel.append(head);

	const list = el('ul', 'hm-list');
	const cards = homes.map((home) => {
		const card = homeCard(home, { onDisconnect, onReconnect, focused });
		list.append(card);
		return { home, card };
	});
	panel.append(list);
	frag.append(panel);

	explainWhoseFault({ platform, cards });
	return frag;
}

/**
 * Read the platform's own verdict on the home lane and say what it means for
 * this person, in their words.
 *
 * Two outcomes, and neither of them is a dashboard:
 *
 *   * the lane is unhealthy, so a banner says so before they touch anything. It
 *     is us. Nothing in their house needs restarting.
 *   * the lane is healthy and one of their homes is not, so that card says the
 *     other houses are answering normally. It is theirs, and the recovery is the
 *     one already printed on the card.
 *
 * A status feed that is unreachable produces neither, because guessing here is
 * worse than silence: telling somebody their house is at fault during an outage
 * we caused is the one wrong answer.
 */
async function explainWhoseFault({ platform, cards }) {
	let home;
	try {
		const res = await fetch(PLATFORM_STATUS_URL, { headers: { accept: 'application/json' } });
		if (!res.ok) return;
		const body = await res.json();
		home = (body?.subsystems?.items || []).find((item) => item?.name === 'home');
	} catch {
		return;
	}
	if (!home || !home.status) return;

	if (home.status === 'degraded' || home.status === 'down') {
		clear(platform);
		platform.append(noticeEl({
			tone: home.status === 'down' ? 'error' : 'warn',
			title: t('home_manage.platform_title', 'This one is us, not your house.'),
			body: t('home_manage.platform_body', 'three.ws is having trouble reaching connected homes right now. Nothing in your house needs restarting and your access token is fine. We are on it, and your home will come back on its own.'),
		}));
		return;
	}

	if (home.status !== 'ok') return;
	for (const { home: row, card } of cards) {
		if (row.status !== 'unreachable' && row.status !== 'auth_failed') continue;
		const line = card.querySelector('.hm-status');
		if (!line) continue;
		line.append(el('span', 'hm-status-verdict', ` ${t('home_manage.only_this_house', 'Every other connected home is answering normally, so this one looks like your house rather than us.')}`));
	}
}

function homeCard(home, { onDisconnect, onReconnect, focused = false }) {
	const li = el('li');
	const card = el('div', 'hm-card');

	const main = el('div', 'hm-card-main');
	// textContent throughout: the label is whatever the user typed and the URL is
	// whatever they pasted.
	main.append(el('p', 'hm-card-label', home.label || hostOf(home.base_url)));
	main.append(el('p', 'hm-card-url', home.base_url || ''));
	main.append(statusLine(home));

	const actions = el('div', 'hm-card-actions');
	// "Open" opens the house: the live 3D scene at /smart-home/<id>, which is the
	// product. This card, with its grants and its action log, is that home's
	// settings and sits one segment deeper.
	const open = el('a', 'hm-btn', t('home_manage.open', 'Open'));
	open.href = `/smart-home/${encodeURIComponent(home.id)}`;
	open.setAttribute('aria-label', t('home_manage.open_aria', 'Open {{home}}', { home: home.label || hostOf(home.base_url) }));
	actions.append(open);

	// Not rendered on the focused view, where it would link to the current page.
	if (!focused) {
		const settings = el('a', 'hm-btn hm-btn-ghost', t('home_manage.settings', 'Settings'));
		settings.href = `/smart-home/${encodeURIComponent(home.id)}/settings`;
		settings.setAttribute('aria-label', t('home_manage.settings_aria', 'Settings for {{home}}', { home: home.label || hostOf(home.base_url) }));
		actions.append(settings);
	}

	// A house whose stored token was rejected, or that has stopped answering, is
	// the one case where reading the status is not enough: the fix is to connect
	// it again, and without this the card states a problem and offers no way out
	// of it except disconnecting.
	if (home.status === 'auth_failed' || home.status === 'unreachable') {
		const again = el('button', 'hm-btn', home.status === 'auth_failed'
			? t('home_manage.reconnect_token', 'Reconnect with a new token')
			: t('home_manage.try_again', 'Try connecting again'));
		again.type = 'button';
		again.addEventListener('click', () => onReconnect && onReconnect(null, {
			label: home.label,
			baseUrl: home.base_url,
		}));
		actions.append(again);
	}

	const drop = el('button', 'hm-btn hm-btn-danger', t('home_manage.disconnect', 'Disconnect'));
	drop.type = 'button';
	drop.addEventListener('click', () => confirmDisconnect(card, home, onDisconnect));
	actions.append(drop);

	card.append(main, actions);
	li.append(card);

	const detail = el('div');
	detail.style.marginTop = 'var(--space-sm)';
	detail.append(summary(home));
	detail.append(healthPanel(home));
	detail.append(householdPanel(home));
	detail.append(grantsPanel(home));
	detail.append(logPanel(home));
	li.append(detail);
	return li;
}

/**
 * "Is my house all right, and if not, is it me or is it them."
 *
 * The `home` subsystem in /api/healthz deliberately refuses to page anyone for a
 * single house going dark, because one person's unplugged router is not an
 * outage. That decision is only defensible if the person whose router it is gets
 * told, and this is where they get told.
 *
 * Two load strategies on purpose. A house that already looks unhealthy on its
 * card fetches immediately, because somebody staring at a red dot should not have
 * to find and open a panel to learn why. A house that looks fine waits to be
 * asked, so a user with six working homes pays no extra round trips on load: the
 * same trade grantsPanel and logPanel already make.
 */
function healthPanel(home) {
	const load = () => getJson(`/api/home/${encodeURIComponent(home.id)}/health`);
	const troubled = home.status !== 'connected' || isStale(home);

	if (!troubled) {
		return lazyPanel({
			title: t('home_manage.health_title', 'How this home is doing'),
			summary: t('home_manage.health_summary', 'Reachability, what your agent has done here, and whether any problem is ours.'),
			load,
			render: renderHealth,
		});
	}

	const wrap = el('div');
	wrap.style.marginTop = 'var(--space-sm)';
	const skeleton = el('div', 'hm-skeleton');
	skeleton.style.height = '5rem';
	wrap.append(skeleton);

	load().then(
		(body) => {
			clear(wrap);
			wrap.append(renderHealth(body));
		},
		(err) => {
			clear(wrap);
			// The card already says the house is not answering. This panel failing
			// on top of that must not read as a second, different fault.
			wrap.append(noticeEl({
				tone: 'warn',
				title: t('home_manage.health_failed_title', 'We could not check why yet.'),
				body: err?.message || t('home_manage.health_failed_body', 'Reload the page to try again.'),
			}));
		},
	);
	return wrap;
}

/** Tone follows whose problem it is, not how loud the words are. */
function healthTone(health) {
	if (health.state === 'live') return 'ok';
	if (health.state === 'revoked' || health.state === 'pending') return 'info';
	// Ours is a warning rather than an error: nothing the reader can act on is
	// broken, and painting their working house red would be a lie.
	if (health.fault === 'us' || health.state === 'stale') return 'warn';
	return 'error';
}

function renderHealth(body) {
	const health = body?.health || {};
	const frag = document.createDocumentFragment();

	if (health.measured === false) {
		frag.append(noticeEl({
			tone: 'warn',
			title: health.headline || 'We could not measure this home just now.',
			body: health.reason || 'Try again in a moment.',
		}));
		return frag;
	}

	frag.append(noticeEl({
		tone: healthTone(health),
		title: health.headline || 'Home status',
		body: health.reason || '',
		bullets: Array.isArray(health.advice) && health.advice.length ? health.advice : undefined,
	}));

	const stats = el('div', 'hm-stats');
	const a = health.actions || {};
	stats.append(
		stat(count(a.ok), 'Actions done'),
		stat(count(a.refused), 'Stopped to ask'),
		stat(count(a.failed), 'Failed'),
		stat(a.p95LatencyMs == null ? 'Not measured' : `${a.p95LatencyMs} ms`, 'Our response time'),
	);
	frag.append(stats);

	const expired = Number(health.confirmations?.expired) || 0;
	if (expired > 0) {
		frag.append(el(
			'p',
			'hm-hint',
			`${expired} confirmation${expired === 1 ? '' : 's'} timed out without an answer. Those actions did not happen.`,
		));
	}

	// The correlation answer, kept to a count. A user is entitled to know whether
	// they are alone in this; they are not entitled to anything about a stranger's
	// house.
	const others = Number(health.fleet?.othersFailing) || 0;
	if (others > 0 && health.fault !== 'us') {
		frag.append(el(
			'p',
			'hm-hint',
			`${others} other home${others === 1 ? ' is' : 's are'} also having trouble right now, which is not yet enough for us to call it a problem on our side.`,
		));
	}

	return frag;
}

/**
 * The standing allowances, with a revoke on each.
 *
 * Loaded on expand rather than on page load: a user with six houses should not
 * pay six extra round trips to see a list most of them will be empty.
 */
function grantsPanel(home) {
	return lazyPanel({
		title: t('home_manage.grants_title', 'Standing allowances'),
		summary: t('home_manage.grants_summary', 'What your agent may open without asking you first.'),
		load: () => getJson(`/api/home/${encodeURIComponent(home.id)}/grants`),
		render: (body, rerender) => {
			const grants = Array.isArray(body?.grants) ? body.grants : [];
			if (!grants.length) {
				return emptyBlock(
					t('home_manage.grants_empty_title', 'Nothing is pre-approved.'),
					t('home_manage.grants_empty_body', 'Every unlock, every opening and every disarm stops and asks you. When you grant one, it appears here with a revoke.'),
				);
			}
			const list = el('ul', 'hm-rows');
			for (const grant of grants) list.append(grantRow(home, grant, rerender));
			return list;
		},
	});
}

function grantRow(home, grant, rerender) {
	const li = el('li', 'hm-row');
	const main = el('div', 'hm-row-main');
	// An entity id is a string the house controls. Text only.
	const title = el('p', 'hm-row-title');
	title.append(el('span', 'hm-mono', grant.entity_id));
	main.append(title);
	main.append(el('p', 'hm-row-meta', grant.expires_at
		? t('home_manage.grant_until', 'Allowed until {{when}}.', { when: formatWhen(grant.expires_at) })
		: t('home_manage.grant_forever', 'Allowed until you revoke it.')));

	const revoke = el('button', 'hm-btn hm-btn-danger', t('home_manage.revoke', 'Revoke'));
	revoke.type = 'button';
	revoke.addEventListener('click', async () => {
		revoke.disabled = true;
		revoke.textContent = t('home_manage.revoking', 'Revoking');
		try {
			await sendJson(`/api/home/${encodeURIComponent(home.id)}/grants?entity_id=${encodeURIComponent(grant.entity_id)}`, 'DELETE');
			rerender();
		} catch (err) {
			revoke.disabled = false;
			revoke.textContent = t('home_manage.try_again_short', 'Try again');
			main.append(el('p', 'hm-row-meta', err?.message || t('home_manage.did_not_go_through', 'That did not go through.')));
		}
	});

	li.append(main, revoke);
	return li;
}

/** Every write the platform made in this house, refusals included. */
const LOG_PAGE = 25;

function logPanel(home) {
	const url = (before) => {
		const q = new URLSearchParams({ limit: String(LOG_PAGE) });
		if (before) q.set('before', before);
		return `/api/home/${encodeURIComponent(home.id)}/log?${q}`;
	};

	return lazyPanel({
		title: t('home_manage.log_title', 'What happened in this house'),
		summary: t('home_manage.log_summary', 'Every action your agent took, and every one it refused.'),
		load: () => getJson(url()),
		render: (body) => {
			const rows = Array.isArray(body?.actions) ? body.actions : [];
			if (!rows.length) {
				return emptyBlock(
					t('home_manage.log_empty_title', 'Nothing yet.'),
					t('home_manage.log_empty_body', 'Once your agent turns a light on or refuses to open a door, it lands here with who asked and what happened.'),
				);
			}

			const wrap = el('div');
			const list = el('ul', 'hm-rows');
			for (const row of rows) list.append(logRow(row));
			wrap.append(list);

			// The endpoint pages on a timestamp rather than an offset, because rows
			// land while somebody is reading and an offset would silently skip one.
			// Appending rather than replacing keeps the reader's scroll position and
			// the history they have already read.
			let cursor = body.next_before || null;
			if (!cursor) return wrap;

			const more = el('button', 'hm-btn hm-btn-ghost', t('home_manage.show_older', 'Show older activity'));
			more.type = 'button';
			more.addEventListener('click', async () => {
				more.disabled = true;
				more.textContent = t('home_manage.loading', 'Loading');
				try {
					const next = await getJson(url(cursor));
					for (const row of next.actions || []) list.append(logRow(row));
					cursor = next.next_before || null;
					if (!cursor) {
						more.replaceWith(el('p', 'hm-hint', t('home_manage.log_end', 'That is the whole history we hold for this home.')));
						return;
					}
					more.disabled = false;
					more.textContent = t('home_manage.show_older', 'Show older activity');
				} catch (err) {
					more.disabled = false;
					more.textContent = t('home_manage.try_again_short', 'Try again');
					wrap.append(el('p', 'hm-row-meta', err?.message || t('home_manage.did_not_load', 'That did not load.')));
				}
			});

			const actions = el('div', 'hm-actions');
			actions.style.marginTop = 'var(--space-sm)';
			actions.append(more);
			wrap.append(actions);
			return wrap;
		},
	});
}

function logRow(row) {
	const li = el('li', 'hm-row');
	const main = el('div', 'hm-row-main');
	const title = el('p', 'hm-row-title');
	title.append(el('span', 'hm-mono', row.action || 'unknown action'));
	main.append(title);

	const targets = Array.isArray(row.entity_ids) ? row.entity_ids : [];
	const parts = [
		`${formatWhen(row.created_at)}`,
		`by ${row.actor || 'unknown'}`,
		targets.length ? targets.join(', ') : null,
		row.guarded ? (row.confirmed_by ? 'confirmed by a person' : 'stopped by the gate') : null,
	].filter(Boolean);
	main.append(el('p', 'hm-row-meta', parts.join(' · ')));

	const outcome = String(row.outcome || 'ok');
	const tag = el('span', `hm-tag hm-tag-${outcome}`, outcome === 'refused' ? 'refused' : outcome === 'failed' ? 'failed' : 'done');
	li.append(main, tag);
	return li;
}

/**
 * A collapsed section that fetches on first open, keeps a skeleton the exact
 * height of its content while it loads, and renders its own error state rather
 * than throwing the whole page away.
 */
function lazyPanel({ title, summary: summaryText, load, render }) {
	const wrap = el('details', 'hm-panel hm-details');
	wrap.style.marginTop = 'var(--space-sm)';
	wrap.style.background = 'transparent';

	const head = el('summary');
	head.append(el('span', '', title));
	wrap.append(head);

	const caption = el('p', 'hm-hint', summaryText);
	wrap.append(caption);

	const body = el('div');
	body.style.marginTop = 'var(--space-sm)';
	wrap.append(body);

	let loaded = false;
	const run = async () => {
		clear(body);
		const skeleton = el('div', 'hm-skeleton');
		skeleton.style.height = '3.4rem';
		body.append(skeleton);
		try {
			const data = await load();
			clear(body);
			body.append(render(data, run));
		} catch (err) {
			clear(body);
			body.append(noticeEl({
				tone: 'error',
				title: t('home_manage.panel_failed_title', 'We could not load this.'),
				body: err?.message || t('home_manage.panel_failed_body', 'Try opening it again in a moment.'),
			}));
		}
	};

	wrap.addEventListener('toggle', () => {
		if (!wrap.open || loaded) return;
		loaded = true;
		run();
	});
	return wrap;
}

function emptyBlock(title, body) {
	const wrap = el('div', 'hm-empty');
	wrap.style.padding = 'var(--space-md) 0';
	wrap.append(el('p', 'hm-empty-title', title), el('p', 'hm-empty-body', body));
	return wrap;
}

async function getJson(url) {
	const res = await fetch(url, { credentials: 'include', headers: { accept: 'application/json' } });
	const body = await res.json().catch(() => null);
	if (!res.ok) throw new Error(body?.message || body?.error_description || `Request failed (${res.status}).`);
	return body;
}

async function sendJson(url, method) {
	const headers = { accept: 'application/json' };
	try {
		const csrfRes = await fetch('/api/csrf-token', { credentials: 'include' });
		if (csrfRes.ok) {
			const csrf = await csrfRes.json();
			const token = csrf?.token || csrf?.data?.token;
			if (token) headers['x-csrf-token'] = token;
		}
	} catch {
		// No CSRF token available: let the server refuse rather than guessing.
	}
	const res = await fetch(url, { method, credentials: 'include', headers });
	const body = await res.json().catch(() => null);
	if (!res.ok) throw new Error(body?.message || body?.error_description || `Request failed (${res.status}).`);
	return body;
}

function formatWhen(iso) {
	const at = Date.parse(iso || '');
	if (!Number.isFinite(at)) return t('home_manage.unknown_time', 'an unknown time');
	// The reader's own locale and their own time zone, through Intl. `undefined`
	// asked the browser rather than the site, which are different the moment
	// somebody picks a language the browser is not set to.
	return new Date(at).toLocaleString(locale(), { dateStyle: 'medium', timeStyle: 'short' });
}

/**
 * The measured summary. Every number here came back from the house at connect
 * time; a capability we could not measure prints as "not measured", never as a
 * confident zero.
 */
function summary(home) {
	const caps = home.capabilities || {};
	const wrap = el('div', 'hm-stats');
	wrap.append(
		stat(count(caps.areaCount), t('home_manage.stat_rooms', 'Rooms')),
		stat(count(caps.entityCount), t('home_manage.stat_devices', 'Devices')),
		stat(count(caps.macroCount), t('home_manage.stat_scenes', 'Scenes')),
		// The version string is the house's own. Only the placeholder for a
		// version we never measured is ours to translate.
		stat(caps.haVersion || t('home_manage.not_measured', 'Not measured'), 'Home Assistant'),
	);

	const holder = el('div');
	holder.append(wrap);

	// A house without mcp_server is an ordinary house, so this is an upgrade
	// offer, never an error.
	if (caps.mcp) {
		holder.append(noticeEl({
			tone: 'ok',
			title: t('home_manage.mcp_on_title', 'Model Context Protocol server connected ({{tools}} tools).', { tools: count(caps.mcpToolCount) }),
			body: t('home_manage.mcp_on_body', 'Your agent uses the exact tools you exposed in Home Assistant, with your own exposure rules.'),
		}));
	} else if (caps.websocket) {
		holder.append(noticeEl({
			tone: 'info',
			title: t('home_manage.mcp_off_title', 'Optional: turn on the Model Context Protocol server.'),
			body: t('home_manage.mcp_off_body', 'Add the Model Context Protocol Server integration in Home Assistant, under Settings, Devices and services, to give your agent the exact tool set you curated. Everything already works without it.'),
		}));
	}
	return holder;
}

function stat(value, label) {
	const box = el('div', 'hm-stat');
	box.append(el('span', 'hm-stat-value', value), el('span', 'hm-stat-label', label));
	return box;
}

function count(value) {
	return Number.isFinite(Number(value)) ? formatNumber(Number(value)) : t('home_manage.not_measured', 'Not measured');
}

/**
 * State 9 lives here. A connected home whose last handshake has aged past the
 * window is rendered as stale with its age spelled out, so "is this live?" is
 * answerable at a glance rather than inferred from a dot nobody can read.
 */
function statusLine(home) {
	const wrap = el('p', 'hm-status');
	const stale = isStale(home);
	const key = stale ? 'stale' : home.status || 'pending';

	const dot = el('span', `hm-dot hm-dot-${key}`);
	dot.setAttribute('aria-hidden', 'true');
	wrap.append(dot, el('span', '', statusText(home, stale)));
	return wrap;
}

function isStale(home) {
	if (home.status !== 'connected') return false;
	const last = Date.parse(home.last_ok_at || '');
	if (!Number.isFinite(last)) return false;
	return Date.now() - last > STALE_AFTER_MS;
}

/**
 * Is this house currently something other than live?
 *
 * The card already says so in words; this is the same judgement as a boolean,
 * so the page can name the state it is in rather than reporting `connected`
 * over a card that reads "not answering right now". Three ways a house is not
 * live, and the card has a different sentence for each: it has stopped
 * answering (stale), it is refusing the connection (unreachable), or the token
 * we hold no longer works (auth_failed). `pending` is not degraded, it is the
 * first few seconds of a connection that is still being made.
 */
export function isDegraded(home) {
	if (!home) return false;
	if (home.status === 'unreachable' || home.status === 'auth_failed') return true;
	return isStale(home);
}

function statusText(home, stale) {
	if (stale) return t('home_manage.status_stale', 'Last answered {{ago}}. Showing the last state we saw.', { ago: ago(home.last_ok_at) });
	switch (home.status) {
		case 'connected':
			return home.last_ok_at
				? t('home_manage.status_live_updated', 'Live, updated {{ago}}.', { ago: ago(home.last_ok_at) })
				: t('home_manage.status_live', 'Live.');
		case 'auth_failed': return home.status_detail || t('home_manage.status_auth', 'Home Assistant rejected the stored token. Reconnect with a new one.');
		case 'unreachable': return unreachableText(home);
		case 'revoked': return t('home_manage.status_revoked', 'Disconnected.');
		default: return home.status_detail || t('home_manage.status_connecting', 'Connecting.');
	}
}

/**
 * What to say about a house that is not answering.
 *
 * The distinction is the whole of state 8 versus state 9, and getting it wrong
 * is worse than saying nothing. `status_detail` on a failed dial carries the
 * connect-time diagnosis, which for a LAN address reads "if it is only on your
 * home network, three.ws cannot route to it: use your remote https URL". That
 * is the right sentence for a house that has never connected. It is exactly the
 * wrong one for a house that worked this morning and then lost power: the
 * address was never the problem, and we would be sending somebody off to
 * reconfigure a reverse proxy over a tripped breaker. Caught live, by stopping
 * a connected house and reading its card.
 *
 * A house that has answered before therefore gets told the true thing (it
 * stopped answering, and this is when it last spoke). The platform's own note
 * that it has backed off its retries survives either way, because that one is
 * true in both cases and it is the part that says "you do not have to do
 * anything".
 */
function unreachableText(home) {
	const paused = /paused retries/i.test(home.status_detail || '')
		? ` ${t('home_manage.retries_paused', 'three.ws has paused its retries for a few minutes and will try again on its own.')}`
		: '';
	if (home.last_ok_at) {
		return t('home_manage.status_down_seen', 'Not answering right now. It last answered {{ago}}, and that is the state shown below.', { ago: ago(home.last_ok_at) }) + paused;
	}
	return home.status_detail || t('home_manage.status_down_never', 'Not answering right now. The last state we saw is below.');
}

/**
 * Plain language, and never a future tense for a past timestamp.
 *
 * The wording comes from Intl.RelativeTimeFormat via the shared bridge, so
 * "3 minutes ago" carries each locale's own plural rules instead of an English
 * `s` appended in code. Only the two things Intl has no opinion about, an
 * unreadable timestamp and the "just now" band, are catalog keys.
 */
function ago(iso) {
	const then = Date.parse(iso || '');
	if (!Number.isFinite(then)) return t('home_manage.unknown_when', 'at an unknown time');
	const ms = Date.now() - then;
	if (ms < 45_000) return t('home_manage.moments_ago', 'moments ago');
	return relativeAge(ms);
}

/**
 * Disconnecting destroys a credential, so it confirms in place rather than
 * behind a browser dialog: the confirmation says exactly what happens to the
 * token, on our side and on theirs.
 */
function confirmDisconnect(card, home, onDisconnect) {
	const existing = card.parentElement.querySelector('[data-confirm]');
	if (existing) existing.remove();

	const box = el('div', 'hm-notice hm-notice-warn');
	box.dataset.confirm = 'true';
	box.setAttribute('role', 'alertdialog');
	box.setAttribute('aria-label', t('home_manage.disconnect_aria', 'Disconnect {{home}}', { home: home.label || t('home_manage.this_home', 'This home') }));

	const content = el('div');
	content.append(
		el('p', 'hm-notice-title', t('home_manage.disconnect_question', 'Disconnect {{home}}?', { home: home.label || hostOf(home.base_url) })),
		el('p', 'hm-notice-body', t('home_manage.disconnect_body_1', 'The access token we hold is erased immediately and your agent loses all access to this house. Your standing allowances and the action log are kept so you can still read what happened.')),
		el('p', 'hm-notice-body', t('home_manage.disconnect_body_2', 'This does not delete the token inside Home Assistant. Delete it there too if you want it gone on both sides.')),
	);

	const actions = el('div', 'hm-actions');
	actions.style.marginTop = 'var(--space-sm)';
	const yes = el('button', 'hm-btn hm-btn-danger', t('home_manage.disconnect_yes', 'Disconnect and erase the token'));
	yes.type = 'button';
	const no = el('button', 'hm-btn hm-btn-ghost', t('home_manage.disconnect_no', 'Keep it connected'));
	no.type = 'button';

	const dismiss = () => {
		box.remove();
		document.removeEventListener('keydown', onKey);
		card.querySelector('.hm-btn-danger')?.focus();
	};
	// Escape closes it, because this is a dialog and a destructive one: a keyboard
	// user must be able to back out of it the way they back out of every other
	// dialog, without hunting for the cancel button.
	const onKey = (event) => {
		if (event.key === 'Escape') {
			event.stopPropagation();
			dismiss();
		}
	};
	document.addEventListener('keydown', onKey);
	no.addEventListener('click', dismiss);
	yes.addEventListener('click', async () => {
		yes.disabled = true;
		no.disabled = true;
		yes.textContent = t('home_manage.disconnecting', 'Disconnecting');
		try {
			await onDisconnect(home);
			document.removeEventListener('keydown', onKey);
		} catch (err) {
			clear(content);
			content.append(
				el('p', 'hm-notice-title', t('home_manage.did_not_go_through', 'That did not go through.')),
				el('p', 'hm-notice-body', err?.message || t('home_manage.try_in_a_moment', 'Try again in a moment.')),
			);
			yes.disabled = false;
			no.disabled = false;
			yes.textContent = t('home_manage.try_again_short', 'Try again');
		}
	});

	actions.append(yes, no);
	content.append(actions);
	box.append(content);
	card.parentElement.append(box);
	yes.focus();
}

function hostOf(url) {
	try {
		return new URL(url).host;
	} catch {
		return url || 'this home';
	}
}