From 099f5aa2872580b238f724524530949452524ed2 Mon Sep 17 00:00:00 2001 From: MayaTheShy Date: Sun, 29 Mar 2026 14:42:47 -0400 Subject: [PATCH] fix: enhance WebSocket bridge connection to flush pending commands and improve initial sync --- web/server/server.js | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/web/server/server.js b/web/server/server.js index 7fb16f1..fc6e8ad 100644 --- a/web/server/server.js +++ b/web/server/server.js @@ -60,9 +60,21 @@ const wsManager = createWebSocketManager(server, { apiKey: API_KEY, // ---- Bridge lifecycle ---- - onBridgeConnect: () => { + onBridgeConnect: (ws) => { console.log('\u{1F309} CC:Tweaked bridge connected via WebSocket'); wsManager.broadcastToClients({ type: 'state_update', bridgeConnected: true }); + + // Flush any pending commands queued while no WS bridge was connected. + // Replaces the implicit sync that HTTP polling previously provided. + const pending = getPendingCommands(); + if (pending.length > 0) { + try { + ws.send(JSON.stringify({ type: 'command_batch', commands: pending })); + console.log(`[Bridge] Flushed ${pending.length} pending command(s) via WS`); + } catch (e) { + console.error('[Bridge] Failed to flush pending commands:', e.message); + } + } }, onBridgeMessage: (ws, data) => { @@ -193,6 +205,14 @@ function broadcastToClients(data) { wsManager.broadcastToClients(data); } +// Returns a filtered copy of pending commands (clears expired entries). +// Used by both the HTTP polling endpoint and WS initial sync. +function getPendingCommands() { + const now = Date.now(); + pendingCommands = pendingCommands.filter(cmd => (now - cmd.timestamp) < 30000); + return [...pendingCommands]; +} + // Pushes a command to the CC:Tweaked bridge. // Primary: real-time push via WebSocket (wsManager.sendToBridge). // Fallback: queues for HTTP polling if no WS bridge is connected. @@ -986,11 +1006,7 @@ app.post('/api/bridge/state', (req, res) => { // Bridge polls for pending commands (auth required — contains operational data) app.get('/api/bridge/commands', requireAuth, (req, res) => { try { - const now = Date.now(); - // Clear old commands (>30s) - pendingCommands = pendingCommands.filter(cmd => (now - cmd.timestamp) < 30000); - - const commands = [...pendingCommands]; + const commands = getPendingCommands(); res.json({ commands }); } catch (error) { res.status(500).json({ error: error.message });