From a25a27b3eac5300691900325d999bce54e76d6cd Mon Sep 17 00:00:00 2001 From: Doug Rathbone Date: Fri, 20 Nov 2026 11:56:16 +0000 Subject: [PATCH 1/6] fix: discard a TREEXML that does not fit before discovery is ready Replaying only the fragments that fit the pending buffer published a partial tree, and discovery then treated the missing groups as gone. Drop that tree whole so startup requests a complete one. --- src/commandResponseProcessor.js | 25 ++++++++++-- src/config/schema.js | 2 +- tests/commandResponseProcessor.test.js | 53 ++++++++++++++++++++++++-- 3 files changed, 73 insertions(+), 7 deletions(-) diff --git a/src/commandResponseProcessor.js b/src/commandResponseProcessor.js index f91fa2ef..363beae6 100644 --- a/src/commandResponseProcessor.js +++ b/src/commandResponseProcessor.js @@ -66,6 +66,10 @@ class CommandResponseProcessor { ? pendingCap : resolveSetting({}, 'commandResponseMaxPendingTreeMessages'); this._pendingTreeOverflowLogged = false; + // Once a tree no longer fits, the rest of that tree is discarded too. + // Keeping the head and dropping the tail is what used to replay a + // truncated TREEXML into discovery. + this._pendingTreeDiscarding = false; this.onObjectStatus = onObjectStatus; this.onCommandError = onCommandError || null; // Called for network-level interface/state responses @@ -123,6 +127,7 @@ class CommandResponseProcessor { this._pendingTreeMessages = []; } this._pendingTreeOverflowLogged = false; + this._pendingTreeDiscarding = false; } /** @@ -520,11 +525,23 @@ class CommandResponseProcessor { } /** - * Queue a TREEXML fragment until HA Discovery is constructed. Log once - * when the cap is hit so a truncated tree is visible in the logs. + * Queue a TREEXML fragment until HA Discovery is constructed. + * + * A tree that does not fit is discarded whole. Replaying the fragments + * that happened to fit publishes a partial tree, and discovery then + * treats the missing groups as gone. The following startup request + * fetches a complete one. A later TREE_START begins a new buffer. * @private */ _bufferTreeMessage(code, data) { + if (this._pendingTreeDiscarding) { + if (code === CGATE_RESPONSE_TREE_START) { + this._pendingTreeDiscarding = false; + } else { + if (code === CGATE_RESPONSE_TREE_END) this._pendingTreeDiscarding = false; + return; + } + } if (this._pendingTreeMessages.length < this._maxPendingTreeMessages) { if (code === CGATE_RESPONSE_TREE_START) { this.logger.debug('Buffering tree start (HA Discovery not yet initialized)'); @@ -532,10 +549,12 @@ class CommandResponseProcessor { this._pendingTreeMessages.push({ code, data }); return; } + this._pendingTreeMessages = []; + this._pendingTreeDiscarding = code !== CGATE_RESPONSE_TREE_END; if (this._pendingTreeOverflowLogged) return; this._pendingTreeOverflowLogged = true; this.logger.warn( - `Dropping TREEXML fragments: HA Discovery is not ready and the pending-tree buffer is full (${this._maxPendingTreeMessages} messages). Discovery may start with a truncated tree.` + `Discarding incomplete TREEXML: HA Discovery is not ready and the pending-tree buffer is full (${this._maxPendingTreeMessages} messages). Discovery will request a fresh tree once it starts.` ); } diff --git a/src/config/schema.js b/src/config/schema.js index 4858825e..84eb8d85 100644 --- a/src/config/schema.js +++ b/src/config/schema.js @@ -1502,7 +1502,7 @@ const SETTINGS_SCHEMA = { default: 500, unit: 'none', exposure: 'standalone', - description: 'How many TREEXML fragments to buffer while HA Discovery is still starting. Further fragments are dropped (with one warning) until discovery is ready.', + description: 'How many TREEXML fragments to buffer while HA Discovery is still starting. A tree that does not fit is discarded whole, and discovery requests a fresh one once it starts.', reason: TUNING_ONLY_REASON }, commandErrorRepeatWindowMs: { diff --git a/tests/commandResponseProcessor.test.js b/tests/commandResponseProcessor.test.js index 31836ee6..0267859f 100644 --- a/tests/commandResponseProcessor.test.js +++ b/tests/commandResponseProcessor.test.js @@ -547,7 +547,7 @@ describe('CommandResponseProcessor', () => { expect(processorWithNullHaDiscovery._pendingTreeMessages).toHaveLength(0); }); - it('warns once when the pending-tree buffer is full and then drops further fragments', () => { + it('discards the whole pending tree when the buffer is full and does not replay it', () => { const capped = new CommandResponseProcessor({ eventPublisher: mockEventPublisher, haDiscovery: null, @@ -558,11 +558,58 @@ describe('CommandResponseProcessor', () => { capped._processCommandResponse(CGATE_RESPONSE_TREE_START, 'start'); capped._processCommandResponse(CGATE_RESPONSE_TREE_DATA, 'data-1'); capped._processCommandResponse(CGATE_RESPONSE_TREE_DATA, 'data-2'); + capped._processCommandResponse(CGATE_RESPONSE_TREE_DATA, 'data-3'); capped._processCommandResponse(CGATE_RESPONSE_TREE_END, 'end'); - expect(capped._pendingTreeMessages).toHaveLength(2); + expect(capped._pendingTreeMessages).toHaveLength(0); expect(mockLogger.warn).toHaveBeenCalledTimes(1); - expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('pending-tree buffer is full')); + expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('Discarding incomplete TREEXML')); + + const mockHaDiscovery = { + handleTreeStart: jest.fn(), + handleTreeData: jest.fn(), + handleTreeEnd: jest.fn() + }; + capped.haDiscovery = mockHaDiscovery; + expect(mockHaDiscovery.handleTreeStart).not.toHaveBeenCalled(); + expect(mockHaDiscovery.handleTreeData).not.toHaveBeenCalled(); + expect(mockHaDiscovery.handleTreeEnd).not.toHaveBeenCalled(); + }); + + it('buffers a later complete tree after discarding one that overflowed', () => { + const capped = new CommandResponseProcessor({ + eventPublisher: mockEventPublisher, + haDiscovery: null, + onObjectStatus: mockOnObjectStatus, + logger: mockLogger, + maxPendingTreeMessages: 3 + }); + capped._processCommandResponse(CGATE_RESPONSE_TREE_START, 'start-1'); + capped._processCommandResponse(CGATE_RESPONSE_TREE_DATA, 'data-1'); + capped._processCommandResponse(CGATE_RESPONSE_TREE_DATA, 'data-2'); + capped._processCommandResponse(CGATE_RESPONSE_TREE_DATA, 'overflow'); + capped._processCommandResponse(CGATE_RESPONSE_TREE_END, 'end-1'); + + capped._processCommandResponse(CGATE_RESPONSE_TREE_START, 'start-2'); + capped._processCommandResponse(CGATE_RESPONSE_TREE_DATA, 'data-2'); + capped._processCommandResponse(CGATE_RESPONSE_TREE_END, 'end-2'); + + expect(capped._pendingTreeMessages).toEqual([ + { code: CGATE_RESPONSE_TREE_START, data: 'start-2' }, + { code: CGATE_RESPONSE_TREE_DATA, data: 'data-2' }, + { code: CGATE_RESPONSE_TREE_END, data: 'end-2' } + ]); + + const mockHaDiscovery = { + handleTreeStart: jest.fn(), + handleTreeData: jest.fn(), + handleTreeEnd: jest.fn() + }; + capped.haDiscovery = mockHaDiscovery; + expect(mockHaDiscovery.handleTreeStart).toHaveBeenCalledTimes(1); + expect(mockHaDiscovery.handleTreeStart).toHaveBeenCalledWith('start-2'); + expect(mockHaDiscovery.handleTreeData).toHaveBeenCalledWith('data-2'); + expect(mockHaDiscovery.handleTreeEnd).toHaveBeenCalledWith('end-2'); }); it('should still process object status when haDiscovery is null', () => { From afc898ecaaa96457ee565a658795788cd27e1928 Mon Sep 17 00:00:00 2001 From: Doug Rathbone Date: Fri, 20 Nov 2026 11:57:05 +0000 Subject: [PATCH 2/6] fix: ignore TreeXML data that arrives with no session A data chunk without a start used to open a fallback session and attach the XML to the next queued network, or to unknown. Drop the chunk so a reordered fragment cannot corrupt discovery for the wrong network. --- src/haDiscoveryTreeSession.js | 9 +++++++-- tests/haDiscovery.test.js | 13 +++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/haDiscoveryTreeSession.js b/src/haDiscoveryTreeSession.js index 0bc12744..c83cb776 100644 --- a/src/haDiscoveryTreeSession.js +++ b/src/haDiscoveryTreeSession.js @@ -511,8 +511,13 @@ class _HaDiscoveryTreeSession { handleTreeData(statusData) { if (!this.activeTreeSession) { - this.logger.warn('Received TreeXML data without active tree session; creating fallback session.'); - this.handleTreeStart(''); + // A data chunk with no TREE_START used to open a fallback session + // and attach the XML to whichever network was next in the queue, + // or to the literal 'unknown'. That corrupts discovery for the + // wrong network. Drop the chunk. The request watchdog still fails + // a tree that never completes. + this.logger.warn('Received TreeXML data without active tree session; ignoring it.'); + return; } const chunk = typeof statusData === 'string' ? statusData : String(statusData); // Cap while streaming so a compromised/runaway C-Gate cannot grow diff --git a/tests/haDiscovery.test.js b/tests/haDiscovery.test.js index 824b1551..f87847bf 100644 --- a/tests/haDiscovery.test.js +++ b/tests/haDiscovery.test.js @@ -171,12 +171,25 @@ describe('HaDiscovery', () => { }); it('should accumulate tree data in array', () => { + haDiscovery.handleTreeStart('start'); haDiscovery.handleTreeData('line1'); haDiscovery.handleTreeData('line2'); expect(haDiscovery.treeBufferParts).toEqual(['line1', 'line2']); }); + it('ignores tree data that arrives before a start and leaves the pending network queued', () => { + haDiscovery.pendingTreeNetworks = ['254']; + const warnSpy = jest.spyOn(haDiscovery.logger, 'warn'); + + haDiscovery.handleTreeData(''); + + expect(haDiscovery.activeTreeSession).toBeNull(); + expect(haDiscovery.pendingTreeNetworks).toEqual(['254']); + expect(haDiscovery.treeBufferParts).toEqual([]); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('without active tree session')); + }); + it('should join buffer parts with newlines on tree end', () => { // Split valid TreeXML across data parts; if they are not newline-joined // into well-formed XML the real parser would fail and nothing publishes. From 1cc6dde38144cc51f067fae7ab10165a3e71f7c2 Mon Sep 17 00:00:00 2001 From: Doug Rathbone Date: Fri, 20 Nov 2026 11:57:11 +0000 Subject: [PATCH 3/6] test: a failed C-Gate send warns once and the next command still goes A pool rejection resolves the queue item after one warning. Lock that contract so a transient failure cannot stall the queue, and so the failed command is not sent a second time. --- tests/cgateWebBridge.test.js | 51 ++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/tests/cgateWebBridge.test.js b/tests/cgateWebBridge.test.js index 0134fd53..dc09bb55 100644 --- a/tests/cgateWebBridge.test.js +++ b/tests/cgateWebBridge.test.js @@ -1913,6 +1913,57 @@ describe('CgateWebBridge', () => { ); expect(publishSpy.mock.calls[0][1]).toContain('No healthy connections'); }); + + it('warns once for a failed send and still sends the next command', async () => { + jest.useFakeTimers(); + try { + mockConnectionPool.isStarted = true; + setPoolHealthyCount(3); + mockConnectionPool.getStats.mockImplementation(() => ({ + isStarted: mockConnectionPool.isStarted, + isShuttingDown: false, + healthyConnections: mockConnectionPool.healthyConnections.size, + writableConnections: mockConnectionPool.healthyConnections.size + })); + let attempts = 0; + mockConnectionPool.execute.mockImplementation(async () => { + attempts += 1; + if (attempts === 1) { + throw new Error('No healthy connections available in pool'); + } + return true; + }); + + bridge.settings.messageinterval = 10; + bridge.settings.messageIntervalMinMs = 10; + bridge.settings.commandMinIntervalMs = 10; + bridge.settings.commandMinIntervalFloorMs = 10; + bridge._buildQueues(); + + const publishSpy = jest.spyOn(bridge.mqttManager, 'publish'); + bridge.cgateCommandQueue.add('CMD1\n'); + bridge.cgateCommandQueue.add('CMD2\n'); + + for (let i = 0; i < 10 && mockConnectionPool.execute.mock.calls.length < 2; i++) { + jest.advanceTimersByTime(20); + await Promise.resolve(); + await Promise.resolve(); + } + + expect(mockConnectionPool.execute).toHaveBeenCalledTimes(2); + expect(mockConnectionPool.execute).toHaveBeenNthCalledWith(1, 'CMD1\n'); + expect(mockConnectionPool.execute).toHaveBeenNthCalledWith(2, 'CMD2\n'); + const warnings = publishSpy.mock.calls.filter((call) => ( + call[0] === 'hello/cgateweb/warnings' + && String(call[1]).includes('C-Gate command send failed') + )); + expect(warnings).toHaveLength(1); + expect(bridge.cgateCommandQueue.length).toBe(0); + } finally { + mockConnectionPool.execute.mockImplementation(async () => true); + jest.useRealTimers(); + } + }); }); describe('command queue gating', () => { From b7d742dc6b08d6d898309c690f70c785ac4666e2 Mon Sep 17 00:00:00 2001 From: Doug Rathbone Date: Fri, 20 Nov 2026 11:57:11 +0000 Subject: [PATCH 4/6] fix: bound the discovery config replay cache The replay map grew with every unique config topic for the life of the process. Cap it, drop the oldest entries, and request a fresh tree after a broker restart so those devices are announced again. --- docs/SETTINGS.md | 1 + src/config/schema.js | 9 +++ src/haDiscovery.js | 59 ++++++++++++++++++-- tests/defaultSettings.test.js | 4 +- tests/fixtures/defaultSettings.snapshot.json | 1 + tests/haDiscovery.test.js | 24 ++++++++ 6 files changed, 90 insertions(+), 8 deletions(-) diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index ac368196..653fc1f1 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -457,6 +457,7 @@ C-Gate accepts connections on the command port before its networks have loaded, | `haDiscoveryTreeRetryMaxDelayMs` | *standalone only* | integer (ms) | `60000` | Backoff ceiling. | | `haDiscoveryTreeRequestTimeoutMs` | *standalone only* | integer (ms) | `8000` | "No response at all" timeout for a tree request. | | `haDiscoveryTreeStreamStallMs` | *standalone only* | integer (ms) | `8000` | How long a tree stream may go **silent mid-transfer** before counting as stalled. Reset by every data chunk, so it bounds idle time rather than total transfer time. Raise it only if a very large tree on slow hardware still reports "tree stream stalled". | +| `haDiscoveryConfigCacheMaxEntries` | *standalone only* | integer | `20000` | How many discovery configs to remember so a broker restart can replay them. Past this, the oldest are dropped and the next restart re-requests the tree. A normal install never reaches it. | | `haDiscoveryMaxTreeResyncAttempts` | *standalone only* | integer | `3` | Re-fetches of an accepted tree that still had empty `` because C-Gate had not finished syncing group bindings. | | `haDiscoveryTreeResyncInitialDelayMs` | *standalone only* | integer (ms) | `30000` | Initial delay before the first re-fetch. | | `haDiscoveryTreeResyncMaxDelayMs` | *standalone only* | integer (ms) | `120000` | Ceiling for re-fetch backoff. | diff --git a/src/config/schema.js b/src/config/schema.js index 84eb8d85..4ab3b60e 100644 --- a/src/config/schema.js +++ b/src/config/schema.js @@ -1440,6 +1440,15 @@ const SETTINGS_SCHEMA = { description: 'How long a TreeXML request may go without any response at all before it counts as failed.', reason: TUNING_ONLY_REASON }, + haDiscoveryConfigCacheMaxEntries: { + key: 'haDiscoveryConfigCacheMaxEntries', + type: 'number', + default: 20000, + unit: 'none', + exposure: 'standalone', + description: 'How many Home Assistant discovery configs to remember so they can be replayed after a broker restart. Past this, the oldest are dropped and the next restart re-requests the tree.', + reason: 'Each config is a few hundred bytes and a normal install is well under this. The cap stops a stream of unique topics from growing the cache for the life of the process.' + }, haDiscoveryTreeStreamStallMs: { key: 'haDiscoveryTreeStreamStallMs', type: 'number', diff --git a/src/haDiscovery.js b/src/haDiscovery.js index 26dcd6a5..f11cc559 100644 --- a/src/haDiscovery.js +++ b/src/haDiscovery.js @@ -4,7 +4,7 @@ const path = require('path'); const { createLogger } = require('./logger'); const { findNetworkData, collectUnitGroups, collectUnitTypeData, networkHasUnsyncedUnits } = require('./haDiscoveryTree'); const { parseSecurityZoneLabelKey, securityZoneLabelKey } = require('./securityZoneLabels'); -const { resolveSetting } = require('./config/schema'); +const { resolveSetting, resolveClampedSetting } = require('./config/schema'); const { DEFAULT_CBUS_APP_LIGHTING, MQTT_RETAINED_STATE_OPTIONS, @@ -54,14 +54,18 @@ class HaDiscovery { // after an MQTT broker restart drops them (issue #44). Recorded in the // _publish wrapper below rather than at each of the ~16 call sites that // publish a config, so the cache cannot drift out of sync with them. - // Bounded by entity count: a few hundred payloads of roughly 500 bytes. + // Capped so a runaway unique-topic stream cannot grow for the life of + // the process. Updating an existing topic does not count as growth. + // Oldest entries are dropped first; a broker restart then re-requests + // the tree so those devices are announced again. + this._configCacheMaxEntries = resolveClampedSetting(settings || {}, 'haDiscoveryConfigCacheMaxEntries', { min: 1 }); + this._configCacheEvicted = false; + this._discoveryNetworks = null; this._publishedConfigPayloads = new Map(); this._rawPublish = publishFn; this._publish = (topic, payload, options) => { if (typeof topic === 'string' && topic.endsWith(CONFIG_TOPIC_SUFFIX)) { - // An empty payload is a retraction — forget it, don't replay it. - if (payload) this._publishedConfigPayloads.set(topic, payload); - else this._publishedConfigPayloads.delete(topic); + this._rememberConfigPayload(topic, payload); } return publishFn(topic, payload, options); }; @@ -208,9 +212,12 @@ class HaDiscovery { * A broker restart without retained-message persistence loses the configs, * and Home Assistant then has no entities at all until the next tree run. * Replaying the cached payloads restores them exactly, without re-running - * TREEXML and its retry/epoch machinery (issue #44). + * TREEXML and its retry/epoch machinery (issue #44). If the cache had to + * drop configs to stay within its cap, a fresh tree is requested as well + * so those devices are announced again. * * @returns {number} configs republished + * @this {HaDiscovery & HaDiscoveryMixinMethods} */ republishDiscoveryConfigs() { let count = 0; @@ -220,11 +227,50 @@ class HaDiscovery { this._rawPublish(topic, payload, MQTT_RETAINED_STATE_OPTIONS); count++; } + if (this._configCacheEvicted) { + this.logger.warn( + 'Discovery config cache was truncated; requesting a fresh tree so evicted devices are announced again' + ); + this.trigger(this._discoveryNetworks); + } if (count > 0) this.logger.info(`Republished ${count} HA Discovery config(s)`); this.syncUnlistedGroupDiscovery(); return count; } + /** + * Remember a discovery config for replay, or forget it when retracted. + * An update of a topic already cached refreshes that entry in place. + * A new topic past the cap evicts the oldest one. + * @param {string} topic + * @param {string} payload + * @private + */ + _rememberConfigPayload(topic, payload) { + if (!payload) { + this._publishedConfigPayloads.delete(topic); + return; + } + if (this._publishedConfigPayloads.has(topic)) { + // Refresh in place and move to the newest end of the eviction order. + this._publishedConfigPayloads.delete(topic); + this._publishedConfigPayloads.set(topic, payload); + return; + } + while (this._publishedConfigPayloads.size >= this._configCacheMaxEntries) { + const oldest = this._publishedConfigPayloads.keys().next().value; + if (oldest === undefined) break; + this._publishedConfigPayloads.delete(oldest); + if (!this._configCacheEvicted) { + this._configCacheEvicted = true; + this.logger.warn( + `HA discovery config cache reached ${this._configCacheMaxEntries} entries; oldest configs will not be replayed from memory. A broker restart re-requests the tree.` + ); + } + } + this._publishedConfigPayloads.set(topic, payload); + } + /** * Replace the label data (used for hot-reload). * Accepts either a full labelData object or a plain Map for backward compatibility. @@ -537,6 +583,7 @@ class HaDiscovery { } this.logger.info(`HA Discovery enabled, querying network trees...`); + this._discoveryNetworks = discoveredNetworks; let networksToDiscover = this.settings.ha_discovery_networks; // If no networks explicitly configured, fall back to auto-discovered networks diff --git a/tests/defaultSettings.test.js b/tests/defaultSettings.test.js index ec2013c9..c6cb9de3 100644 --- a/tests/defaultSettings.test.js +++ b/tests/defaultSettings.test.js @@ -11,14 +11,14 @@ describe('defaultSettings — frozen baseline', () => { expect(defaultSettings).toStrictEqual(defaultSettingsSnapshot); }); - it('exports the same 155 keys as the baseline', () => { + it('exports the same 156 keys as the baseline', () => { expect(Object.keys(defaultSettings).sort()) .toEqual(Object.keys(defaultSettingsSnapshot).sort()); // Bumping this count is only ever legitimate alongside a genuinely NEW // setting added to the fixture; a changed value for an existing key is // the thing this baseline exists to catch, and must never be "fixed" // in the fixture. - expect(Object.keys(defaultSettings)).toHaveLength(155); + expect(Object.keys(defaultSettings)).toHaveLength(156); }); it('returns a fresh object so consumers cannot mutate the schema defaults', () => { diff --git a/tests/fixtures/defaultSettings.snapshot.json b/tests/fixtures/defaultSettings.snapshot.json index f317e654..c78538b6 100644 --- a/tests/fixtures/defaultSettings.snapshot.json +++ b/tests/fixtures/defaultSettings.snapshot.json @@ -45,6 +45,7 @@ "getallnetapp": null, "getallonstart": false, "getallperiod": null, + "haDiscoveryConfigCacheMaxEntries": 20000, "haDiscoveryMaxTreeResyncAttempts": 3, "haDiscoveryMaxTreeRetryAttempts": 8, "haDiscoveryTreeRequestTimeoutMs": 8000, diff --git a/tests/haDiscovery.test.js b/tests/haDiscovery.test.js index f87847bf..876c55a7 100644 --- a/tests/haDiscovery.test.js +++ b/tests/haDiscovery.test.js @@ -3691,4 +3691,28 @@ describe('HaDiscovery — discovery config replay (issue #44)', () => { d._publish('cbus/read/254/208/13/state', 'ON', { retain: true }); expect(d.republishDiscoveryConfigs()).toBe(0); }); + + it('drops the oldest discovery configs once the cache is full and re-requests the tree on replay', () => { + d.settings.haDiscoveryConfigCacheMaxEntries = 2; + d._configCacheMaxEntries = 2; + d.settings.ha_discovery_networks = ['254']; + d.settings.cbusname = 'TESTPROJECT'; + const send = jest.fn(); + d._sendCommand = send; + + d.ensureSecurityZoneDiscovery('254', '208', '13'); + d.ensureSecurityZoneDiscovery('254', '208', '14'); + publishFn.mockClear(); + + expect(d._publishedConfigPayloads.size).toBe(2); + expect(d._configCacheEvicted).toBe(true); + expect(d.republishDiscoveryConfigs()).toBe(2); + expect(publishFn).not.toHaveBeenCalledWith( + 'homeassistant/binary_sensor/cgateweb_254_208_13/config', + expect.anything(), + expect.anything() + ); + expect(send).toHaveBeenCalledWith(expect.stringContaining('254')); + d.stop(); + }); }); From 5b5f96011d6d1d6b20c3230e2b741f39e843cfb2 Mon Sep 17 00:00:00 2001 From: Doug Rathbone Date: Fri, 20 Nov 2026 11:57:11 +0000 Subject: [PATCH 5/6] ci: publish the source release before the add-on store The distribution push used to run before changelog extraction and the source GitHub Release. A failure after that push left Supervisor on the new version with no source release. Create the source release first, so a later store-push failure stays on the previous add-on and the drift check can see the unpublished tag. --- .github/workflows/hacs-distribution.yml | 33 ++++++++++++++----------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/.github/workflows/hacs-distribution.yml b/.github/workflows/hacs-distribution.yml index 4fbdadb3..4dd595bf 100644 --- a/.github/workflows/hacs-distribution.yml +++ b/.github/workflows/hacs-distribution.yml @@ -337,6 +337,25 @@ jobs: fi echo "Rendered distribution config validated at version ${VERSION}." + # Release notes and the source GitHub Release are created before the + # add-on store is updated. Doing it the other way left Supervisor on the + # new version whenever changelog extraction or the source release failed. + # If the store push fails after this point, the source release already + # exists and distribution-drift-check reports the unpublished tag. + - name: Write source-repo release notes from the changelog + env: + VERSION: ${{ steps.version.outputs.version }} + run: node tools/extract-changelog.js "$VERSION" > source-release-notes.md + + - name: Create source-repo GitHub Release + uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3 + with: + tag_name: v${{ steps.version.outputs.version }} + name: v${{ steps.version.outputs.version }} + body_path: source-release-notes.md + draft: false + prerelease: false + - name: Checkout or initialize distribution repository env: HACS_DEPLOY_TOKEN: ${{ secrets.HACS_DEPLOY_TOKEN }} @@ -401,20 +420,6 @@ jobs: exit 1 fi - - name: Write source-repo release notes from the changelog - env: - VERSION: ${{ steps.version.outputs.version }} - run: node tools/extract-changelog.js "$VERSION" > source-release-notes.md - - - name: Create source-repo GitHub Release - uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3 - with: - tag_name: v${{ steps.version.outputs.version }} - name: v${{ steps.version.outputs.version }} - body_path: source-release-notes.md - draft: false - prerelease: false - - name: Create distribution-repo GitHub Release uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3 with: From 8c56486d9e9a6b42bb97c11ab5b153e135887b49 Mon Sep 17 00:00:00 2001 From: Doug Rathbone Date: Fri, 20 Nov 2026 11:57:11 +0000 Subject: [PATCH 6/6] chore: release v1.40.4 --- homeassistant-addon/CHANGELOG.md | 11 +++++++++++ homeassistant-addon/config.yaml | 2 +- package-lock.json | 4 ++-- package.json | 2 +- 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/homeassistant-addon/CHANGELOG.md b/homeassistant-addon/CHANGELOG.md index dea16b0e..a205d713 100644 --- a/homeassistant-addon/CHANGELOG.md +++ b/homeassistant-addon/CHANGELOG.md @@ -11,6 +11,17 @@ If this add-on saves you time, you can [buy me a coffee](https://buymeacoffee.co Releases before 1.22.0 are in the [changelog archive](https://github.com/dougrathbone/cgateweb/blob/master/homeassistant-addon/CHANGELOG-archive.md). +## [1.40.4](https://github.com/dougrathbone/cgateweb/releases/tag/v1.40.4) - 2026-11-20 + +### Fixed + +- **Home Assistant no longer builds devices from a partial C-Bus tree.** When the tree arrives before discovery is ready and does not fit, the add-on discards it and requests a complete one. +- **A tree fragment with no matching start is ignored.** Discovery no longer assigns that fragment to the wrong network. + +### Changed + +- **Discovery keeps a bounded set of device configs across a broker restart.** An installation past that bound is rediscovered from C-Gate instead of growing the add-on's memory without a limit. + ## [1.40.3](https://github.com/dougrathbone/cgateweb/releases/tag/v1.40.3) - 2026-11-14 ### Fixed diff --git a/homeassistant-addon/config.yaml b/homeassistant-addon/config.yaml index 6db6d1fb..afb05232 100644 --- a/homeassistant-addon/config.yaml +++ b/homeassistant-addon/config.yaml @@ -1,5 +1,5 @@ name: "C-Gate Web Bridge" -version: "1.40.3" +version: "1.40.4" slug: cgateweb description: "Bridge between Clipsal C-Bus systems and MQTT/Home Assistant" url: "https://github.com/dougrathbone/cgateweb" diff --git a/package-lock.json b/package-lock.json index 372bd862..b05ebd63 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "cgateweb", - "version": "1.40.3", + "version": "1.40.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "cgateweb", - "version": "1.40.3", + "version": "1.40.4", "license": "MIT", "dependencies": { "adm-zip": "^0.6.1", diff --git a/package.json b/package.json index c5fddbc1..82f5822b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cgateweb", - "version": "1.40.3", + "version": "1.40.4", "description": "Node.js bridge connecting Clipsal C-Bus automation systems to MQTT for Home Assistant integration", "keywords": [ "cbus",