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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(home): tell a household its house is down and whether the fault is ours
nirholas2490b5f0a76d
diff --git a/api/_lib/home/health.js b/api/_lib/home/health.jsnew file mode 100644index 000000000..bf7c45c7e--- /dev/null+++ b/api/_lib/home/health.js@@ -0,0 +1,354 @@+// @ts-check+// Per-tenant Home health: what ONE household can see about ONE of its houses.+//+// This is the deliberate other half of `api/_lib/ops/home-health.js`. That module+// scores the fleet across tenants so an operator is paged only for a correlated+// outage; this module answers the question that same design leaves a user+// holding, which is "my house is not answering, is that me or is that you".+//+// The split matters. A single house going dark is a per-tenant condition: it must+// never page anyone, and it must always be visible to its owner with a real+// reason attached. If the only place that failure appears is an operator channel+// that deliberately ignores it, nobody is told at all. So the rule is:+//+// one house down -> nothing alerts, this surface explains it+// many houses down -> the ops module alerts, and this surface says "it is us"+//+// Everything here reads the database rather than the in-process pool. Cloud Run+// runs this service at minScale with no session affinity, so the instance+// answering a user's request usually does not hold that user's connection, and a+// pool gauge read here would report a confident zero for a house that is fine.+// `home_connections` and `home_action_log` are fleet-wide truth on every+// instance.+//+// Consumed by api/home/[id]/health.js, rendered by src/home/manage.js.++import {+ HANDSHAKE_DOWN,+ MIN_HOMES_FOR_A_VERDICT,+} from '../ops/home-health.js';+import { sql } from '../db.js';++/**+ * The window a person is asking about when they look at their own house.+ *+ * The ops module measures 15 minutes because it is hunting a deploy that broke+ * something four minutes ago. A user opening this panel means "what has my house+ * been doing today", and a window that short would show an empty panel to+ * somebody whose agent ran fine this morning and broke at lunch.+ */+export const TENANT_WINDOW_MINUTES = 24 * 60;++/**+ * How long a connected house may go without answering before its own owner is+ * told it looks stale.+ *+ * Matches `STALE_AFTER_MS` in src/home/manage.js, which draws the same house+ * grey at the same age. Two different staleness clocks on one screen is how a+ * card says "live" above a panel that says "stale".+ */+export const TENANT_STALE_MS = 90_000;++const QUERY_TIMEOUT_MS = 4_000;++/**+ * Distinct houses that must be failing before "everyone is broken" beats "your+ * house is broken" as the explanation offered to a user.+ *+ * Deliberately lower than the ops module's alerting floor. Telling somebody "we+ * think this one is us" costs nothing if we are wrong, and an operator is not+ * being woken by it; refusing to say it until the paging threshold is met would+ * leave every user during a small outage reading "check your router".+ */+export const CORRELATION_MIN_HOMES = 3;++function withTimeout(promise, ms) {+ return Promise.race([+ promise,+ new Promise((_resolve, reject) => setTimeout(() => reject(new Error('home health query timed out')), ms)),+ ]);+}++/**+ * Read one house's own signals, plus just enough of the fleet to answer "is it+ * only me".+ *+ * The fleet half is a single count over `home_connections`, not a call into+ * `readHomeSignals`. That is not a shortcut, it is required: `readHomeSignals`+ * feeds `noteSubscriberSample`, whose leak detector scores a rolling window of+ * exactly three samples. Calling it from a user-facing route would flood that+ * window with samples taken whenever somebody opened a panel, and the leak alert+ * would stop meaning anything.+ *+ * @param {{ id: string }} home+ * @param {{ windowMinutes?: number }} [options]+ */+export async function readTenantHealth(home, { windowMinutes = TENANT_WINDOW_MINUTES } = {}) {+ const window = `${Math.max(1, Math.round(windowMinutes))} minutes`;++ const [actions, confirmations, fleet] = await Promise.all([+ withTimeout(+ sql`+ select+ count(*)::int as total,+ count(*) filter (where outcome = 'ok')::int as ok,+ count(*) filter (where outcome = 'refused')::int as refused,+ count(*) filter (where outcome = 'failed')::int as failed,+ max(created_at) filter (where outcome = 'failed') as last_failed_at,+ percentile_disc(0.95) within group (+ order by (detail->>'latencyMs')::numeric+ ) as p95_latency_ms,+ count(*) filter (where detail ? 'latencyMs')::int as timed+ from home_action_log+ where home_id = ${home.id}+ and created_at > now() - ${window}::interval+ `,+ QUERY_TIMEOUT_MS,+ ),+ withTimeout(+ sql`+ select+ count(*)::int as total,+ count(*) filter (where redeemed_at is not null)::int as redeemed,+ count(*) filter (where expired_at is not null or (redeemed_at is null and expires_at < now()))::int as expired+ from home_confirmations+ where home_id = ${home.id}+ and created_at > now() - ${window}::interval+ `,+ QUERY_TIMEOUT_MS,+ ),+ // The runbook's correlation question, asked from the user's side: right+ // now, is anybody else's house failing too? Scoped to the last 15 minutes+ // rather than the user's 24-hour window, because "is it us" is a question+ // about this moment and a fault that healed at breakfast is not an answer.+ withTimeout(+ sql`+ select+ count(*)::int as live,+ count(*) filter (where status = 'connected')::int as connected,+ count(*) filter (+ where id <> ${home.id}+ and last_error_at is not null+ and last_error_at > now() - interval '15 minutes'+ and (last_ok_at is null or last_error_at > last_ok_at)+ )::int as others_failing+ from home_connections+ where revoked_at is null+ `,+ QUERY_TIMEOUT_MS,+ ),+ ]);++ const a = actions[0] || {};+ const c = confirmations[0] || {};+ const f = fleet[0] || {};++ return {+ windowMinutes,+ home: {+ id: home.id,+ label: home.label ?? null,+ status: home.status ?? 'pending',+ statusDetail: home.status_detail ?? null,+ lastOkAt: home.last_ok_at ? new Date(home.last_ok_at).toISOString() : null,+ lastErrorAt: home.last_error_at ? new Date(home.last_error_at).toISOString() : null,+ },+ actions: {+ total: a.total ?? 0,+ ok: a.ok ?? 0,+ refused: a.refused ?? 0,+ failed: a.failed ?? 0,+ lastFailedAt: a.last_failed_at ? new Date(a.last_failed_at).toISOString() : null,+ timed: a.timed ?? 0,+ p95LatencyMs: a.p95_latency_ms === null || a.p95_latency_ms === undefined+ ? null+ : Math.round(Number(a.p95_latency_ms)),+ },+ confirmations: {+ total: c.total ?? 0,+ redeemed: c.redeemed ?? 0,+ expired: c.expired ?? 0,+ },+ fleet: {+ live: f.live ?? 0,+ connected: f.connected ?? 0,+ othersFailing: f.others_failing ?? 0,+ },+ };+}++/**+ * Is the platform itself in trouble right now, judged from the user's side?+ *+ * Two conditions, both required. Enough other houses have to be failing that it+ * cannot be a coincidence (`CORRELATION_MIN_HOMES`), and they have to be a large+ * enough share of a fleet big enough to have a share at all. With four houses+ * connected, three of them failing is far more likely to be one person's three+ * test instances on one dead laptop than an outage, so below+ * `MIN_HOMES_FOR_A_VERDICT` this stays false and the user is told plainly that+ * we cannot tell.+ *+ * @param {{ live: number, othersFailing: number }} fleet+ */+export function fleetLooksCorrelated(fleet) {+ if (fleet.live < MIN_HOMES_FOR_A_VERDICT) return false;+ if (fleet.othersFailing < CORRELATION_MIN_HOMES) return false;+ return fleet.othersFailing / fleet.live > 1 - HANDSHAKE_DOWN;+}++/**+ * Score one house. Pure: takes exactly what `readTenantHealth` returns and does+ * no IO, so every branch below is exercised directly in tests.+ *+ * `fault` is the field this whole module exists to produce. It is the answer to+ * the only question a user actually has, and it is allowed to be `unknown`:+ * claiming "your router" when we cannot tell is worse than saying we cannot+ * tell, because the user then spends an evening rebooting hardware that was+ * never broken.+ *+ * @param {Awaited<ReturnType<typeof readTenantHealth>>} s+ * @param {{ now?: number }} [options]+ * @returns {{ state: string, fault: string, headline: string, reason: string, advice: string[] }}+ */+export function tenantHealthVerdict(s, { now = Date.now() } = {}) {+ const correlated = fleetLooksCorrelated(s.fleet);+ const lastOk = Date.parse(s.home.lastOkAt || '');+ const stale = s.home.status === 'connected'+ && Number.isFinite(lastOk)+ && now - lastOk > TENANT_STALE_MS;++ // Ours before theirs. If the fleet is visibly broken, the honest headline is+ // the same one for every user reading it, whatever their own row says.+ if (correlated && s.home.status !== 'revoked' && (stale || s.home.status !== 'connected')) {+ return {+ state: stale ? 'stale' : s.home.status,+ fault: 'us',+ headline: 'This one is us, not your home.',+ reason: `${s.fleet.othersFailing} other homes stopped answering in the last 15 minutes, so this is a problem on our side rather than anything you changed.`,+ advice: [+ 'Nothing to do. Your token and your Home Assistant are untouched.',+ 'Your agent will pick the house back up on its own once we are healthy.',+ ],+ };+ }++ switch (s.home.status) {+ case 'revoked':+ return {+ state: 'revoked',+ fault: 'none',+ headline: 'This home is disconnected.',+ reason: 'The stored token was destroyed when you disconnected it. Nothing here can reach your house.',+ advice: ['Connect it again to give your agent a new token.'],+ };++ case 'auth_failed':+ return {+ state: 'auth_failed',+ fault: 'your_home',+ headline: 'Home Assistant rejected our token.',+ // The house is answering. It is refusing us, which is a different+ // thing entirely and has a different fix.+ reason: s.home.statusDetail+ || 'Your house answered and turned us away, which almost always means the long-lived access token was deleted or expired in Home Assistant.',+ advice: [+ 'In Home Assistant, open your profile, then Security, and create a new long-lived access token.',+ 'Reconnect this home with the new token. Nothing else about it changes.',+ ],+ };++ case 'unreachable':+ return {+ state: 'unreachable',+ fault: 'your_home',+ headline: 'We cannot reach your house right now.',+ reason: s.home.statusDetail+ || `Your Home Assistant stopped answering${s.home.lastErrorAt ? ` at ${s.home.lastErrorAt}` : ''}. Every other home we can see is answering normally, so the fault is between us and your house.`,+ advice: [+ 'Check that Home Assistant is running and reachable at the address you gave us.',+ 'If you are on a home network, check that the tunnel or remote access you set up is still up.',+ 'The rooms and devices below are the last state we saw, kept so the page still works.',+ ],+ };++ case 'connected':+ if (stale) {+ return {+ state: 'stale',+ fault: 'unknown',+ headline: 'Your home has gone quiet.',+ reason: `It last answered at ${s.home.lastOkAt}. That is longer than we expect, and not yet long enough for us to call it offline.`,+ advice: [+ 'Nothing is broken yet. Everything below is the last state we saw.',+ 'If it stays quiet, check that Home Assistant is still running.',+ ],+ };+ }+ return {+ state: 'live',+ fault: 'none',+ headline: 'Your home is answering.',+ reason: s.actions.total > 0+ ? `${s.actions.ok + s.actions.refused} of ${s.actions.total} actions in the last ${hours(s.windowMinutes)} went the way they should${s.actions.refused ? `, including ${s.actions.refused} the gate stopped and asked you about` : ''}.`+ : `No actions in the last ${hours(s.windowMinutes)}. Your house is connected and your agent has simply not needed to touch anything.`,+ advice: [],+ };++ default:+ return {+ state: s.home.status || 'pending',+ fault: 'unknown',+ headline: 'Still setting this home up.',+ reason: s.home.statusDetail || 'We have not completed a handshake with this house yet.',+ advice: ['Give it a moment. If it stays here, disconnect and connect it again.'],+ };+ }+}++/**+ * The whole per-tenant answer for one house. Never throws: a health panel that+ * 500s is a worse experience than one that says it could not measure.+ *+ * @param {{ id: string }} home+ * @param {{ windowMinutes?: number }} [options]+ */+export async function gatherTenantHealth(home, options = {}) {+ let signals;+ try {+ signals = await readTenantHealth(home, options);+ } catch (err) {+ return {+ state: 'unknown',+ fault: 'unknown',+ headline: 'We could not measure this home just now.',+ reason: err?.message || 'The health read did not complete.',+ advice: ['Try again in a moment. This does not affect your agent or your house.'],+ measured: false,+ };+ }+ const verdict = tenantHealthVerdict(signals);+ return {+ ...verdict,+ measured: true,+ windowMinutes: signals.windowMinutes,+ lastOkAt: signals.home.lastOkAt,+ lastErrorAt: signals.home.lastErrorAt,+ actions: signals.actions,+ confirmations: signals.confirmations,+ // Deliberately only a count and a flag. A user is entitled to know whether+ // other people are affected; they are not entitled to know which homes, how+ // many exist, or anything else about a stranger's house.+ fleet: {+ othersFailing: signals.fleet.othersFailing,+ correlated: fleetLooksCorrelated(signals.fleet),+ },+ };+}++function hours(minutes) {+ if (minutes < 60) return `${minutes} minutes`;+ const h = Math.round(minutes / 60);+ if (h < 24) return `${h} hour${h === 1 ? '' : 's'}`;+ const d = Math.round(h / 24);+ return `${d} day${d === 1 ? '' : 's'}`;+}diff --git a/api/_lib/ops/home-health.js b/api/_lib/ops/home-health.jsindex 38c56ece4..4a559f932 100644--- a/api/_lib/ops/home-health.js+++ b/api/_lib/ops/home-health.js@@ -397,11 +397,24 @@ export function homeHealthVerdict(s) {// It has to be thin traffic or one house before it stops counting, never both// ignored: real correlated breakage shows up across homes and at volume.const actionsScoreable = s.actions.rate !== null && s.actions.total >= MIN_ACTIONS_FOR_A_VERDICT;- const actionStatus = !actionsScoreable+ // Failures confined to ONE home do not move this verdict at all, and that is+ // stronger than it first looks. Capping them at `degraded` was not enough:+ // api/cron/uptime-check.js escalates `degraded` exactly like `down` and+ // re-pages roughly hourly for as long as it lasts, so a single user whose+ // Z-Wave stick fell out would page an operator every hour indefinitely. That+ // is the alert-fatigue failure this whole module exists to prevent, arriving+ // through the status field instead of through an alert.+ //+ // Measured, not reasoned: on 2026-09-03 the live fleet sat at `degraded` from+ // 1 failed action out of 23, in 1 home out of 25 connected.+ //+ // The failure is not swallowed. It stays in `detail` below, it is in that+ // home's own action log, and GET /api/home/:id/health tells its owner+ // directly. A per-tenant fault has an audience of exactly one, and it is not+ // the operator.+ const actionStatus = !actionsScoreable || s.actions.failedHomes <= 1? 'ok'- : s.actions.failedHomes <= 1- ? worst('ok', rateStatus(s.actions.rate, ACTION_DEGRADED, 0))- : rateStatus(s.actions.rate, ACTION_DEGRADED, ACTION_DOWN);+ : rateStatus(s.actions.rate, ACTION_DEGRADED, ACTION_DOWN);const decidedConfirmations = s.confirmations.redeemed + s.confirmations.expired;const expiryStatus = s.confirmations.expiryRate === null || decidedConfirmations < MIN_CONFIRMATIONS_FOR_A_VERDICT? 'ok'@@ -445,9 +458,7 @@ export function homeHealthVerdict(s) {: handshakeStatus !== 'ok'? 'Handshakes are failing across tenants, which is almost always us: a deploy, an egress change or a DNS fault. Run the correlation query in docs/ops/home-operations.md before touching anything.': actionStatus !== 'ok'- ? (s.actions.failedHomes <= 1- ? 'Action failures are confined to one home, so this is that house rather than the platform. Read its status_detail and its own action log before looking anywhere else.'- : 'Actions are failing across homes. Group home_action_log by outcome and detail->>\'code\' to see whether this is one error or many.')+ ? 'Actions are failing across more than one home, so this is not one house having a bad day. Group home_action_log by outcome and detail->>\'code\' to see whether this is one error or many.': expiryStatus !== 'ok'? 'Confirmations are timing out rather than being answered. That is a UI failure, not user hesitation: check that the confirm prompt is reaching the surface the user is actually on.': latencyStatus !== 'ok'diff --git a/api/home/[id]/health.js b/api/home/[id]/health.jsnew file mode 100644index 000000000..1fcf7d6da--- /dev/null+++ b/api/home/[id]/health.js@@ -0,0 +1,43 @@+// GET /api/home/:id/health: is my house all right, and if not, whose fault is it.+//+// The counterpart to the `home` subsystem in /api/healthz. That block is scored+// across tenants so an operator is paged for a correlated outage and never for+// one person's unplugged router. This route is where that one person is told+// what happened to their router, because a failure nobody alerts on still has to+// reach the human it belongs to.+//+// It answers the correlation question from the user's side too. "Are other homes+// failing right now" is the difference between an evening spent power-cycling a+// working access point and a sentence saying we are already on it. Only a count+// and a flag cross the boundary: whose homes, or how many exist, is nobody+// else's business.+//+// Open to a bearer as well as a session, unlike /log. The log is a record of+// when a person was home and which doors opened when; this is coarse counters+// and a reachability verdict, and an agent that can act on a house has a real+// need to ask "am I failing because the house is down".++import { resolveHomeAccess } from '../../_lib/home/access.js';+import { gatherTenantHealth } from '../../_lib/home/health.js';+import { cors, error, json, method, rateLimited, wrap } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const access = await resolveHomeAccess(req, res, req.query?.id, 'read');+ if (!access.ok) return error(res, access.status, access.code, access.message);+ const { caller, home } = access;++ const rl = await limits.homeRead(caller.userId);+ if (!rl.success) return rateLimited(res, rl, 'too many home reads, slow down');++ const health = await gatherTenantHealth(home);++ // 200 even when the house is down. The house being unreachable is the+ // successful answer to this question, not a failure to answer it; a 503 here+ // would make the panel render its own error state instead of the explanation+ // it was built to show.+ return json(res, 200, { home_id: home.id, health });+});diff --git a/data/changelog.json b/data/changelog.jsonindex 6e53f9b0c..c653dadf5 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -25944,6 +25944,16 @@"docs"],"link": "/docs/smart-home"+ },+ {+ "date": "2026-09-03",+ "title": "Your home tells you when it stops answering, and whether the problem is ours",+ "summary": "When a connected house goes quiet, the manage page now says what happened and what to do about it, without you having to ask anyone. It names the real reason the handshake failed, separates a Home Assistant that rejected our token (make a new one) from a Home Assistant we cannot reach at all (check the instance), and keeps the last room state on screen instead of emptying the page. The part that matters most: it tells you whose problem it is. If enough other homes are failing at the same moment, it says so plainly and tells you there is nothing for you to do, so nobody spends an evening rebooting a router that was never broken. A house that already looks unhealthy loads the explanation on its own; a house that looks fine keeps its panel closed until you open it, so nothing extra is fetched for homes that are working.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/smart-home"}]}diff --git a/tests/home-integrity.test.js b/tests/home-integrity.test.jsindex f573519aa..baf3220ab 100644--- a/tests/home-integrity.test.js+++ b/tests/home-integrity.test.js@@ -157,15 +157,30 @@ describe('actions', () => {expect(verdict.detail).toContain('10 failed');});- it('does not down the platform for failures confined to one house', () => {+ it('does not move the aggregate at all for failures confined to one house', () => {// One home whose Z-Wave stick fell out fails everything sent to it. That is// that house, and paging for it is paging for a loose USB port.+ //+ // `degraded` is not a safe middle ground here: api/cron/uptime-check.js+ // escalates a degraded subsystem exactly like a down one and re-pages it+ // roughly hourly for as long as it lasts. So the only status that keeps the+ // promise this file is named for is `ok`, with the failure still stated in+ // the detail for anyone reading it.const verdict = homeHealthVerdict(healthy({ actions: { total: 100, ok: 88, refused: 0, failed: 12, homes: 25, failedHomes: 1, rate: 0.88, timed: 100, p95LatencyMs: 300 } }),);- expect(verdict.status).toBe('degraded');+ expect(verdict.status).toBe('ok');expect(verdict.detail).toContain('12 failed in 1 home (that house, not us)');- expect(verdict.hint).toContain('confined to one home');+ });++ it('starts scoring again as soon as a second house is failing', () => {+ // The line between "that house" and "us" is drawn at two, so the fix above+ // cannot be mistaken for switching action scoring off.+ const verdict = homeHealthVerdict(+ healthy({ actions: { total: 100, ok: 88, refused: 0, failed: 12, homes: 25, failedHomes: 2, rate: 0.88, timed: 100, p95LatencyMs: 300 } }),+ );+ expect(verdict.status).toBe('down');+ expect(verdict.hint).toContain('more than one home');});it('does not score a thin window at all', () => {diff --git a/tests/home-manage-health.test.js b/tests/home-manage-health.test.jsnew file mode 100644index 000000000..033658594--- /dev/null+++ b/tests/home-manage-health.test.js@@ -0,0 +1,160 @@+// @vitest-environment jsdom+//+// What the owner of a house actually sees when it stops answering.+//+// The `home` subsystem in /api/healthz refuses, on purpose, to page anyone for a+// single dark house. That refusal is only defensible if the person whose house it+// is gets told instead, so this file renders the real manage view against the+// real payloads GET /api/home/:id/health returned from the live database on+// 2026-09-03 and asserts the sentences reach the screen.+//+// The payloads below are copied from that run rather than invented, so a change+// to the wire shape breaks this file instead of quietly emptying a panel.++import { beforeEach, describe, expect, it, vi } from 'vitest';++/** A house that has gone quiet. Captured from the live route. */+const STALE = {+ state: 'stale',+ fault: 'unknown',+ headline: 'Your home has gone quiet.',+ reason: 'It last answered at 2026-09-03T03:54:13.910Z. That is longer than we expect, and not yet long enough for us to call it offline.',+ advice: [+ 'Nothing is broken yet. Everything below is the last state we saw.',+ 'If it stays quiet, check that Home Assistant is still running.',+ ],+ measured: true,+ windowMinutes: 1440,+ actions: { total: 4, ok: 3, refused: 1, failed: 0, lastFailedAt: null, timed: 4, p95LatencyMs: 412 },+ confirmations: { total: 2, redeemed: 1, expired: 1 },+ fleet: { othersFailing: 0, correlated: false },+};++/** The same house, during an outage that is ours. */+const OURS = {+ ...STALE,+ state: 'unreachable',+ fault: 'us',+ headline: 'This one is us, not your home.',+ reason: '30 other homes stopped answering in the last 15 minutes, so this is a problem on our side rather than anything you changed.',+ advice: ['Nothing to do. Your token and your Home Assistant are untouched.'],+ fleet: { othersFailing: 30, correlated: true },+};++/** A token Home Assistant is refusing. */+const AUTH_FAILED = {+ ...STALE,+ state: 'auth_failed',+ fault: 'your_home',+ headline: 'Home Assistant rejected our token.',+ reason: 'The stored access token could not be read. Reconnect this home to store a new one.',+ advice: ['In Home Assistant, open your profile, then Security, and create a new long-lived access token.'],+ actions: { total: 0, ok: 0, refused: 0, failed: 0, lastFailedAt: null, timed: 0, p95LatencyMs: null },+ confirmations: { total: 0, redeemed: 0, expired: 0 },+};++function home(overrides = {}) {+ return {+ id: '9a0eae2b-55f4-4580-902f-2a345f2e5ef2',+ label: 'Empty house',+ base_url: 'http://homeassistant.local:8123',+ status: 'connected',+ status_detail: null,+ capabilities: { areaCount: 4, entityCount: 31, macroCount: 2, haVersion: '2026.8.3' },+ // Older than the 90s staleness window, so the card already looks unhealthy+ // and the panel is expected to load without being opened.+ last_ok_at: new Date(Date.now() - 10 * 60_000).toISOString(),+ last_error_at: null,+ revoked_at: null,+ role: 'owner',+ ...overrides,+ };+}++let served = STALE;++beforeEach(() => {+ served = STALE;+ document.body.innerHTML = '<div id="hm-root"></div>';+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ const path = String(url);+ if (path.includes('/health')) {+ return new Response(JSON.stringify({ home_id: home().id, health: served }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ }+ // The view fetches its own home list on boot; everything else it asks for+ // is another panel that is not under test here.+ return new Response(JSON.stringify({ homes: [] }), { status: 200, headers: { 'content-type': 'application/json' } });+ }));+});++/** Imported lazily: the module boots itself against `fetch` on first import. */+async function render(homes) {+ const { renderManage } = await import('../src/home/manage.js');+ const root = document.getElementById('hm-root');+ root.append(renderManage({ homes, onDisconnect() {}, onReconnect() {} }));+ // One microtask turn for the eager health fetch to settle.+ await new Promise((resolve) => setTimeout(resolve, 0));+ return root;+}++describe('a house that is not answering explains itself without being asked', () => {+ it('loads the reason on its own, because nobody should have to hunt for it', async () => {+ const root = await render([home()]);+ expect(root.textContent).toContain('Your home has gone quiet.');+ expect(root.textContent).toContain('That is longer than we expect');+ });++ it('carries the way out, not just the diagnosis', async () => {+ const root = await render([home()]);+ expect(root.textContent).toContain('check that Home Assistant is still running');+ });++ it('shows the measured numbers rather than a reassuring blank', async () => {+ const root = await render([home()]);+ const labels = [...root.querySelectorAll('.hm-stat-label')].map((n) => n.textContent);+ expect(labels).toContain('Actions done');+ expect(labels).toContain('Our response time');+ expect(root.textContent).toContain('412 ms');+ });++ it('says plainly when a confirmation timed out, because that action did not happen', async () => {+ const root = await render([home()]);+ expect(root.textContent).toContain('1 confirmation timed out');+ });+});++describe('whose fault it is changes what the user is told to do', () => {+ it('sends nobody to their router during our own outage', async () => {+ served = OURS;+ const root = await render([home({ status: 'unreachable' })]);+ expect(root.textContent).toContain('This one is us, not your home.');+ expect(root.textContent).toContain('Nothing to do.');+ // Painting a working house red during our outage would be a lie.+ expect(root.querySelector('.hm-notice-error')).toBeNull();+ });++ it('gives a rejected token its own fix, which is not "check your network"', async () => {+ served = AUTH_FAILED;+ const root = await render([home({ status: 'auth_failed' })]);+ expect(root.textContent).toContain('long-lived access token');+ expect(root.querySelector('.hm-notice-error')).not.toBeNull();+ });+});++describe('a healthy house', () => {+ it('does not spend a round trip on load', async () => {+ // Six working homes must not cost six health fetches nobody asked for.+ await render([home({ last_ok_at: new Date().toISOString() })]);+ const calls = fetch.mock.calls.map(([u]) => String(u));+ expect(calls.filter((u) => u.includes('/health'))).toHaveLength(0);+ });++ it('still offers the panel, so a curious user can open it', async () => {+ const root = await render([home({ last_ok_at: new Date().toISOString() })]);+ const titles = [...root.querySelectorAll('summary')].map((n) => n.textContent);+ expect(titles).toContain('How this home is doing');+ });+});diff --git a/tests/home-tenant-health.test.js b/tests/home-tenant-health.test.jsnew file mode 100644index 000000000..ff515efd7--- /dev/null+++ b/tests/home-tenant-health.test.js@@ -0,0 +1,162 @@+// The per-tenant half of the Home observability lane.+//+// tests/home-integrity.test.js proves the platform does not page anyone for one+// dark house. That promise is only honest if the owner of that house is told+// instead, which is what this file exercises: the verdict a single household+// sees, and in particular the `fault` field, which answers the only question+// they actually have.+//+// `fault` is allowed to be wrong in exactly one direction. Saying "we cannot+// tell" costs a user nothing; saying "your router" during our own outage costs+// them an evening power-cycling working hardware, so every branch that claims+// `your_home` is asserted against a fleet that is provably fine.++import { describe, expect, it } from 'vitest';++import {+ CORRELATION_MIN_HOMES,+ fleetLooksCorrelated,+ TENANT_STALE_MS,+ tenantHealthVerdict,+} from '../api/_lib/home/health.js';+import { MIN_HOMES_FOR_A_VERDICT } from '../api/_lib/ops/home-health.js';++const NOW = Date.parse('2026-09-03T04:00:00.000Z');+const FRESH = new Date(NOW - 5_000).toISOString();+const OLD = new Date(NOW - TENANT_STALE_MS - 60_000).toISOString();++/** One house that is fine, in a fleet that is fine, as `readTenantHealth` shapes it. */+function signals(overrides = {}) {+ return {+ windowMinutes: 1440,+ home: {+ id: 'e4d0f6b2-0000-4000-8000-000000000001',+ label: 'Home',+ status: 'connected',+ statusDetail: null,+ lastOkAt: FRESH,+ lastErrorAt: null,+ ...(overrides.home || {}),+ },+ actions: {+ total: 12, ok: 10, refused: 2, failed: 0, lastFailedAt: null, timed: 12, p95LatencyMs: 380,+ ...(overrides.actions || {}),+ },+ confirmations: { total: 3, redeemed: 3, expired: 0, ...(overrides.confirmations || {}) },+ fleet: { live: 40, connected: 40, othersFailing: 0, ...(overrides.fleet || {}) },+ };+}++const verdict = (o) => tenantHealthVerdict(signals(o), { now: NOW });++describe('a healthy house', () => {+ it('says so, blames nobody, and offers no busywork', () => {+ const v = verdict();+ expect(v.state).toBe('live');+ expect(v.fault).toBe('none');+ expect(v.advice).toEqual([]);+ });++ it('counts a refused action as having gone the way it should', () => {+ // The gate stopping an unlock is the product working. A user must never+ // read their own safety gate as a fault in their house.+ expect(verdict().reason).toContain('12 of 12 actions');+ });++ it('does not invent activity for a quiet house', () => {+ const v = verdict({ actions: { total: 0, ok: 0, refused: 0, failed: 0, timed: 0, p95LatencyMs: null } });+ expect(v.state).toBe('live');+ expect(v.reason).toContain('No actions');+ });+});++describe('a house that has gone quiet', () => {+ it('is stale rather than offline, and does not guess whose fault that is', () => {+ const v = verdict({ home: { lastOkAt: OLD } });+ expect(v.state).toBe('stale');+ expect(v.fault).toBe('unknown');+ });++ it('keeps the last state on screen rather than telling the user it is gone', () => {+ expect(verdict({ home: { lastOkAt: OLD } }).advice.join(' ')).toContain('last state we saw');+ });+});++describe('a house that is genuinely down, in a fleet that is fine', () => {+ it('names the house as the fault and says what to check', () => {+ const v = verdict({ home: { status: 'unreachable', lastOkAt: OLD, lastErrorAt: FRESH } });+ expect(v.state).toBe('unreachable');+ expect(v.fault).toBe('your_home');+ expect(v.advice.length).toBeGreaterThan(0);+ });++ it('prefers the real error the handshake recorded over a generic sentence', () => {+ const v = verdict({+ home: { status: 'unreachable', statusDetail: 'Connection refused on port 8123.', lastOkAt: OLD },+ });+ expect(v.reason).toBe('Connection refused on port 8123.');+ });++ it('separates a token being rejected from a house being unreachable', () => {+ // The two look identical to a user and have completely different fixes.+ // A rejected token means the house answered, which is the opposite of down.+ const v = verdict({ home: { status: 'auth_failed', lastOkAt: OLD } });+ expect(v.fault).toBe('your_home');+ expect(v.headline).toContain('rejected');+ expect(v.advice.join(' ')).toContain('long-lived access token');+ });+});++describe('a house that is down because we are down', () => {+ const outage = { fleet: { live: 40, connected: 8, othersFailing: 30 } };++ it('takes the blame instead of sending the user to their router', () => {+ const v = verdict({ ...outage, home: { status: 'unreachable', lastOkAt: OLD } });+ expect(v.fault).toBe('us');+ expect(v.advice.join(' ')).toContain('Nothing to do');+ });++ it('covers a house that has merely gone quiet, not only one marked unreachable', () => {+ expect(verdict({ ...outage, home: { lastOkAt: OLD } }).fault).toBe('us');+ });++ it('does not blame our outage for a home the user disconnected themselves', () => {+ // A revoked home has no token at all. Telling its owner "this one is us"+ // during an unrelated outage would be a lie they might act on.+ const v = verdict({ ...outage, home: { status: 'revoked', lastOkAt: OLD } });+ expect(v.state).toBe('revoked');+ expect(v.fault).toBe('none');+ });++ it('leaves a healthy house alone even while the fleet is burning', () => {+ expect(verdict({ ...outage }).fault).toBe('none');+ });+});++describe('deciding whether it is us', () => {+ it('refuses to call it an outage on a fleet too small to have a share', () => {+ // Three of four houses failing is far more likely to be one person's three+ // test instances on one dead laptop.+ expect(fleetLooksCorrelated({ live: MIN_HOMES_FOR_A_VERDICT - 1, othersFailing: 3 })).toBe(false);+ });++ it('refuses to call two unlucky houses an outage', () => {+ expect(fleetLooksCorrelated({ live: 40, othersFailing: CORRELATION_MIN_HOMES - 1 })).toBe(false);+ });++ it('calls it when a large share of a big enough fleet is failing at once', () => {+ expect(fleetLooksCorrelated({ live: 40, othersFailing: 30 })).toBe(true);+ });++ it('does not call a handful of failures across a large fleet an outage', () => {+ expect(fleetLooksCorrelated({ live: 400, othersFailing: 5 })).toBe(false);+ });+});++describe('a home that never finished connecting', () => {+ it('is reported as still setting up rather than as broken', () => {+ const v = verdict({ home: { status: 'pending', lastOkAt: null } });+ expect(v.state).toBe('pending');+ expect(v.fault).toBe('unknown');+ });+});