Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(home): stop one flapping house killing every other house on the instance

nirholasae3dfdcdda62
diff --git a/api/_lib/home/runtime.js b/api/_lib/home/runtime.js
index 566a97123..a1ada77f4 100644
--- a/api/_lib/home/runtime.js
+++ b/api/_lib/home/runtime.js
@@ -768,6 +768,13 @@ function withTimeout(promise, ms, makeError) {
const timeout = new Promise((_resolve, reject) => {
timer = setTimeout(() => reject(makeError()), ms);
});
+ // The loser of this race still settles. A connect that rejects AFTER its
+ // timeout already fired would otherwise be an unhandled rejection, and under
+ // Node's default --unhandled-rejections=throw an unhandled rejection
+ // terminates the process: one house that fails slowly would take every other
+ // house on the instance down with it. `Promise.race` observes the winner
+ // only, so the loser needs its own handler.
+ promise.then(undefined, () => {});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
diff --git a/docs/upstream/home-assistant-js-websocket-resubscribe-rejection.md b/docs/upstream/home-assistant-js-websocket-resubscribe-rejection.md
new file mode 100644
index 000000000..fa07045fb
--- /dev/null
+++ b/docs/upstream/home-assistant-js-websocket-resubscribe-rejection.md
@@ -0,0 +1,128 @@
+# Upstream report: a flapping connection crashes the process
+
+**Package:** [`home-assistant-js-websocket`](https://github.com/home-assistant/home-assistant-js-websocket)
+**Version reproduced against:** 9.6.0
+**Severity:** a server holding connections to many Home Assistant instances is
+terminated by one of them flapping.
+**Status:** written 2026-09-03, ready to file. Worked around in
+[`packages/home-bridge/src/bridge.js`](../../packages/home-bridge/src/bridge.js)
+(`guardSubscriptions`) so three.ws is safe today.
+
+---
+
+## Summary
+
+`Connection` re-establishes its subscriptions after a reconnect and attaches no
+rejection handler to the promise it creates. If the socket drops again while a
+resubscribe command is in flight, that command rejects, the rejection is never
+observed, and Node terminates the process under its default
+`--unhandled-rejections=throw`.
+
+In a browser this is a console error. In a Node server holding one connection per
+tenant, **one flapping instance kills every other tenant's connection in the same
+process.**
+
+## Where
+
+`dist/connection.js`, in `_setSocket`, on reconnect:
+
+```js
+oldSubscriptions.forEach((info) => {
+ if ("subscribe" in info && info.subscribe) {
+ info.subscribe().then((unsub) => { // <- no .catch
+ info.unsubscribe = unsub;
+ info.resolve();
+ });
+ }
+});
+```
+
+`info.subscribe` is `() => this.subscribeMessage(callback, subscribeMessage, options)`,
+which rejects when the command comes back `success: false` or when the socket
+closes with the command outstanding.
+
+A second, smaller instance of the same shape is in `dist/collection.js`:
+
+```js
+if (subscribeUpdates) {
+ unsubProm = subscribeUpdates(conn, store); // <- promise, never caught
+}
+...
+if (unsubProm) unsubProm.then((unsub) => { unsub(); }); // <- no .catch either
+```
+
+## How it was reproduced
+
+Against a real Home Assistant (`ghcr.io/home-assistant/home-assistant:stable`,
+reporting `2026.9.0`) rather than a mock, with a TCP proxy in front of the
+container that closes every socket and refuses new ones on command:
+
+1. Open a connection through the proxy and `subscribeEntities`.
+2. Cut the proxy, wait 2.5 s, restore it, wait 2.5 s. Repeat.
+3. Within about five cycles the process exits with:
+
+```
+UnhandledPromiseRejection: ... The promise rejected with the reason "#<Object>".
+```
+
+The rejection value is a Home Assistant result frame:
+
+```json
+{ "type": "result", "success": false, "error": {} }
+```
+
+The harness is [`scripts/home-chaos.mjs`](../../scripts/home-chaos.mjs),
+scenario 2. `node --expose-gc scripts/home-chaos.mjs 2` reproduces it with the
+workaround removed.
+
+## Suggested fix
+
+Attach a handler in both places. The resubscribe already has an `info.reject`
+available, so the failure can be delivered to whoever is awaiting the original
+`subscribeMessage` rather than dropped:
+
+```js
+info.subscribe().then(
+ (unsub) => {
+ info.unsubscribe = unsub;
+ info.resolve();
+ },
+ (err) => {
+ // A resubscribe that fails during a flap must not become an unhandled
+ // rejection. The next `ready` will try again; a consumer awaiting the
+ // original subscribe should hear about it in the meantime.
+ info.reject?.(err);
+ },
+);
+```
+
+and in `collection.js`:
+
+```js
+if (subscribeUpdates) {
+ unsubProm = subscribeUpdates(conn, store);
+ unsubProm.catch(() => {}); // retried on the next `ready`
+}
+```
+
+## The workaround, for anyone who finds this before the fix lands
+
+Replace `subscribeMessage` on the connection object. `info.subscribe` resolves
+the method off the instance at call time, so this covers the reconnect path as
+well as the first subscribe:
+
+```js
+const original = connection.subscribeMessage.bind(connection);
+connection.subscribeMessage = (callback, message, options) =>
+ original(callback, message, options).then(
+ (unsubscribe) => unsubscribe,
+ (err) => {
+ report(err); // do not swallow it
+ return () => {}; // a no-op unsubscribe keeps the library's bookkeeping intact
+ },
+ );
+```
+
+The library retries the same subscription on the next `ready`, so recovery is
+unaffected: verified by reconnecting the house afterwards and seeing live state
+resume.
diff --git a/packages/home-bridge/README.md b/packages/home-bridge/README.md
index 4ca55b169..67a94195f 100644
--- a/packages/home-bridge/README.md
+++ b/packages/home-bridge/README.md
@@ -226,6 +226,24 @@ HOME_ASSISTANT_URL=http://127.0.0.1:42125 HOME_ASSISTANT_TOKEN=... npx vitest ru
node scripts/home-test-instance.mjs --down
```
+## A flapping house cannot kill your process
+
+`connect()` installs `guardSubscriptions` on the connection it opens, and that is not
+belt and braces. `home-assistant-js-websocket` re-establishes its subscriptions after a
+reconnect with no rejection handler on the promise, so a house whose uplink flaps can
+drop the socket again with a resubscribe command in flight, and the rejection reaches
+Node unobserved. Under Node's default `--unhandled-rejections=throw` that **terminates
+the process**, which on a server holding one connection per house means one bad uplink
+takes every other house down with it.
+
+Reproduced against a real Home Assistant, at the fifth flap, by scenario 2 of
+[`scripts/home-chaos.mjs`](../../scripts/home-chaos.mjs). The bug and the fix we would
+like to see are written up in
+[docs/upstream/home-assistant-js-websocket-resubscribe-rejection.md](../../docs/upstream/home-assistant-js-websocket-resubscribe-rejection.md).
+Until that lands, a failed subscribe here is reported on the bridge's `error` event and
+resolves to a no-op unsubscribe, so the library retries it on the next `ready` and the
+process survives.
+
## Read next
- [docs/tutorials/connect-your-home.md](../../docs/tutorials/connect-your-home.md): zero to a
diff --git a/packages/home-bridge/src/bridge.js b/packages/home-bridge/src/bridge.js
index 8730bd200..fbe4509ce 100644
--- a/packages/home-bridge/src/bridge.js
+++ b/packages/home-bridge/src/bridge.js
@@ -165,6 +165,10 @@ export class HomeBridge {
throw toBridgeError(err, this.#options.baseUrl);
}
+ guardSubscriptions(this.#connection, (err) =>
+ this.#emit('error', toBridgeError(err, this.#options.baseUrl, 'A state subscription could not be established.')),
+ );
+
this.#connection.addEventListener('ready', () => this.#emit('reconnected', undefined));
this.#connection.addEventListener('disconnected', () => this.#emit('disconnected', undefined));
@@ -386,6 +390,73 @@ export class HomeBridge {
}
}
+/**
+ * Stop a flapping house from killing the process.
+ *
+ * `home-assistant-js-websocket` re-establishes its subscriptions after a
+ * reconnect in `Connection._setSocket`:
+ *
+ * info.subscribe().then((unsub) => { info.unsubscribe = unsub; info.resolve(); });
+ *
+ * There is no rejection handler on that promise. A house whose uplink flaps can
+ * drop the socket again while the resubscribe command is still in flight, the
+ * command rejects with a `{ type: "result", success: false }` frame, and the
+ * rejection reaches the process unobserved. Under Node's default
+ * `--unhandled-rejections=throw` that TERMINATES the process, so one flapping
+ * house takes down every other house's connection on the same server. Reproduced
+ * against a real Home Assistant by scenario 2 of scripts/home-chaos.mjs, which
+ * crashed exactly this way at the fifth flap.
+ *
+ * The bug is upstream and is reported there (see the package README). Until a
+ * fix lands, this closes it at the one seam we own: the connection object the
+ * library uses. `info.subscribe` is `() => this.subscribeMessage(...)`, which
+ * resolves the method off the instance at call time, so replacing it here covers
+ * the reconnect path as well as the first subscribe.
+ *
+ * The failure is REPORTED, not swallowed: it reaches the bridge's `error` event
+ * with a real message. The resolved value is a no-op unsubscribe, which keeps
+ * the library's own bookkeeping intact so the same subscription is retried on
+ * the next `ready`.
+ *
+ * @param {object} connection a home-assistant-js-websocket Connection
+ * @param {(err: unknown) => void} onError
+ */
+export function guardSubscriptions(connection, onError) {
+ const report = (err) => {
+ try {
+ onError(err);
+ } catch {
+ // An error reporter that throws must not become the crash it exists to prevent.
+ }
+ };
+
+ const original = connection.subscribeMessage.bind(connection);
+ connection.subscribeMessage = (callback, message, options) =>
+ original(callback, message, options).then(
+ // BOTH ends of the subscription need this, and the second one is easy
+ // to miss. `getCollection` tears a subscription down with
+ // `unsubProm.then((unsub) => unsub())`, also with no catch, and
+ // `info.unsubscribe` sends an `unsubscribe_events` command that rejects
+ // the same way when the socket is already going. Guarding only the
+ // subscribe leaves the process dying on close instead of on connect.
+ (unsubscribe) => () => {
+ try {
+ const result = unsubscribe();
+ if (result && typeof result.then === 'function') result.then(undefined, report);
+ return result;
+ } catch (err) {
+ report(err);
+ return undefined;
+ }
+ },
+ (err) => {
+ report(err);
+ return () => {};
+ },
+ );
+ return connection;
+}
+
function firstEntityId(data) {
const id = data?.entity_id;
if (Array.isArray(id)) return id[0];
diff --git a/packages/home-bridge/src/index.js b/packages/home-bridge/src/index.js
index d949fdee8..ac495e6cc 100644
--- a/packages/home-bridge/src/index.js
+++ b/packages/home-bridge/src/index.js
@@ -1,4 +1,4 @@
-export { HomeBridge, toBridgeError } from './bridge.js';
+export { guardSubscriptions, HomeBridge, toBridgeError } from './bridge.js';
export { ERR, HomeBridgeError } from './errors.js';
// The two connection sentinels a custom socket factory has to reject with, so a
// server that supplies one (api/_lib/home-url-guard.js pins the socket to the
diff --git a/packages/home-bridge/tests/home-bridge.test.js b/packages/home-bridge/tests/home-bridge.test.js
index d802e8b96..536d5a0fd 100644
--- a/packages/home-bridge/tests/home-bridge.test.js
+++ b/packages/home-bridge/tests/home-bridge.test.js
@@ -16,6 +16,7 @@ import {
createAllowList,
ERR,
flattenEntities,
+ guardSubscriptions,
HomeBridge,
isPrivateHost,
matchMacro,
@@ -268,3 +269,102 @@ describe('HomeBridge construction', () => {
await expect(bridge.call('light', 'turn_on', {})).rejects.toMatchObject({ code: ERR.NOT_CONNECTED });
});
});
+
+describe('a flapping house cannot kill the process', () => {
+ // home-assistant-js-websocket resubscribes after a reconnect with
+ // `info.subscribe().then(...)` and no rejection handler. A house that drops
+ // its socket again while that resubscribe is in flight produces an unhandled
+ // rejection, and under Node's default mode an unhandled rejection terminates
+ // the process: one flapping house takes every other house down with it.
+ // Reproduced against a real Home Assistant by scripts/home-chaos.mjs
+ // scenario 2 before this guard existed.
+ function fakeConnection(behaviour) {
+ return {
+ calls: 0,
+ async subscribeMessage(callback, message, options) {
+ this.calls++;
+ return behaviour(this.calls, callback, message, options);
+ },
+ };
+ }
+
+ it('turns a failed subscribe into a reported error and a no-op unsubscribe', async () => {
+ const failure = { type: 'result', success: false, error: {} };
+ const connection = fakeConnection(() => Promise.reject(failure));
+ const seen = [];
+ guardSubscriptions(connection, (err) => seen.push(err));
+
+ const unsubscribe = await connection.subscribeMessage(() => {}, { type: 'subscribe_entities' });
+
+ expect(typeof unsubscribe).toBe('function');
+ expect(() => unsubscribe()).not.toThrow();
+ expect(seen).toHaveLength(1);
+ // Reported, never swallowed, and reported RAW: the guard hands the failure
+ // to its caller untranslated, so the bridge can turn a bare Home Assistant
+ // result frame into a sentence and a test can see the frame itself.
+ expect(seen[0]).toEqual(failure);
+ });
+
+ it('passes a successful subscribe through, and its unsubscribe still works', async () => {
+ let stopped = 0;
+ const unsub = () => {
+ stopped++;
+ return 'stopped';
+ };
+ const connection = fakeConnection(() => Promise.resolve(unsub));
+ guardSubscriptions(connection, () => {});
+
+ const returned = await connection.subscribeMessage(() => {}, { type: 'subscribe_entities' });
+ expect(returned()).toBe('stopped');
+ expect(stopped).toBe(1);
+ });
+
+ it('turns a failing unsubscribe into a report instead of a crash', async () => {
+ // getCollection tears down with `unsubProm.then((unsub) => unsub())` and no
+ // catch, and the unsubscribe itself sends a command that rejects when the
+ // socket is already going. Guarding only the subscribe moves the crash from
+ // connect to close rather than removing it.
+ const failure = { type: 'result', success: false, error: {} };
+ const connection = fakeConnection(() => Promise.resolve(() => Promise.reject(failure)));
+ const seen = [];
+ guardSubscriptions(connection, (err) => seen.push(err));
+
+ const unsubscribe = await connection.subscribeMessage(() => {}, { type: 'subscribe_entities' });
+ const result = unsubscribe();
+ await expect(result).rejects.toEqual(failure);
+ expect(seen).toEqual([failure]);
+ });
+
+ it('turns an unsubscribe that throws synchronously into a report too', async () => {
+ const boom = new Error('socket already gone');
+ const connection = fakeConnection(() => Promise.resolve(() => {
+ throw boom;
+ }));
+ const seen = [];
+ guardSubscriptions(connection, (err) => seen.push(err));
+
+ const unsubscribe = await connection.subscribeMessage(() => {}, { type: 'subscribe_entities' });
+ expect(() => unsubscribe()).not.toThrow();
+ expect(seen).toEqual([boom]);
+ });
+
+ it('survives a reporter that throws, which is the crash it exists to prevent', async () => {
+ const connection = fakeConnection(() => Promise.reject(new Error('socket closed')));
+ guardSubscriptions(connection, () => {
+ throw new Error('the reporter is broken too');
+ });
+
+ await expect(connection.subscribeMessage(() => {}, { type: 'subscribe_entities' })).resolves.toBeTypeOf('function');
+ });
+
+ it('keeps guarding across repeated failures, so a flap never escapes', async () => {
+ const connection = fakeConnection((n) => (n % 2 ? Promise.reject(new Error(`flap ${n}`)) : Promise.resolve(() => {})));
+ const seen = [];
+ guardSubscriptions(connection, (err) => seen.push(err));
+
+ for (let i = 0; i < 10; i++) {
+ await expect(connection.subscribeMessage(() => {}, { type: 'subscribe_entities' })).resolves.toBeTypeOf('function');
+ }
+ expect(seen).toHaveLength(5);
+ });
+});