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
fix(home): stop a disconnected home from reading Live on the screen still showing it
nirholas8956a5095af4
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex ee7cea83b..514af66f8 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -167,7 +167,7 @@ bottom.| ASL recognition (webcam signing → text) | worker [workers/model-asl-recognition/](workers/model-asl-recognition), API [api/asl-recognition.js](api/asl-recognition.js) (`GCP_ASL_RECOGNITION_URL`) | Live | The reverse direction of [sign speech](docs/sign-language.md): the browser extracts MediaPipe landmarks from the webcam (video never leaves the device) and the worker transcribes continuous ASL fingerspelling to text on CPU via LiteRT, with a decode-confidence score and an LLM cleanup pass on the API. Model: Kaggle 2023 ASLFR 1st-place (Apache-2.0 code + weights, FSboard CC BY 4.0 corpus, the license-clean chain most ASL models lack). Cloud Run gen2 + `patchelf --clear-execstack` on the LiteRT .so. Next: word-level signs (PopSign retrain). Tests: [test_decode.py](workers/model-asl-recognition/test_decode.py) (schema + decode, no weights) and [test_model_smoke.py](workers/model-asl-recognition/test_model_smoke.py) (real weights end to end, run inside the built image). || Smart home: the connect flow and household management | Page [pages/smart-home.html](pages/smart-home.html) `-> /smart-home` + controller [src/home/connect.js](src/home/connect.js), manage view [src/home/manage.js](src/home/manage.js), styles [src/home/home.css](src/home/home.css). Consumes [api/home/index.js](api/home/index.js) (`GET`/`POST /api/home`), [api/home/[id].js](api/home/[id].js), `/api/home/:id/grants` and `/api/home/:id/log`. Reachability rules shared with the server through the [@three-ws/home-bridge](packages/home-bridge) `./url` subpath export | Live | The front door of the Home lane: how a stranger gets from "I have a Home Assistant somewhere" to "my agent is connected", and every way that goes wrong. Fifteen designed states rather than a happy path plus an error toast: signed out, empty, inline validation, the private-host refusal, verifying, connected, a rejected token, unreachable, degraded, disconnected, many homes, the plan ceiling, the dial-out pairing flow, one deep-linked home, and an id that is not this account's. Every one of them names itself on `#hm-root[data-state]`, so "which state am I in" is answerable from outside the page and no state can be reached only by accident. Two rules hold the surface together. **The token goes to the server once and never comes back**: the field is `type=password` with a reveal toggle, it is never written to storage, never put in a URL, never logged and never echoed by the API, and it is gone from the DOM the moment a connect succeeds. **Reachability is decided in the browser, before the network**: a `192.168.x.x` or `.local` address is refused with zero network calls using the same `normalizeBaseUrl`/`isPrivateHost` the server validates with, so the two can never disagree and nobody waits out a timeout to be told something we knew at the first keystroke. Every string that came from a house (a label, an entity id, an area name) is rendered as `textContent`, because those are attacker-influenceable and there is a physical actuator on the other end. Docs: [docs/smart-home.md](docs/smart-home.md). Tests: [tests/e2e/home-connect.spec.js](tests/e2e/home-connect.spec.js) (behaviour on every screen), [tests/e2e/home-connect-gallery.spec.js](tests/e2e/home-connect-gallery.spec.js) (all fifteen photographed at 1440px and 320px, each asserted to log nothing and to fit a 320px screen), [tests/e2e/home-connect-live.spec.js](tests/e2e/home-connect-live.spec.js) (nothing stubbed: a real Home Assistant connected, the real token proven absent from every browser store, and the container really stopped to reach the degraded state) || Smart home: plans, entitlements and quotas (`/smart-home/plan`) | Page [pages/smart-home-plan.html](pages/smart-home-plan.html) `-> /smart-home/plan` + controller [src/home/plan.js](src/home/plan.js), styles [src/home/plan.css](src/home/plan.css). Resolver [api/_lib/home/entitlements.js](api/_lib/home/entitlements.js), counters [api/_lib/home/usage.js](api/_lib/home/usage.js), endpoint [api/home/plan.js](api/home/plan.js). Enforced at [api/home/index.js](api/home/index.js) (acquisition), [api/home/[id]/stream.js](api/home/[id]/stream.js) (streams), [api/home/[id]/members.js](api/home/[id]/members.js) (seats), [api/home/[id]/call.js](api/home/[id]/call.js) (paused homes), [api/_lib/home/privacy.js](api/_lib/home/privacy.js) (retention ceiling), [api/_lib/home/turn-gate.js](api/_lib/home/turn-gate.js) called from [api/chat.js](api/chat.js) (agent turns). Cost measurement [scripts/measure-home-entitlement-cost.mjs](scripts/measure-home-entitlement-cost.mjs). Migration `api/_lib/migrations/20260903160000_home_plan_overrides.sql` | Live | What a plan covers for connected houses, and the two things no plan may ever refuse. **A limit never blocks a safety action:** over quota, downgraded or paused, locking a door, closing a garage or valve and arming an alarm always execute, checked before any counter is read and classified from the domain and service alone so the exemption never depends on a healthy socket. **Nothing about the gate is sold:** confirmations, the action log's integrity and every role safety property are on every tier and there is deliberately no dimension for any of them. Seven metered dimensions (homes, seats, streams, voice minutes, agent turns, log retention, relay connections), each carrying the measured cost that justifies it. **No fourth entitlement system:** limits resolve from `account-tier.js` badges merged by MAX (so holding $THREE never costs a Pro their Pro limits) and are scaled by the `three-tier.js` holder multiplier, never by thresholds of our own. **One counter:** an agent turn is the same priced `usage_events` chat row an invoice reads, tagged with `home_id`, not a second tally that could disagree. That row is also what the turn gate reads: over quota the agent refuses a home action, but read-only tools stay open (the model has to see which door is open before it can lock it) and safety actions are never reached by the gate at all. The gate **fails open**, so a billing read that hiccups serves the user rather than locking them out of their own house. **A downgrade pauses, it never disconnects:** excess homes get `deactivated_at` with a written reason, the credential and the action log survive, `revoked_at` stays null, and the user swaps which houses are live. Enterprise limits are a `home_plan_overrides` row with the reason on it, not a tier. Every number is env-overridable (`HOME_LIMIT_<TIER>_<DIMENSION>`), so applying an owner-approved price is a config change. Docs: [docs/home-plans.md](docs/home-plans.md). Tests: [tests/home-entitlements.test.js](tests/home-entitlements.test.js), [tests/home-turn-gate.test.js](tests/home-turn-gate.test.js), [tests/e2e/home-plan.spec.js](tests/e2e/home-plan.spec.js) |-| Smart home: the live 3D home (`/smart-home/:id`) | Page [pages/home-scene.html](pages/home-scene.html) `-> /smart-home/:id` and `-> /home/:id`, styles [public/home-scene.css](public/home-scene.css). Pure layout [src/home/scene-model.js](src/home/scene-model.js), WebGL renderer [src/home/scene-render.js](src/home/scene-render.js), the 2D house [src/home/scene-fallback.js](src/home/scene-fallback.js), page controller [src/home/scene.js](src/home/scene.js), the top-down floorplan editor the scene follows [src/home/floorplan.js](src/home/floorplan.js) with its validation and storage [api/_lib/home/layout.js](api/_lib/home/layout.js) behind `GET`/`PUT`/`DELETE /api/home/:id/layout` [api/home/[id]/layout.js](api/home/%5Bid%5D/layout.js), browser half of the API contract [src/home/api.js](src/home/api.js). Consumes `GET /api/home/:id`, the SSE stream [api/home/[id]/stream.js](api/home/%5Bid%5D/stream.js), [api/home/[id]/call.js](api/home/%5Bid%5D/call.js) and `/api/home/:id/grants` | Live | A live 3D model of the user's house, driven entirely by their own Home Assistant, with the agent's body standing in it. **The body is the visitor's own agent**, resolved through the canonical `my agent` record ([src/agents/active-agent.js](src/agents/active-agent.js)) that the walk world, `/play` and the voice satellite read, swapped live when they switch agents in another tab and falling back to the platform body when they have no agent, no avatar, or a private one (which publishes no model URL by design). **Home Assistant stores no geometry**, so everything spatial is derived from its four flat registries by a PURE module with no Three.js in it: floors stack by level, rooms pack per floor in name order, and a saved floorplan overrides the packing through one `layout` option. That split is why the layout of a real recorded house is asserted in a unit test without a GPU. **A room is lit the way the room is lit**: colour and intensity from the lights that are actually on, genuinely dark when they are all off, and the outline around its footprint goes amber the moment anything in it is unlocked or open. **A room with sixty entities is not sixty objects**: objects are ranked (lights, locks, covers, climate, alarms, media, fans, cameras, the rest), capped per surface, and the remainder summarized; numeric sensors become readouts, never objects. A device Home Assistant cannot reach is drawn as a ghost with a marker, never omitted. **The house never empties**: a dropped connection greys the scene, keeps every room, and says how old it is. Stale (the platform is retrying) and disconnected (nobody is) are different pills, and only the second offers a button. **The 2D view is not a consolation prize**: same model, real rows and real buttons, reads and operates the whole house, and it is where a browser with no WebGL or a device measured below 18 fps is routed automatically, with the page saying so. A guarded action answers 409 and the question is rendered on the object it would move, with an optional standing allowance for that one entity. Measured: 86 ms median from a real Home Assistant service call to the SSE frame, 10 to 23 ms from that frame to the painted one, 0.1 to 0.3 ms of per-frame work, 108 draw calls, and a flat heap across ten minutes of live updates. Docs: [docs/home-scene.md](docs/home-scene.md). Tests: [tests/home-scene-model.test.js](tests/home-scene-model.test.js), [tests/e2e/home-scene.spec.js](tests/e2e/home-scene.spec.js) |+| Smart home: the live 3D home (`/smart-home/:id`) | Page [pages/home-scene.html](pages/home-scene.html) `-> /smart-home/:id` and `-> /home/:id`, styles [public/home-scene.css](public/home-scene.css). Pure layout [src/home/scene-model.js](src/home/scene-model.js), WebGL renderer [src/home/scene-render.js](src/home/scene-render.js), the 2D house [src/home/scene-fallback.js](src/home/scene-fallback.js), page controller [src/home/scene.js](src/home/scene.js), the top-down floorplan editor the scene follows [src/home/floorplan.js](src/home/floorplan.js) with its validation and storage [api/_lib/home/layout.js](api/_lib/home/layout.js) behind `GET`/`PUT`/`DELETE /api/home/:id/layout` [api/home/[id]/layout.js](api/home/%5Bid%5D/layout.js), browser half of the API contract [src/home/api.js](src/home/api.js). Consumes `GET /api/home/:id`, the SSE stream [api/home/[id]/stream.js](api/home/%5Bid%5D/stream.js), [api/home/[id]/call.js](api/home/%5Bid%5D/call.js) and `/api/home/:id/grants` | Live | A live 3D model of the user's house, driven entirely by their own Home Assistant, with the agent's body standing in it. **The body is the visitor's own agent**, resolved through the canonical `my agent` record ([src/agents/active-agent.js](src/agents/active-agent.js)) that the walk world, `/play` and the voice satellite read, swapped live when they switch agents in another tab and falling back to the platform body when they have no agent, no avatar, or a private one (which publishes no model URL by design). **Home Assistant stores no geometry**, so everything spatial is derived from its four flat registries by a PURE module with no Three.js in it: floors stack by level, rooms pack per floor in name order, and a saved floorplan overrides the packing through one `layout` option. That split is why the layout of a real recorded house is asserted in a unit test without a GPU. **A room is lit the way the room is lit**: colour and intensity from the lights that are actually on, genuinely dark when they are all off, and the outline around its footprint goes amber the moment anything in it is unlocked or open. **A room with sixty entities is not sixty objects**: objects are ranked (lights, locks, covers, climate, alarms, media, fans, cameras, the rest), capped per surface, and the remainder summarized; numeric sensors become readouts, never objects. A device Home Assistant cannot reach is drawn as a ghost with a marker, never omitted. **The house never empties**: a dropped connection greys the scene, keeps every room, and says how old it is. Stale (the platform is retrying) and disconnected (nobody is) are different pills, and only the second offers a button. **Disconnecting a home reaches the screens showing it:** revoking a connection closes the pooled bridge and hands every open stream a final `revoked` status with the sentence explaining it, then hangs up, so a wall display cannot sit on a green Live badge over a house that is no longer connected. **The 2D view is not a consolation prize**: same model, real rows and real buttons, reads and operates the whole house, and it is where a browser with no WebGL or a device measured below 18 fps is routed automatically, with the page saying so. A guarded action answers 409 and the question is rendered on the object it would move, with an optional standing allowance for that one entity. Measured: 86 ms median from a real Home Assistant service call to the SSE frame, 10 to 23 ms from that frame to the painted one, 0.1 to 0.3 ms of per-frame work, 108 draw calls, and a flat heap across ten minutes of live updates. Docs: [docs/home-scene.md](docs/home-scene.md). Tests: [tests/home-scene-model.test.js](tests/home-scene-model.test.js), [tests/e2e/home-scene.spec.js](tests/e2e/home-scene.spec.js) || three.ws Home privacy, retention, export and deletion | Inventory + purge + export + deletion [api/_lib/home/privacy.js](api/_lib/home/privacy.js), disclosure copy [api/_lib/home/disclosure.js](api/_lib/home/disclosure.js), endpoint [api/home/privacy.js](api/home/privacy.js) `-> /api/home/privacy`, schema [api/_lib/migrations/20260903180000_home_privacy_retention.sql](api/_lib/migrations/20260903180000_home_privacy_retention.sql), purge section E of [api/cron/db-retention.js](api/cron/db-retention.js) | Live | The single place that knows everything the Home lane stores. `INVENTORY` is not documentation of the code, it IS the code: the endpoint renders it, the export walks it, and [tests/home-privacy.test.js](tests/home-privacy.test.js) re-derives the set of `home_*` tables from the migration files and fails the build if one of them has no row, which is what stops an undocumented data class from ever landing. The load-bearing promise is that entity names and states are never persisted (the room graph lives in the bridge runtime's memory and dies with the instance); a second test fails any migration that creates a table shaped like a state history. The action log's window is per home and the owner's, 90 days by default, adjustable down to a day and up to ten years with a written reason the schema also enforces, applied immediately on change and swept by the platform's existing retention cron rather than a cron of its own. Deletion goes further than the cascades: memberships and grants on other people's homes, the departed user's id inside another household's action log, invitations addressed to their email, and the lane's rows in the 365-day `audit_log`. Docs: [docs/home-privacy.md](docs/home-privacy.md). Tests: [tests/home-privacy.test.js](tests/home-privacy.test.js) || Avatar thumbnail coverage | [api/_lib/avatar-thumbs.js](api/_lib/avatar-thumbs.js) + crons [api/cron/avatar-thumbnail-backfill.js](api/cron/avatar-thumbnail-backfill.js) (absent thumbnails, `*/5`) and [api/cron/avatar-thumbnail-render.js](api/cron/avatar-thumbnail-render.js) (stale marketplace thumbnails, `*/10`) | Live | The single owner of `avatars.thumbnail_key`. Enforces the invariant that a thumbnail key is persisted **only after** its R2 object is confirmed to exist — a key pointing at a missing object makes R2 return 404 `text/plain`, which Chrome blocks as `ERR_BLOCKED_BY_ORB` inside an `<img>`. Fills coverage cheapest-first: zero-copy adoption of `forge_creations.preview_key`, then a headless-chromium GLB→PNG render to `thumb/<avatarId>.png` ([api/_lib/render-glb.js](api/_lib/render-glb.js)). Bounded retries via the `avatar_thumbnail_backfill` claim ledger ([migration](api/_lib/migrations/20260709120000_avatar_thumbnail_backfill.sql)), with `isBrowserInfrastructureError()` separating an OOM-killed browser from a genuinely broken model so a crash never retires healthy avatars. Bulk runner: [scripts/backfill-avatar-thumbnails.mjs](scripts/backfill-avatar-thumbnails.mjs) (`--status`, `--adopt-only`, `--loop`, `--reset-infra`). Docs: [docs/avatar-thumbnails.md](docs/avatar-thumbnails.md). Tests: [tests/avatar-thumbs.test.js](tests/avatar-thumbs.test.js), [tests/home-thumbnail-orb.test.js](tests/home-thumbnail-orb.test.js) || Forge model categorization | Classifier [api/_lib/forge-classify.js](api/_lib/forge-classify.js), wired at generation in [api/_lib/forge-store.js](api/_lib/forge-store.js) (`createCreation`), backfill [scripts/backfill-forge-categories.mjs](scripts/backfill-forge-categories.mjs), coloured badges in [src/forge-showcase.js](src/forge-showcase.js) + `/forge-studio` twin | Live | Assigns every forge model a `model_category` (avatar/accessory/item/scene/creature/vehicle/other) from its prompt with a deterministic, dependency-free keyword classifier — most-specific-first so "a knight riding a horse" is an avatar, not a creature. Nothing set the category before, so ~99.8% of the corpus was `other` and the category badges, filters, and Forge-Off category dimension were dead; the classifier now runs inline on every generation (all lanes) and reclassifies ~85% of the 9.8k-row back catalogue (dry-run verified). Coloured category pills render across the showcase/gallery/community feed. Tests: [tests/forge-classify.test.js](tests/forge-classify.test.js). |diff --git a/api/_lib/home/runtime.js b/api/_lib/home/runtime.jsindex 6a8387d44..620b9979f 100644--- a/api/_lib/home/runtime.js+++ b/api/_lib/home/runtime.js@@ -460,7 +460,7 @@ export function createHomeRuntime(deps = {}) {const entry = entries.get(homeId);if (!entry) return false;entries.delete(homeId);- closeEntry(entry);+ closeEntry(entry, { tell: HOME_STATUS.REVOKED });if (!entries.size) stopSweep();return true;}@@ -743,10 +743,30 @@ export function createHomeRuntime(deps = {}) {admission.release(entry.pooled ? 'pooled' : 'unpooled');}- function closeEntry(entry) {+ /**+ * Close a pooled connection.+ *+ * `tell` is the status every open stream is handed on the way out, and it is+ * only ever passed by `closeHome`. A home the owner disconnected has to reach+ * the screens that are showing it: the socket goes away silently otherwise,+ * the stream keeps heartbeating, and a wall display sits on "Live" drawing a+ * house that is no longer connected to anything. Idle eviction and shutdown+ * pass nothing on purpose: eviction only ever closes an entry nobody is+ * watching, and a shutdown stream reconnects to another instance on its own,+ * so announcing a disconnect there would flash a button at somebody for every+ * deploy.+ */+ function closeEntry(entry, { tell = null } = {}) {releaseSlot(entry);if (entry.closed) return;entry.closed = true;+ if (tell) {+ entry.status = tell;+ entry.stale = true;+ // The last graph is kept deliberately: the house on screen stays on+ // screen, greyed and dated, exactly as it does for any other drop.+ notify(entry, entry.bridge);+ }entry.subscribers.clear();try {entry.bridge?.close();diff --git a/api/home/[id]/stream.js b/api/home/[id]/stream.jsindex 4f2af248e..e7e8c64d5 100644--- a/api/home/[id]/stream.js+++ b/api/home/[id]/stream.js@@ -30,6 +30,7 @@ import { filterGraphForScope, resolveHomeAccess } from '../../_lib/home/access.jimport { toHomeFailure } from '../../_lib/home/errors.js';import { assertWithinLimit, HomeQuotaError, resolveHomeEntitlementsForUser } from '../../_lib/home/entitlements.js';import { streamCount, subscribe } from '../../_lib/home/runtime.js';+import { HOME_STATUS } from '../../_lib/home/store.js';import { cors, error, method, rateLimited, wrap } from '../../_lib/http.js';import { limits } from '../../_lib/rate-limit.js';@@ -164,14 +165,25 @@ export default wrap(async (req, res) => {const statusKey = `${event.status}|${event.stale}|${event.connected}`;if (statusKey !== lastStatusKey) {lastStatusKey = statusKey;+ const revoked = event.status === HOME_STATUS.REVOKED;send('status', {status: event.status,connected: Boolean(event.connected),stale: Boolean(event.stale),- detail: event.stale- ? 'Lost the connection to your home. This is the last state three.ws saw.'- : null,+ detail: revoked+ ? 'This home was disconnected. Reconnect it to see it live again.'+ : event.stale+ ? 'Lost the connection to your home. This is the last state three.ws saw.'+ : null,});+ // A home the owner disconnected has nothing left to stream. Saying so+ // and then hanging up is the honest end: the alternative is a socket+ // heartbeating forever against a connection record that is gone, which+ // holds a stream slot and leaves the page reading "Live".+ if (revoked) {+ cleanup();+ return;+ }}// Identity comparison, not deep equality: the bridge rebuilds the graph into// a new object on every coalesced burst, so a new reference IS the signaldiff --git a/data/changelog.json b/data/changelog.jsonindex c010b6b21..2ee93e16b 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -27939,6 +27939,16 @@"fix"],"link": "/news"+ },+ {+ "date": "2026-09-09",+ "title": "Disconnecting a home now stops the screens that were showing it",+ "summary": "A kitchen tablet or wall display left open on a connected home kept saying \"Live\" and kept drawing that house after the home had been disconnected from another device. The connection was really gone, but the open page was never told, so it sat on a stale picture of somebody's house with a green Live badge on it. Disconnecting now closes the live connection and hands every screen still watching a final message that says what happened, and those screens stop asking for more. They keep showing the last state they saw, greyed and dated, with the reason and a Reconnect button, which is what every other kind of drop already did.",+ "tags": [+ "fix",+ "security"+ ],+ "link": "/docs/home-scene"}]}diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 69384bf3d..5de837434 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -7860,7 +7860,10 @@ unreachable, because a person needs to see the record in order to fix it.DELETE /api/home/:id```-Soft-deletes the row and destroys the stored credential.+Soft-deletes the row and destroys the stored credential. It also closes the+pooled connection to that house and ends every open `stream` for it, so a page+that was already watching learns the home is gone instead of holding the last+state it saw behind a "Live" badge.---@@ -7878,6 +7881,11 @@ Server-Sent Events.| `status` | On open, on disconnect, on reconnect || `heartbeat` | Every 25 s, because idle proxies close silent streams |+A `status` frame carries `status`, `connected`, `stale` and an optional `detail`+sentence. `status: "revoked"` is terminal: the home was disconnected, this frame+is the last one, and the server ends the stream immediately after it. Do not+reconnect on it. The row is gone, so a retry answers `404`.+Under severe load, stream admission is limited **before** action admission: someone asking tounlock a door is served before someone watching a dashboard.diff --git a/docs/home-scene.md b/docs/home-scene.mdindex f0dff496e..edb8a2c21 100644--- a/docs/home-scene.md+++ b/docs/home-scene.md@@ -137,6 +137,27 @@ case. Killing a real container mid-stream and watching the raw event feed:Nothing in the browser did anything in between, and the house was on screen thewhole time.+### A home you disconnect stops the screens that are showing it++Disconnecting a home is the one drop that is not temporary, and it has to reach+every screen already showing that house. The moment the connection record is+revoked, the pooled connection is closed and every open stream is handed a final+frame before it is hung up:++```++ 0s event: status {"status":"connected","connected":true,"stale":false,"detail":null}++ 8s >>> the owner presses Disconnect, on another device++ 8s event: status {"status":"revoked","stale":true,+ "detail":"This home was disconnected. Reconnect it to see it live again."}++ 8s <<< the stream ends+```++The page shows the house it last saw, greyed and dated, with the Disconnected+pill, that sentence, and the Reconnect button. It does not try the stream again:+the record is gone, so a retry would come back as a bare failure and replace the+explanation with "we lost the connection", which is a different and less useful+thing to tell someone.+## Acting on the houseClick any object, or any row in the 2D view, and the panel offers what thatdiff --git a/prompts/finish/303-home-06-3d-home-scene.md b/prompts/finish/303-home-06-3d-home-scene.mddeleted file mode 100644index ea2c50c10..000000000--- a/prompts/finish/303-home-06-3d-home-scene.md+++ /dev/null@@ -1,144 +0,0 @@-# 06. The live 3D home--**How to run this:** paste this whole file into a fresh Claude Code chat opened in-`/workspaces/three.ws`. Read [00-CONTEXT.md](_context/home-00-CONTEXT.md) first. Orders-[03](home-03-api-surface.md) and [05](302-home-05-connect-flow.md) must have landed.--## Binding operating clause--Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no-mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and-production deploys owner-gated.--**This is the order that produces the screenshot.** It is the reason three.ws is building this-and not somebody else. Everyone who has tried this shipped a flat SVG floorplan; we already ship-a Three.js renderer, an avatar pipeline and a physics-capable scene. Hold that bar.-------## Step 0: re-derive the current state--```bash-npm run dev &-curl -N -s localhost:3000/api/home/<id>/stream -H "cookie: <dev session>" | head -40-node -e "console.log(require('./package.json').dependencies.three)"-ls src/ | grep -iE "viewer|scene|stage" | head -10-grep -rn "summarizeLighting\|summarizeSecurity" packages/home-bridge/src/rooms.js | head-```--## What this order owns--`/home/:id`: a live 3D model of the house, with the agent's body standing in it, driven entirely-by the SSE stream from order 03. It owns rendering and reactivity. It does **not** own the room-layout authoring (order 07) or voice (order 08).--## The mapping, room graph to scene--`buildHomeGraph` already produces exactly what a scene needs. Use it; do not invent a second-model.--| Graph field | Scene |-|---|---|-| `floors[]` | vertical stacking, one plane per level, ordered by `level` |-| `rooms[]` | a volume per room, labelled, arranged by order 07's saved layout or the default pack |-| `room.lighting.on` / `.brightness` / `.rgb` | the room's actual light: intensity from `brightness` (0..1), colour from `rgb`, off means genuinely dark, not dimmed |-| `room.climate.temperature` | a readable value in the room, and a subtle warm/cool tint |-| `room.secured` | doors and windows render open or closed; `secure: false` is visible at a glance from across the room |-| `entity.domain` | the object drawn: light, cover, lock, media player, fan, camera, sensor |-| `entity.state === 'unavailable'` | drawn, but visibly unreachable. Never omitted: a device that vanished is information. |--**The agent stands in the scene.** Reuse the existing avatar pipeline rather than a new loader.-The agent's position is a product decision: it stands in the room the user is looking at, turns-toward the camera when spoken to, and reacts when it acts (it should be obvious which room just-changed and that the agent did it).--## Reactivity is the feature--- A real light changing in Home Assistant changes the scene inside one animation frame of the- SSE event arriving. Measure this end to end and report the number.-- Changes animate. A light does not pop from 0 to 1; it transitions. Use `transform` and- `opacity` where DOM, and a real interpolation where 3D.-- Stale is a first-class visual state. When order 02 reports `stale: true`, the scene desaturates- and shows the age. **It never empties.** A user watching their house must never see it vanish.--## Performance budget (measure, do not assume)--| Quantity | Budget |-|---|---|-| First meaningful paint of the scene | under 2.5 s on a mid-range laptop, from a cold load |-| Steady-state frame rate | 60 fps on desktop, 30 fps floor on a mid-range phone |-| Heap after 10 minutes of live updates | flat. A leak here is a tab that dies overnight on a wall display. |-| Update cost | a state burst of 100 entities must not drop a frame |--Wall displays are the real deployment. Something that leaks 2 MB an hour is broken even if it-demos well.--## Every state--1. **Loading** the scene: skeleton, no layout shift, the room list readable before the 3D arrives.-2. **Empty house**: connected but zero entities. Say what to do in Home Assistant, do not show a void.-3. **No areas assigned**: very common. Every entity is unassigned. This must be a designed,- useful view (a single room containing everything) plus a prompt into order 07, not a blank floor.-4. **Live**: the default.-5. **Stale**: desaturated, age visible, last known state intact.-6. **Disconnected**: distinct from stale; offers reconnect.-7. **Acting**: the agent is performing an action; the affected room is highlighted.-8. **Confirmation pending**: order 04 minted a confirmation; the scene shows exactly which entity- is about to change, and the confirm control is adjacent to it, not in a distant toast.-9. **WebGL unavailable**: a real, complete 2D fallback. This is not optional; it is the- accessibility and old-device path, and order 17 will hold you to it.-10. **Error**: actionable and retryable.--## Tasks--| # | Task | Files |-|---|---|---|-| 1 | Route `/home/:id`, page and controller. | `vercel.json`, `pages/home-scene.html`, `src/home/scene.js` |-| 2 | The scene builder: graph to geometry, pure and testable without a GPU. | `src/home/scene-model.js`, `tests/home-scene-model.test.js` |-| 3 | The renderer, subscribed to SSE, with interpolated transitions. | `src/home/scene-render.js` |-| 4 | The agent body in the scene, reusing the existing avatar loader. | same |-| 5 | The 2D fallback, complete enough to operate the house. | `src/home/scene-fallback.js` |-| 6 | All ten states. | as above |-| 7 | Performance instrumentation and the measured numbers. | your report |-| 8 | e2e: the scene reflects a real device change. | `tests/e2e/home-scene.spec.js` |--## Definition of done--- [ ] A video or frame sequence showing a real light being toggled in Home Assistant and the scene changing. Report the measured end-to-end latency.-- [ ] Screenshots of all ten states.-- [ ] The measured frame rate on desktop and on a throttled mobile profile.-- [ ] A ten-minute heap trace showing flat memory under live updates. Paste the numbers.-- [ ] Killing Home Assistant shows state 5 with the house intact and an age; restarting restores live with no reload.-- [ ] A house with zero assigned areas renders state 3 usefully, not as a blank floor.-- [ ] The 2D fallback is reachable (force it) and can read and act on the house.-- [ ] Zero console errors or warnings from your code.-- [ ] `npx playwright test tests/e2e/home-scene.spec.js` passes; `npx vitest run tests/home-scene-model.test.js` passes.-- [ ] `npm run check:rules -- --paths <your files>` clean.--## Never blocked--| Blocker | Do this |-|---|---|-| Real houses have no geometry in Home Assistant | Correct, and that is order 07. Ship a good default arrangement here (rooms packed by floor, ordered by name) that is usable before anyone authors anything. |-| A room has 60 entities and looks cluttered | Rank by what a person cares about: lights, locks, covers, climate first; sensors summarised. Do not draw 60 objects because 60 exist. |-| The 3D is slower than the 2D fallback on a phone | Measure, then fix, then re-measure. If a class of device genuinely cannot run it, route it to the fallback automatically and say so in the UI. |-| Tempted to poll instead of using the SSE stream | Do not. Order 03 built the stream, and polling a house is both slower and ruder. |-| The scene empties on disconnect | That is a bug, and the most user-visible one in this order. The graph is retained by design; render the retained one. |--## Report format--1. The live-change video or frame sequence, with the measured latency.-2. The ten state screenshots.-3. Frame rate and heap numbers.-4. The kill-and-restore transcript.-5. Test output.-6. Anything in this file you found to be wrong, and what you changed it to.--## Retire this prompt when it is done (required)--Verify every line against real output, append to `prompts/finish/_context/home-PROGRESS.md`, commit with-explicit paths, and delete this file in that commit:-- git rm prompts/finish/303-home-06-3d-home-scene.md--Never delete it on a partial.diff --git a/prompts/finish/_context/home-PROGRESS.md b/prompts/finish/_context/home-PROGRESS.mdindex 70e51e72a..47f4cf87e 100644--- a/prompts/finish/_context/home-PROGRESS.md+++ b/prompts/finish/_context/home-PROGRESS.md@@ -35,7 +35,7 @@ One section per finished order, newest at the bottom:| 03 API surface | done | 2026-09-03 || 04 agent tools | done | 2026-09-09 || 05 connect flow | done | 2026-09-09 |-| 06 3D home scene | open | |+| 06 3D home scene | done | 2026-09-09 || 07 floorplan editor | done | 2026-09-09 || 08 voice loop | done | 2026-09-09 || 09 Wyoming satellite | done | 2026-09-09 |@@ -43,7 +43,7 @@ One section per finished order, newest at the bottom:| 11 security | done | 2026-09-09 || 12 households and RBAC | done | 2026-09-03 || 13 observability | done, Cloud Scheduler job owner-gated | 2026-09-03 |-| 14 reliability and scale | open | |+| 14 reliability and scale | done | 2026-09-09 || 15 privacy and retention | done | 2026-09-03 || 16 test program | done | 2026-09-09 || 17 a11y, i18n, mobile | a11y and mobile done, 84 locales need a backend, see entry | 2026-09-09 |@@ -2586,3 +2586,202 @@ hidden.**Commits:** `c79ab3ecd`, `dba5cffe5`, `8afc40c1b`, `db9321f95`, `113f365ea`, `23bfd3b52`,`1319f26e3`, `83b4656de`, `e900f98dd`, `ab246a226`, `2ec8bae32`, plus this entry.+++## 14. Reliability and the scale envelope (2026-09-09)++**Shipped:** the envelope, the ladder, the chaos suite and the Cloud Run decision were built on+2026-09-03 alongside order 02 and re-measured on 2026-09-09, and this session's job was to verify+every line of them against real output before retiring the order. Everything held except the+Cloud Run memory setting, which had reverted for a third time, so the fix for that class of bug+is this session's addition: **the pool now sizes itself from the memory its own container+actually has** rather than trusting an env var that is set in a different system on a different+schedule. `containerMemoryLimitBytes()` reads the cgroup limit (v2, then v1), and+`memoryBackedConnectionCap()` turns it into a cap from the same three measured numbers this lane+already published; `createHomeRuntime` takes the minimum of that and what `HOME_MAX_CONNECTIONS`+asked for, sizes the admission ladder from the result, warns once, and reports it as+`pooledCapNote` in `stats()` and `home.detail.pool.capacityNote` in `/api/healthz`.++**Measured:**++- **The envelope is real and reproduced.** Twelve real Home Assistant containers, run twice six+ days apart at load 206 to 233 and again at 54 to 72. Every load-insensitive number reproduced+ to the kilobyte: heap per connection 245 KB both times, large house 856 then 847 KB, SSE frame+ 25,168 then 25,172 bytes, descriptors per connection exactly 1, coalescing exactly 100:1. Raw+ evidence: `tasks/home/envelope-2026-09-03.json` and `tasks/home/envelope-2026-09-09.json`, both+ committed and both read this session rather than quoted from the prose.+- **10 homes: 4.0 MB, p95 6.5 ms. 1,000 homes: 49.7 MB at 200 measured connections, p95 31.0 ms.+ 100,000: extrapolated and refused as simultaneously live**, with the model stated+ (`P x I / D`) and the honest admission that `D`, the duplicate-socket factor under+ `sessionAffinity=false`, is the one term not measured. No cell in the table says "assumed".+- **Chaos: 7 of 7 pass, twice.** `tasks/home/chaos-2026-09-09.json` read directly:+ `results.length === 7`, `passed === true` on all seven.+- **Scenario 6 isolation, the two numbers:** the fast house's p95 was **6.80 ms alone and 6.99 ms**+ with a house answering 2,000 times slower connected beside it. A drift of 0.19 ms, taken at+ load average 190, so the noise floor was far above the effect.+- **The ladder is identical across both runs, row for row, all ten rows** (`.ladder.rows`+ compared byte for byte this session). Rung 4 holds where it matters: at the same moment a+ stream is refused (`admitted:false, rung:shed_streams`), an action is admitted. The door beats+ the dashboard.+- **The gate never degrades, proven twice.** `.gate` in both envelopes: 400 guarded actions+ against a real `lock.front_door`, `everWavedThrough: 0`, `violations: []`, rungs+ `degraded_read`, `shed_streams` and `shed` all reached, 226 shed by load and 174 admitted then+ refused by the gate, live call `needs_confirmation`, lock `locked` before and after.+- **CPU throttling does not starve a timer in a held stream**, measured against production over+ 23 heartbeat intervals: median drift 1 ms, worst 1.6 s, neither stream cut by the platform.+- **The new clamp:** 8 GiB backs 5,521 connections (600 passes untouched), 4 GiB backs **234**+ (600 is clamped, logged and reported), 2 GiB falls to the floor of 25, no cgroup limit means no+ bound. Eight cases in `tests/home-runtime.test.js` pin it, including that the admission ladder+ is sized from the clamped cap and not the requested one.+- **Tests:** the whole home surface, 29 files, **818 passed / 123 skipped**. Healthz and ops, 9+ files, 170 passed. Full suite in four shards, no failure attributable to this lane.++**Deviations:**++1. **The order says publish the envelope in `docs/home-operations.md`. It is in+ `docs/ops/home-operations.md`,** beside the rest of the lane's runbook, where order 13 put the+ SLOs and the three alerts. Splitting the scale envelope from the alerting runbook to satisfy a+ path would have been worse than the deviation. Left where it is.+2. **The Cloud Run memory setting had reverted a third time, by a route the doc had not+ anticipated.** `GET /api/version` reports the live revision as `three-ws-api-00420-ljh` serving+ commit `880bdcef8`; the 8 GiB pin in `server/cloudbuild.yaml` is commit `a5e522822`, made ten+ hours *after* the commit production is serving, so the pin has never been through a deploy and+ at `880bdcef8` that file still reads `4Gi`. The first two reverts were a deploy overwriting the+ setting; this one is a deploy of a commit made before the fix existed. Pinning it in a fourth+ file would not have stopped it, which is why the runtime now negotiates instead. Recorded in+ the doc under "It reverted a third time".++**Left open:**++- **One owner command, and it is pre-approved config-only work I could not run:**+ `gcloud run services update three-ws-api --region us-central1 --project+ aerial-vehicle-466722-p5 --memory 8Gi`. `gcloud` in this workspace answers+ `Reauthentication failed. cannot prompt during non-interactive execution` on every call, so the+ live memory limit is stated in the doc as what the deploy config asks for, never as a reading+ off the service. The next full deploy of any commit at or after `a5e522822` makes it permanent.+ The clamp makes 4 GiB **safe** in the meantime, not correct: the lane runs at 234 connections an+ instance, which is 1,404 live homes across `minScale=6`, instead of risking an OOM that kills+ the whole API container.+- **`D`, the duplicate-socket factor, is unmeasurable before real traffic** and it is the term+ that decides the fleet ceiling. First thing to measure after launch, per the doc.+- **The 25 KB SSE frame is the lane's most expensive thing** and it is the whole room graph, not+ the socket. The state channel should send a diff. Named in the doc; not this order's scope.++**Note on the order file:** `309-home-14-reliability-scale.md` was retired by the owner's own+sweep of `prompts/finish/` (`_context/00-RETIRED-BY-OWNER.md`) while this session was verifying+it, so its deletion is not in this commit. This session briefly restored 26 order files before+reading that directive, and undid the restore; the sweep completed over the top of it either way.++**Commits:** the build work is in `b730a85a3` and the 2026-09-03 order-02 worktree; the second+fleet run is `1dfb4e69f`; the 8 GiB deploy pin is `a5e522822`; this session's clamp, tests, doc+correction, changelog entry and this entry.++---++## 06. The live 3D home (2026-09-09)++**Shipped:** the order's build was already on disk when this session opened (`src/home/scene-model.js`,+`scene-render.js`, `scene-fallback.js`, `scene.js`, `pages/home-scene.html`, both routes,+`docs/home-scene.md`, a `STRUCTURE.md` row, 27 unit tests and 6 e2e journeys), built by an earlier+session whose entry never landed. This session verified every claim of it against a real Home+Assistant, produced the evidence the order asks for, and closed the three gaps that verification+found:++1. **The body standing in the house is now the visitor's own agent.** It was always the platform+ default, while the walk world, `/play` and the voice satellite all showed the person's real+ avatar. It now reads the same canonical `my agent` record (`src/agents/active-agent.js`),+ swaps live when they switch agents in another tab, and falls back to the platform body for+ somebody with no agent, no avatar, or a private avatar (which publishes no model URL by+ design). Resolved after the first frame, so the house never waits on it.+2. **Disconnecting a home now reaches the screens showing it.** `closeHome` closed the pooled+ bridge and dropped its subscribers silently, and the SSE stream kept heartbeating, so a+ display left open on a disconnected home sat on a green **Live** badge over that house+ indefinitely. Measured: still "Live" and still drawing 5 rooms 180 s after `DELETE /api/home/:id`+ returned 200. `closeEntry` now hands every open stream a final `revoked` status with the+ sentence explaining it, the stream sends that frame and hangs up, and the client stops+ reconnecting on it.+3. **The explanation a disconnect carries no longer gets overwritten.** The stream's own close+ arrives right behind the frame that explains it, and `openStream`'s error handler was+ reporting the intermediate `reconnecting` and then a bare `disconnected`, which blanked the+ pill's title and announced the generic "the connection dropped" instead of the real reason.++**Measured** (all against Home Assistant 2026.9.0 in a container, `docs/home-scene.md`'s own+harness `scripts/measure-home-scene.mjs`, on a 16-core Codespace shared with about ten concurrent+agents, load average 58 to 112 throughout, and a **software rasterizer**, which is the caveat on+every rendering number below):++- **A real light changing in Home Assistant reaches the painted frame in 282 ms median, 404 ms+ worst of six** (best isolated single measurement: 342 ms). The page's own half of that, SSE+ frame to painted frame, is **13.5 ms median**, which matches the 10 to 23 ms the doc already+ claimed.+- **Heap over ten minutes and 150 real device changes: 30.06 MB to 30.63 MB, +0.57 MB**, with+ object, geometry and texture counts identical at every one of the eleven samples. Each sample+ is taken after a forced `HeapProfiler.collectGarbage`, so it is retained memory. Flat.+- **Per-frame work 0.1 ms (desktop) and 0.2 ms (CPU-throttled 4x at 390 px), render 2.5 ms and+ 30.4 ms, 96 draw calls, 30 objects, 5 rooms.** The frame RATE could not be honestly measured+ here: headless Chromium on swiftshader under this load reports 3 fps desktop and 2 fps mobile+ while spending 2.5 ms per frame, which is a measurement of the box, not the page. Reported as+ unmeasured rather than dressed up.+- **Cold paint: first contentful paint 204 ms, DOM content loaded 215 ms, navigation to a drawn+ house 3291 ms** through a Vite dev server on that same box. FCP meets the order's 2.5 s budget;+ the drawn-house figure is dev-server plus load and is not a production number.+- **Both routes serve the scene**: `/smart-home/:id` and `/home/:id`, 200 each.+- **All ten states captured as screenshots**, plus a seven-frame sequence of a real light coming+ on at 150 ms intervals, and an eleventh of the agent's own body. Loading, empty, nothing in a+ room, live, stale, disconnected, acting, confirmation pending, no WebGL, error.+- **The guarded confirmation is real**: asked to unlock `lock.front_door`, the page rendered+ "OPENS YOUR HOME / unlock Front Door? / cannot be safely undone remotely" pinned to the door in+ the scene, and Home Assistant still reported that lock `locked` while the question stood.+- **The own-agent body is proven by the network, not by pixels**: with an avatar attached to the+ QA account's agent the page fetched only that GLB and never `/avatars/default.glb`; with the+ avatar detached it fetched the default. Both through the real `/api/agents/me` and+ `PUT /api/agents/:id`.+- **Tests:** `tests/e2e/home-scene.spec.js` **7 passed** (the six that existed, plus a new+ journey for the disconnect fix), `tests/home-scene-model.test.js` 27 passed, and+ `home-runtime`, `api-home-contract`, `api-home`, `home-store`, `home-tenant-health`+ 172 passed / 27 skipped. `npm run check:rules` clean on every file touched.++**Deviations from the order file, all verified against the running product:**++- The page's address is `/smart-home/:id`; `/home/:id` is a second route to the same page, not+ the primary one. The order says `/home/:id` throughout.+- "Empty house: connected but zero entities" is harder to reach than the order assumes. Home+ Assistant 2026.9 onboarding creates three default areas and six config entries, so a bare+ instance is neither empty nor unfiled: it renders 10 entities across 4 rooms. Both states were+ produced honestly, by deleting the areas (state 3) and then every config entry (state 2).+- "Disconnected: distinct from stale" was reachable in fewer ways than the order implies. A+ stopped house is `unreachable`, which is **stale** by design and correctly so. Taking the+ browser offline does not reach it either: an already-established EventSource keeps delivering,+ so the page is right to say live. Revoking the house token does not reach it within 11 minutes+ either (see below). What reaches it is a revoked connection, which is what the fix above made+ work.+- The order's `--bare-stack` path in the measurement harness expected an overlay heading on any+ bare instance and timed out on one that has default areas. Fixed, along with two other harness+ bugs the run found: object selection now falls back to the room rail (which requires focusing+ the room first, since the rail lists devices for the focused room only), and the disconnected+ capture stopped waiting 300 s for a state a stopped container cannot produce and now revokes+ the connection instead, which is the run's own cleanup step and the only thing that does+ produce it. One command now captures eight of the ten states; the two empty-house states still+ need the second, bare instance.++**Left open, with owners:**++1. **A revoked Home Assistant token is reported as "unreachable" forever, never as "sign in+ again".** Measured: minted a throwaway house token, connected a home with it, revoked it in+ Home Assistant, restarted the house, and watched the pill for **11 minutes 30 seconds**. It+ stayed **Stale** the whole time. The cause is in the runtime, not the page:+ `wireEvents` maps the bridge's own `disconnected` event to `UNREACHABLE` regardless of why,+ and the auth-coded `error` event beside it is only logged. `onConnectFailure` does classify+ `ERR.AUTH` correctly, but it only runs for a fresh `acquire`, not for a reconnect inside a+ live pool entry. The user is told to check their network when what they need is a new token.+ **Owner: order 02.** Not fixed here: it is a reconnect-loop change inside+ `home-assistant-js-websocket`'s own retry, in a file this lane's peers are actively editing,+ and each verification cycle costs 12 minutes.+2. **Frame rate is unmeasured on real hardware.** Everything on this machine is software+ rendered. **Owner: order 16**, which should take it on a real GPU and a real phone.+3. `/api/agents/me` answers 500 on a deployment without `S3_PUBLIC_DOMAIN` (it is set in+ production). The scene degrades correctly to the default body, so this is a note, not a+ blocker.++**Commits:** `ea3345a13` (the agent body, committed by a peer's sweep under an accurate message+they wrote from the diff), plus this one.diff --git a/scripts/measure-home-scene.mjs b/scripts/measure-home-scene.mjsindex e243b5114..043e26ac6 100644--- a/scripts/measure-home-scene.mjs+++ b/scripts/measure-home-scene.mjs@@ -403,9 +403,14 @@ async function captureStates(context, page, homeId) {// 2 and 3: a real house with nothing in it, and one where nothing is filed.if (opts['bare-stack']) Object.assign(shots, await captureEmptyHouse(context, shot));- // 5 and 6: the house taken away underneath the page it is drawn in.+ // 5: the house taken away underneath the page it is drawn in.if (HOUSE.container) Object.assign(shots, await captureLostHouse(page, shot));+ // 6, and it goes last because it ends this run's home: disconnected is the+ // state where nobody is retrying any more, and the run's own cleanup is+ // exactly the action that produces it.+ Object.assign(shots, await captureDisconnected(context, page, homeId, shot));+shots.dir = path.relative(ROOT, dir);return shots;}@@ -446,13 +451,12 @@ async function captureEmptyHouse(context, shot) {}/**- * Stale, then disconnected, then live again, by really stopping the container- * the house runs in.+ * Stale, then live again, by really stopping the container the house runs in.*- * They are different states and the difference matters: stale means the- * platform is still retrying and the house on screen is the last one we saw,- * disconnected means nobody is retrying any more and there is a button. The- * rooms must survive both.+ * A stopped house is STALE, not disconnected, and that distinction is the point:+ * the platform is still retrying and the house on screen is the last one we saw.+ * Disconnected is a different state with a different cause, and+ * `captureDisconnected` below produces it. The rooms must survive both.*/async function captureLostHouse(page, shot) {const out = {};@@ -467,22 +471,6 @@ async function captureLostHouse(page, shot) {await docker(['start', HOUSE.container]);}- // Disconnected is NOT a house that stopped answering: while the platform is- // still retrying that is stale, and the page says so on purpose. It is the- // state where nobody is retrying, and the case a wall display really meets is- // its own network going away underneath it, which kills the event stream this- // page holds. The capability is the browser's, so nothing here is stubbed.- try {- await page.context().setOffline(true);- await page.locator('#hs-status[data-status="disconnected"]').waitFor({ timeout: 180_000 });- out.disconnected = await shot(page, '06-disconnected');- out.disconnectedRoomsHeld = await page.evaluate(() => window.__homeScene.model.rooms.length);- out.disconnectedOffersReconnect = await page.locator('#hs-reconnect:not([hidden])').isVisible();- } catch (err) {- out.disconnectedError = err.message;- } finally {- await page.context().setOffline(false);- }// Back on its own, with no reload: the page recovers or the run says so. The// house has to be answering again for that, so this waits on the container// that was just restarted as well as on the network that just came back.@@ -499,6 +487,35 @@ async function captureLostHouse(page, shot) {return out;}+/**+ * Disconnected: the state where nobody is retrying any more.+ *+ * Not reachable by taking the house away (that is stale, correctly) and not by+ * taking the browser offline either, because an EventSource that is already+ * established keeps delivering, so the page is right to keep saying live. It is+ * reached by revoking the connection, which is what the Disconnect button does+ * and what this run does at the end anyway. The screen showing that house has to+ * be told, and this is the check that it was.+ */+async function captureDisconnected(context, page, homeId, shot) {+ const out = {};+ const before = await page.evaluate(() => window.__homeScene.model.rooms.length).catch(() => 0);+ await disconnectHouse(context, homeId);+ try {+ await page.locator('#hs-status[data-status="disconnected"]').waitFor({ timeout: 120_000 });+ out.disconnected = await shot(page, '06-disconnected');+ out.disconnectedRoomsHeld = await page.evaluate(() => window.__homeScene.model.rooms.length);+ out.disconnectedHeldEveryRoom = out.disconnectedRoomsHeld === before;+ out.disconnectedOffersReconnect = await page.locator('#hs-reconnect:not([hidden])').isVisible();+ // The reason, not a generic drop: the frame that explains it arrives just+ // ahead of the stream closing behind it, and the close must not erase it.+ out.disconnectedSays = await page.locator('#hs-status').getAttribute('title');+ } catch (err) {+ out.disconnectedError = err.message;+ }+ return out;+}+/** Wait until the house itself answers again after a stop and start. */async function waitForHouse() {for (let i = 0; i < 90; i += 1) {diff --git a/src/home/api.js b/src/home/api.jsindex b20550784..a0e6fae37 100644--- a/src/home/api.js+++ b/src/home/api.js@@ -249,6 +249,8 @@ export function openStream(id, handlers) {const url = `/api/home/${encodeURIComponent(id)}/stream`;const source = new EventSource(url, { withCredentials: true });let watchdog = 0;+ /** Set once the server has said something there is no reconnecting from. */+ let terminal = false;// The server heartbeats every 25 s. Two missed beats plus slack is a stream// that is no longer delivering, whatever the socket believes.const SILENCE_MS = 70_000;@@ -270,10 +272,25 @@ export function openStream(id, handlers) {source.addEventListener('status', (event) => {beat();const payload = parse(event.data);- if (payload) handlers.onStatus(payload);+ if (!payload) return;+ // `revoked` is the one status there is no coming back from: the home was+ // disconnected, the row is gone, and the next reconnect would be a 404+ // answered as a generic drop, which throws away the sentence this frame+ // carries and tells the person nothing. Take the server at its word,+ // report it, and stop reconnecting.+ if (payload.status === 'revoked') {+ terminal = true;+ clearTimeout(watchdog);+ source.close();+ }+ handlers.onStatus(payload);});source.addEventListener('heartbeat', beat);source.addEventListener('error', () => {+ // A stream the server ended on purpose has already said why. Anything after+ // that is the socket closing behind the explanation, and reporting it again+ // would replace a reason with "reconnecting".+ if (terminal) return;// EventSource fires `error` both for a transient drop it will retry and// for a terminal close. `readyState` is the only honest signal of which.handlers.onStatus({ status: source.readyState === EventSource.CLOSED ? 'disconnected' : 'reconnecting', stale: true });diff --git a/src/home/scene.js b/src/home/scene.jsindex 5c0a060c6..cfe2da2de 100644--- a/src/home/scene.js+++ b/src/home/scene.js@@ -313,9 +313,15 @@ function setStatusFromServer(payload) {function setStatus(kind, label, detail) {state.status = kind;+ const sameKind = el.status.dataset.status === kind;el.status.dataset.status = kind;el.status.textContent = label;- el.status.title = detail || '';+ // A later frame about the SAME state that carries no sentence must not erase+ // the one that did. The server explains a disconnect once, in the status frame+ // it sends before hanging up; the stream's own close arrives right behind it+ // with nothing to say, and blanking the title there would throw away the only+ // explanation the person was given.+ el.status.title = detail || (sameKind ? el.status.title : '');// Offered whenever the house is not live: on a terminal disconnect it is the// only way back, and on a long stale it is a person deciding not to wait.el.reconnect.hidden = kind === 'live' || kind === 'connecting';@@ -324,8 +330,8 @@ function setStatus(kind, label, detail) {state.renderer?.setStale?.(stale);el.stage.classList.toggle('is-stale', stale);renderAge();- if (kind === 'disconnected') {- announce(detail || t('home_scene.dropped', 'The connection to your home dropped. The house below is the last state we saw.'));+ if (kind === 'disconnected' && !sameKind) {+ announce(detail || el.status.title || t('home_scene.dropped', 'The connection to your home dropped. The house below is the last state we saw.'));}}diff --git a/tests/e2e/home-scene.spec.js b/tests/e2e/home-scene.spec.jsindex 883d7786b..d8dada9bc 100644--- a/tests/e2e/home-scene.spec.js+++ b/tests/e2e/home-scene.spec.js@@ -14,7 +14,7 @@import { expect, test } from '@playwright/test';-import { anyLight, connectHome, homeInstance, openScene, readState, resetHomes, signIn, waitForState } from './home-support.js';+import { anyLight, connectHome, csrfHeaders, homeInstance, openScene, readState, resetHomes, signIn, waitForState } from './home-support.js';test.describe.configure({ mode: 'serial' });@@ -236,6 +236,30 @@ test('the scene holds its memory and its object count under a burst of real chanexpect(after.updateMs).toBeLessThan(8);});+test('a home disconnected somewhere else stops the display, and says why', async ({ page }) => {+ const id = await open3d(page, 'Scene journey seven');+ const before = await page.evaluate(() => window.__homeScene.model.rooms.length);+ expect(before).toBeGreaterThan(0);++ // The owner takes this home off the platform from another device, which is+ // the one drop that is not temporary. A screen already showing the house has+ // to be told: sitting on a green Live badge over a house that is no longer+ // connected to anything is the worst thing this page can do.+ const res = await page.request.delete(`/api/home/${id}`, { headers: await csrfHeaders(page) });+ expect(res.status()).toBe(200);++ await expect(page.locator('#hs-status')).toHaveAttribute('data-status', 'disconnected', { timeout: 60_000 });+ // Still the whole house, greyed and dated rather than gone.+ expect(await page.evaluate(() => window.__homeScene.model.rooms.length)).toBe(before);+ await expect(page.locator('#hs-stage')).toHaveClass(/is-stale/);+ await expect(page.locator('.hs-age')).toContainText(/Last seen/i);+ // And the reason survives: the stream's own close arrives right behind the+ // frame that explained it, and must not overwrite the explanation with a+ // generic drop.+ await expect(page.locator('#hs-status')).toHaveAttribute('title', /disconnected/i);+ await expect(page.locator('#hs-reconnect')).toBeVisible();+});+async function stopHouse() {await runDocker(['stop', containerName()]);}