π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(gateway): reconcile message-gateway connections against database (#16898)
Rdmclin2c59207ae8cce
diff --git a/apps/server/src/services/gateway/MessageGatewayClient.ts b/apps/server/src/services/gateway/MessageGatewayClient.tsindex ef7a366378a..03d45357641 100644--- a/apps/server/src/services/gateway/MessageGatewayClient.ts+++ b/apps/server/src/services/gateway/MessageGatewayClient.ts@@ -160,6 +160,22 @@ export class MessageGatewayClient {return res.json();}+ /**+ * All connectionIds the gateway has ever registered and not yet explicitly+ * disconnected. Unlike `getStats` (which the AdminDO prunes after 30min of+ * silence), this set retains dormant/hibernated connections, so it is the+ * authoritative "actual" set for reconciliation.+ */+ async getRegisteredIds(): Promise<{ ids: string[] }> {+ const res = await this.fetch('/api/admin/registered-ids');++ if (!res.ok) {+ throw new Error(`message-gateway registered-ids failed (${res.status})`);+ }++ return res.json();+ }+// βββ Internal HTTP βββprivate async fetch(path: string, init?: RequestInit): Promise<Response> {diff --git a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts b/apps/server/src/services/gateway/__tests__/GatewayService.test.tsindex ca6e07b3fc6..31f5c202b9f 100644--- a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts+++ b/apps/server/src/services/gateway/__tests__/GatewayService.test.ts@@ -10,6 +10,7 @@ const mockGatewayClient = vi.hoisted(() => ({connect: vi.fn(),disconnect: vi.fn(),disconnectAll: vi.fn(),+ getRegisteredIds: vi.fn(),getStats: vi.fn(),getStatus: vi.fn(),isConfigured: false,@@ -29,6 +30,7 @@ const mockGatewayManager = vi.hoisted(() => ({}));const mockFindEnabledByPlatform = vi.hoisted(() => vi.fn());+const mockFindByIds = vi.hoisted(() => vi.fn());const mockGetServerDB = vi.hoisted(() => vi.fn());const mockInitWithEnvKey = vi.hoisted(() => vi.fn());const mockUpdateBotRuntimeStatus = vi.hoisted(() => vi.fn());@@ -57,6 +59,7 @@ vi.mock('@/database/core/db-adaptor', () => ({vi.mock('@/database/models/agentBotProvider', () => ({AgentBotProviderModel: {+ findByIds: mockFindByIds,findEnabledByPlatform: mockFindEnabledByPlatform,},}));@@ -101,6 +104,11 @@ describe('GatewayService', () => {mockGetServerDB.mockResolvedValue({});mockInitWithEnvKey.mockResolvedValue({});mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindByIds.mockResolvedValue([]);+ // Default: admin snapshot unavailable β sync falls back to per-connection+ // getStatus and skips stale-connection cleanup (matches pre-reconciliation behavior).+ mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));+ mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registered-ids unavailable'));mockUpdateBotRuntimeStatus.mockResolvedValue({});mockIsBotFeatureAccessAllowed.mockResolvedValue(true);mockGetBotFeatureBlockedMessage.mockReturnValue('This bot channel requires a paid plan.');@@ -166,7 +174,13 @@ describe('GatewayService', () => {it('skips webhook-mode providers', async () => {mockFindEnabledByPlatform.mockResolvedValue([- { applicationId: 'app-1', credentials: {}, id: 'prov-1', settings: {}, userId: 'u1' },+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },]);mockResolveConnectionMode.mockReturnValue('webhook');@@ -177,7 +191,13 @@ describe('GatewayService', () => {it('skips already connected providers', async () => {mockFindEnabledByPlatform.mockResolvedValue([- { applicationId: 'app-1', credentials: {}, id: 'prov-1', settings: {}, userId: 'u1' },+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },]);mockResolveConnectionMode.mockReturnValue('websocket');mockGatewayClient.getStatus.mockResolvedValue({@@ -191,7 +211,13 @@ describe('GatewayService', () => {it('skips connecting providers', async () => {mockFindEnabledByPlatform.mockResolvedValue([- { applicationId: 'app-1', credentials: {}, id: 'prov-1', settings: {}, userId: 'u1' },+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },]);mockResolveConnectionMode.mockReturnValue('websocket');mockGatewayClient.getStatus.mockResolvedValue({@@ -205,7 +231,13 @@ describe('GatewayService', () => {it('skips providers in error state', async () => {mockFindEnabledByPlatform.mockResolvedValue([- { applicationId: 'app-1', credentials: {}, id: 'prov-1', settings: {}, userId: 'u1' },+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },]);mockResolveConnectionMode.mockReturnValue('websocket');mockGatewayClient.getStatus.mockResolvedValue({@@ -218,15 +250,19 @@ describe('GatewayService', () => {});it('connects disconnected providers', async () => {- mockFindEnabledByPlatform.mockResolvedValue([- {- applicationId: 'app-1',- credentials: { token: 'x' },- id: 'prov-1',- settings: {},- userId: 'u1',- },- ]);+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord'+ ? [+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },+ ]+ : [],+ );mockResolveConnectionMode.mockReturnValue('websocket');mockGatewayClient.getStatus.mockResolvedValue({state: { status: 'disconnected' },@@ -286,7 +322,13 @@ describe('GatewayService', () => {it('sets connected status for sync connect result', async () => {mockFindEnabledByPlatform.mockResolvedValue([- { applicationId: 'app-1', credentials: {}, id: 'prov-1', settings: {}, userId: 'u1' },+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },]);mockResolveConnectionMode.mockReturnValue('websocket');mockGatewayClient.getStatus.mockRejectedValue(new Error('not found'));@@ -301,7 +343,13 @@ describe('GatewayService', () => {it('tries to connect when status check fails', async () => {mockFindEnabledByPlatform.mockResolvedValue([- { applicationId: 'app-1', credentials: {}, id: 'prov-1', settings: {}, userId: 'u1' },+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },]);mockResolveConnectionMode.mockReturnValue('websocket');mockGatewayClient.getStatus.mockRejectedValue(new Error('DO not found'));@@ -314,7 +362,13 @@ describe('GatewayService', () => {it('handles connect failure gracefully', async () => {mockFindEnabledByPlatform.mockResolvedValue([- { applicationId: 'app-1', credentials: {}, id: 'prov-1', settings: {}, userId: 'u1' },+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },]);mockResolveConnectionMode.mockReturnValue('websocket');mockGatewayClient.getStatus.mockResolvedValue({@@ -326,5 +380,389 @@ describe('GatewayService', () => {await expect(service.ensureRunning()).resolves.toBeUndefined();expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalled();});++ it('keeps the connection when the feature gate check itself throws', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'wechat'+ ? [+ {+ applicationId: 'wechat-app',+ credentials: { botToken: 'token' },+ id: 'wechat-provider',+ settings: {},+ userId: 'u1',+ },+ ]+ : [],+ );+ mockResolveConnectionMode.mockReturnValue('polling');+ mockIsBotFeatureAccessAllowed.mockRejectedValue(new Error('subscription service down'));+ mockGatewayClient.getStatus.mockResolvedValue({ state: { status: 'connected' } });++ await service.ensureRunning();++ // Fail-open: no disconnect, provider stays in the desired set.+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });+ });++ describe('syncGatewayConnections reconciliation (via ensureRunning)', () => {+ const provider = {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ };++ beforeEach(() => {+ mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = '1';+ mockGatewayClient.isConfigured = true;+ mockGatewayClient.isEnabled = true;+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });+ });++ it('disconnects gateway connections with no matching enabled provider', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? [provider] : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: {},+ connections: [+ {+ connectionId: 'prov-1',+ platform: 'discord',+ state: { status: 'connected' },+ userId: 'u1',+ },+ {+ connectionId: 'stale-1',+ platform: 'wechat',+ state: { status: 'connected' },+ userId: 'gone',+ },+ ],+ total: 2,+ });++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('stale-1');+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalledWith('prov-1');+ // Desired + connected β no reconnect either.+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('never disconnects messenger-owned connections', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: {},+ connections: [+ {+ connectionId: 'messenger:discord:singleton',+ platform: 'discord',+ state: { status: 'connected' },+ userId: 'system',+ },+ {+ connectionId: 'messenger:telegram:user-u1',+ platform: 'telegram',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 2,+ });++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });++ it('includes registered-only ids (pruned from stats) in stale-connection cleanup', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['dormant-stale'] });++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('dormant-stale');+ });++ it('marks still-existing (disabled) providers as disconnected when stale-cleaned', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: {},+ connections: [+ {+ connectionId: 'prov-disabled',+ platform: 'discord',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });+ mockFindByIds.mockResolvedValue([+ { applicationId: 'app-disabled', enabled: false, id: 'prov-disabled', platform: 'discord' },+ ]);++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('prov-disabled');+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({+ applicationId: 'app-disabled',+ platform: 'discord',+ status: 'disconnected',+ });+ });++ it('skips stale-connection cleanup when a platform provider query fails', async () => {+ // wechat providers fail to load β desired set incomplete β a healthy+ // wechat connection must NOT be treated as stale.+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) => {+ if (platform === 'wechat') throw new Error('db timeout');+ return [];+ });+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: {},+ connections: [+ {+ connectionId: 'wechat-prov',+ platform: 'wechat',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });++ it('still cleans live stale connections when registered-ids is unavailable', async () => {+ // Mid-rollout: gateway without /api/admin/registered-ids. The stats+ // snapshot alone must keep the stale pass alive for live connections,+ // while desired providers missing from the partial snapshot fall back+ // to per-connection status checks instead of being treated as+ // disconnected (which would wake dormant DOs).+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? [provider] : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: {},+ connections: [+ {+ connectionId: 'stale-live',+ platform: 'wechat',+ state: { status: 'connected' },+ userId: 'gone',+ },+ ],+ total: 1,+ });+ mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('404 not found'));+ mockGatewayClient.getStatus.mockResolvedValue({ state: { status: 'dormant' } });++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('stale-live');+ // prov-1 missing from the incomplete snapshot β ask the DO, find it+ // dormant, leave it alone.+ expect(mockGatewayClient.getStatus).toHaveBeenCalledWith('prov-1');+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalledWith('prov-1');+ });++ it('skips stale cleanup entirely when the provider recheck query fails', async () => {+ // Treating a failed recheck as "no rows" would bypass the TOCTOU guard+ // and could tear down a provider enabled mid-sync.+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: {},+ connections: [+ {+ connectionId: 'stale-1',+ platform: 'discord',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });+ mockFindByIds.mockRejectedValue(new Error('db timeout'));++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });++ it('disconnects the old DO of a webhook-switched provider without marking it disconnected', async () => {+ // An enabled provider switched from persistent to webhook mode: its old+ // gateway DO is stale and must go, but the row is served by the webhook+ // registration now β writing `disconnected` would make a working+ // channel look off (webhook-mode refreshes return the cached snapshot).+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockResolveConnectionMode.mockReturnValue('webhook');+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: {},+ connections: [+ {+ connectionId: 'prov-webhook',+ platform: 'discord',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });+ mockFindByIds.mockResolvedValue([+ {+ applicationId: 'app-webhook',+ enabled: true,+ id: 'prov-webhook',+ platform: 'discord',+ settings: {},+ },+ ]);++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('prov-webhook');+ expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalledWith(+ expect.objectContaining({ applicationId: 'app-webhook', status: 'disconnected' }),+ );+ });++ it('does not disconnect a provider enabled after the desired snapshot was built', async () => {+ // TOCTOU race: the user enables + connects a provider while the sync is+ // between buildDesiredConnections and fetchActualConnections. It shows+ // up in `actual` but not in `desired` β the fresh row recheck must keep+ // it connected.+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: {},+ connections: [+ {+ connectionId: 'prov-race',+ platform: 'discord',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });+ mockFindByIds.mockResolvedValue([+ {+ applicationId: 'app-race',+ enabled: true,+ id: 'prov-race',+ platform: 'discord',+ settings: {},+ },+ ]);++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalledWith(+ expect.objectContaining({ applicationId: 'app-race', status: 'disconnected' }),+ );+ });++ it('uses the stats snapshot instead of per-connection status calls', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? [provider] : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: {},+ connections: [+ {+ connectionId: 'prov-1',+ platform: 'discord',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });++ await service.ensureRunning();++ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('connects desired providers missing from the gateway snapshot', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? [provider] : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });++ await service.ensureRunning();++ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'prov-1', platform: 'discord' }),+ );+ });++ it('keeps (never stale-disconnects, never reconnects) providers whose credentials are undecryptable', async () => {+ // KEY_VAULTS_SECRET mishap scenario: the model returns the row with+ // empty credentials instead of dropping it β the connection must stay+ // untouched rather than being treated as stale.+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord'+ ? [{ applicationId: 'app-1', credentials: {}, id: 'prov-1', settings: {}, userId: 'u1' }]+ : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: {},+ connections: [+ {+ connectionId: 'prov-1',+ platform: 'discord',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('requests the full enabled set including undecryptable rows', async () => {+ await service.ensureRunning();++ expect(mockFindEnabledByPlatform).toHaveBeenCalledWith(+ expect.anything(),+ expect.any(String),+ expect.anything(),+ { includeUndecryptable: true },+ );+ });++ it('asks the DO for status when the id is registered but pruned from stats', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? [provider] : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });+ mockGatewayClient.getStatus.mockResolvedValue({ state: { status: 'dormant' } });++ await service.ensureRunning();++ expect(mockGatewayClient.getStatus).toHaveBeenCalledWith('prov-1');+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });});});diff --git a/apps/server/src/services/gateway/index.ts b/apps/server/src/services/gateway/index.tsindex c48cec99643..3098a92767f 100644--- a/apps/server/src/services/gateway/index.ts+++ b/apps/server/src/services/gateway/index.ts@@ -1,4 +1,5 @@import debug from 'debug';+import pMap from 'p-map';import {assertBotFeatureAccess,@@ -7,10 +8,14 @@ import {} from '@/business/server/bot/featureAccess';import type { MessengerPlatform } from '@/config/messenger';import { getServerDB } from '@/database/core/db-adaptor';-import { AgentBotProviderModel } from '@/database/models/agentBotProvider';+import {+ AgentBotProviderModel,+ type DecryptedBotProvider,+} from '@/database/models/agentBotProvider';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import {getInstallationStore,+ isMessengerConnectionId,messengerConnectionIdForUser,} from '@/server/services/messenger/installations';import { messengerPlatformRegistry } from '@/server/services/messenger/platforms';@@ -40,6 +45,39 @@ const USER_MESSENGER_CONN_TTL_MS = 30 * 60 * 1000;const USER_MESSENGER_CONN_LRU_CAPACITY = 5000;const userMessengerConnections = new Map<string, number>();+/**+ * Cap on concurrent gateway calls during reconciliation. The gateway fans out+ * to one Durable Object per connection, so bursts mostly stress the Worker+ * router β this is about keeping the sync's own fetch fan-out (and DB status+ * writes) bounded as the connection count grows.+ */+const GATEWAY_SYNC_CONCURRENCY = 8;++/**+ * Blast-radius cap for the stale-connection disconnect pass: even with+ * cleanup enforced, one sync round disconnects at most this many connections.+ * A desired-set bug can then cost one bounded, observable batch per cron round+ * instead of the whole fleet; genuine mass cleanup still converges over a few+ * rounds.+ */+const GATEWAY_SYNC_STALE_DISCONNECT_LIMIT = 50;++interface DesiredGatewayConnection {+ connectionMode: ConnectionMode;+ platform: string;+ provider: DecryptedBotProvider;+}++interface ActualConnectionsSnapshot {+ /**+ * False when the registered-ids call failed and the snapshot only covers+ * live stats β dormant/hibernated connections may be missing from the map.+ */+ complete: boolean;+ /** connectionId β gateway status, or null for registered-only (pruned) ids. */+ connections: Map<string, string | null>;+}+function mapGatewayStatusToRuntimeStatus(status: MessageGatewayConnectionStatus['state']['status'],): BotRuntimeStatus {@@ -110,155 +148,391 @@ export class GatewayService {}/**- * Sync all enabled bots to the external message-gateway.- * Called on startup to recover connections after LobeHub restarts.+ * Reconcile the external message-gateway against the database.+ *+ * Desired state = enabled persistent-mode providers whose owner passes the+ * bot feature gate. Actual state = every connection the gateway still holds+ * (live stats βͺ registered ids). The diff runs both ways:+ *+ * - actual β desired β disconnect. Covers deleted/disabled providers,+ * downgraded owners, and providers switched to webhook mode β the stale+ * connections that a connect-only sync never visits.+ * - desired β actual β connect (unless the gateway reports the connection+ * as connected/connecting/dormant/error).+ *+ * Called from the gateway cron; also recovers connections after restarts.*/private async syncGatewayConnections(): Promise<void> {+ const startedAt = Date.now();const client = getMessageGatewayClient();const serverDB = await getServerDB();const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();- let totalSynced = 0;- let totalSkipped = 0;- let totalFailed = 0;+ const { desired, desiredComplete, gated } = await this.buildDesiredConnections(+ serverDB,+ gateKeeper,+ client,+ );++ // Fetch actual AFTER the gated disconnects above so those ids have already+ // dropped out of the gateway's view and don't get double-counted as stale.+ const actual = await this.fetchActualConnections(client);++ // A partial desired set would make healthy connections look stale, so only+ // run the disconnect pass when every platform loaded successfully. A+ // partial ACTUAL set is fine β the pass only disconnects ids it can see.+ let stale = 0;+ if (actual && desiredComplete) {+ stale = await this.disconnectStaleConnections(client, serverDB, actual.connections, desired);+ } else if (actual) {+ log('Gateway sync: desired set incomplete, skipping stale-connection cleanup this round');+ }++ // ββ desired β actual β connect ββ++ let connected = 0;+ let skipped = 0;+ let failed = 0;++ await pMap(+ desired.values(),+ async ({ connectionMode, platform, provider }) => {+ try {+ // Credentials missing/undecryptable: the provider is still desired+ // (protected from the stale pass) but a connect attempt can only+ // fail β leave whatever connection state the gateway already holds.+ if (Object.keys(provider.credentials).length === 0) {+ skipped++;+ log('Gateway sync: %s credentials unavailable, skipping connect', provider.id);+ return;+ }++ const status = await this.resolveGatewayStatus(client, provider.id, actual);++ if (status === 'connected' || status === 'connecting') {+ skipped++;+ log('Gateway sync: %s already %s, skipping', provider.id, status);+ return;+ }+ // Dormant: gateway is running sparse alarm-driven polling and will+ // self-wake when a message arrives. Reconnecting here would defeat+ // the purpose β only manual reconnect (startClient) should override.+ if (status === 'dormant') {+ skipped++;+ log('Gateway sync: %s dormant, skipping (DO is sparse-polling)', provider.id);+ return;+ }+ // "error" means credential/config issue (e.g. WeChat session expired+ // because the account connected elsewhere). Auto-retry is pointless β+ // only user action (saving new credentials) can fix it.+ if (status === 'error') {+ skipped++;+ log('Gateway sync: %s in error state, skipping', provider.id);+ return;+ }++ const webhookPath = `/api/agent/webhooks/${platform}/${provider.applicationId}`;+ const result = await client.connect({+ applicationId: provider.applicationId,+ connectionId: provider.id,+ connectionMode,+ credentials: provider.credentials,+ platform,+ userId: provider.userId,+ webhookPath,+ });++ // Gateway returns "connecting" for async persistent connections+ // (e.g. Discord WebSocket), "connected" for sync webhook-mode.+ await updateBotRuntimeStatus({+ applicationId: provider.applicationId,+ platform,+ status:+ result.status === 'connected'+ ? BOT_RUNTIME_STATUSES.connected+ : BOT_RUNTIME_STATUSES.starting,+ });++ connected++;+ log('Gateway sync: %s %s:%s', result.status, platform, provider.applicationId);+ } catch (err) {+ failed++;+ log('Gateway sync: failed to connect %s:%s: %O', platform, provider.applicationId, err);+ }+ },+ { concurrency: GATEWAY_SYNC_CONCURRENCY },+ );++ log(+ 'Gateway sync complete in %dms: desired=%d actual=%s connected=%d skipped=%d gated=%d stale=%d failed=%d',+ Date.now() - startedAt,+ desired.size,+ actual ? actual.connections.size : 'unavailable',+ connected,+ skipped,+ gated,+ stale,+ failed,+ );+ }++ /**+ * Build the set of connections that SHOULD exist on the gateway: enabled+ * persistent-mode providers whose owner passes the bot feature gate.+ *+ * Paid-gated providers are disconnected inline (the generic stale pass+ * can't produce their user-facing blocked message) and excluded from the+ * desired set. If the gate check itself errors, the provider is kept in+ * desired β a flaky subscription lookup must not tear down a healthy+ * connection.+ */+ private async buildDesiredConnections(+ serverDB: Awaited<ReturnType<typeof getServerDB>>,+ gateKeeper: KeyVaultsGateKeeper,+ client: ReturnType<typeof getMessageGatewayClient>,+ ): Promise<{+ desired: Map<string, DesiredGatewayConnection>;+ desiredComplete: boolean;+ gated: number;+ }> {+ const desired = new Map<string, DesiredGatewayConnection>();+ let desiredComplete = true;+ let gated = 0;- // Sync all registered platformsfor (const definition of platformRegistry.listPlatforms()) {const platform = definition.id;try {+ // includeUndecryptable: rows whose credentials can't be decrypted stay+ // in the desired set (with empty credentials) so a KEY_VAULTS_SECRET+ // mishap degrades to "no reconnects" instead of mass-disconnecting+ // every healthy connection as stale.const providers = await AgentBotProviderModel.findEnabledByPlatform(serverDB,platform,gateKeeper,+ { includeUndecryptable: true },);- let synced = 0;- let skippedWebhook = 0;- let skippedConnected = 0;- let failed = 0;-for (const provider of providers) {- try {- const definition = platformRegistry.getPlatform(platform);- const connectionMode = resolveConnectionMode(definition, provider.settings);-- // Webhook-mode platforms don't need persistent gateway connections.- // The webhook URL is set once when the user saves the bot config- // (via startClientViaGateway). No action needed during periodic sync.- if (connectionMode === 'webhook') {- skippedWebhook++;- continue;- }+ const connectionMode = resolveConnectionMode(definition, provider.settings);- const accessParams = {+ // Webhook-mode platforms don't need persistent gateway connections.+ // The webhook URL is set once when the user saves the bot config+ // (via startClientViaGateway). No action needed during periodic sync.+ if (connectionMode === 'webhook') continue;++ let allowed = true;+ try {+ allowed = await isBotFeatureAccessAllowed({applicationId: provider.applicationId,platform,userId: provider.userId,workspaceId: provider.workspaceId ?? undefined,- };- if (!(await isBotFeatureAccessAllowed(accessParams))) {- skippedConnected++;- try {- await client.disconnect(provider.id);- } catch (err) {- log('Gateway sync: paid-gated disconnect failed %s: %O', provider.id, err);- }- await updateBotRuntimeStatus({- applicationId: provider.applicationId,- errorMessage: getBotFeatureBlockedMessage(- platform,- provider.workspaceId ? 'workspace' : 'personal',- ),- platform,- status: BOT_RUNTIME_STATUSES.failed,- });- log('Gateway sync: paid-gated %s:%s, disconnected', platform, provider.applicationId);- continue;- }+ });+ } catch (err) {+ log(+ 'Gateway sync: feature gate check failed %s, keeping connection: %O',+ provider.id,+ err,+ );+ }- // For persistent connections, check gateway status before reconnecting+ if (!allowed) {+ gated++;try {- const status = await client.getStatus(provider.id);- if (status.state.status === 'connected' || status.state.status === 'connecting') {- skippedConnected++;- log('Gateway sync: %s already %s, skipping', provider.id, status.state.status);- continue;- }- // Dormant: gateway is running sparse alarm-driven polling and will- // self-wake when a message arrives. Reconnecting here would defeat- // the purpose β only manual reconnect (startClient) should override.- if (status.state.status === 'dormant') {- skippedConnected++;- log('Gateway sync: %s dormant, skipping (DO is sparse-polling)', provider.id);- continue;- }- // "error" means credential/config issue (e.g. session expired, unauthorized).- // Auto-retry is pointless β only user action (saving new credentials) can fix it.- if (status.state.status === 'error') {- skippedConnected++;- log('Gateway sync: %s in error (%s), skipping', provider.id, status.state.error);- continue;- }- } catch {- // Status check failed β try to connect+ await client.disconnect(provider.id);+ } catch (err) {+ log('Gateway sync: paid-gated disconnect failed %s: %O', provider.id, err);}-- const webhookPath = `/api/agent/webhooks/${platform}/${provider.applicationId}`;- const result = await client.connect({+ await updateBotRuntimeStatus({applicationId: provider.applicationId,- connectionId: provider.id,- connectionMode,- credentials: provider.credentials,+ errorMessage: getBotFeatureBlockedMessage(+ platform,+ provider.workspaceId ? 'workspace' : 'personal',+ ),platform,- userId: provider.userId,- webhookPath,+ status: BOT_RUNTIME_STATUSES.failed,});+ log('Gateway sync: paid-gated %s:%s, disconnected', platform, provider.applicationId);+ continue;+ }- // Gateway returns "connecting" for async persistent connections- // (e.g. Discord WebSocket), "connected" for sync webhook-mode.- const runtimeStatus =- result.status === 'connected'- ? BOT_RUNTIME_STATUSES.connected- : BOT_RUNTIME_STATUSES.starting;+ desired.set(provider.id, { connectionMode, platform, provider });+ }+ } catch (err) {+ desiredComplete = false;+ log('Gateway sync: error loading providers for platform %s: %O', platform, err);+ }+ }++ return { desired, desiredComplete, gated };+ }++ /**+ * Snapshot the gateway's view of existing connections: live stats (with+ * status) unioned with registered ids (dormant/hibernated connections the+ * AdminDO stats already pruned β status unknown, hence `null`).+ *+ * Returns null when stats are unavailable; callers then fall back to+ * per-connection status checks and skip stale-connection cleanup. The+ * registered-ids call is best-effort: an older gateway without the admin+ * endpoint (mid-rollout) or a transient failure must not disable+ * reconciliation for the live connections stats already covers β the stale+ * pass only ever disconnects ids present in the snapshot, so a partial+ * snapshot just cleans up less. `complete: false` marks the partial case so+ * status resolution won't treat "missing from snapshot" as disconnected.+ */+ private async fetchActualConnections(+ client: ReturnType<typeof getMessageGatewayClient>,+ ): Promise<ActualConnectionsSnapshot | null> {+ const connections = new Map<string, string | null>();++ try {+ const stats = await client.getStats();+ for (const conn of stats.connections) {+ connections.set(conn.connectionId, conn.state.status);+ }+ } catch (err) {+ log('Gateway sync: failed to fetch gateway stats snapshot: %O', err);+ return null;+ }++ let complete = true;+ try {+ const { ids } = await client.getRegisteredIds();+ for (const id of ids) {+ if (!connections.has(id)) connections.set(id, null);+ }+ } catch (err) {+ complete = false;+ log('Gateway sync: registered-ids unavailable, using stats-only snapshot: %O', err);+ }++ return { complete, connections };+ }++ /**+ * actual β desired β disconnect: connections the gateway still holds whose+ * provider was deleted, disabled, or no longer wants a persistent+ * connection. Messenger-owned connections (per-user typing DOs, SystemBot+ * singletons) carry the `messenger:` prefix and are managed elsewhere β+ * never touch them here.+ */+ private async disconnectStaleConnections(+ client: ReturnType<typeof getMessageGatewayClient>,+ serverDB: Awaited<ReturnType<typeof getServerDB>>,+ actual: Map<string, string | null>,+ desired: Map<string, DesiredGatewayConnection>,+ ): Promise<number> {+ const allStaleIds = [...actual.keys()].filter(+ (id) => !desired.has(id) && !isMessengerConnectionId(id),+ );+ if (allStaleIds.length === 0) return 0;++ const staleIds = allStaleIds.slice(0, GATEWAY_SYNC_STALE_DISCONNECT_LIMIT);+ if (staleIds.length < allStaleIds.length) {+ log(+ 'Gateway sync: capping stale disconnects to %d of %d this round',+ staleIds.length,+ allStaleIds.length,+ );+ }++ // Fresh provider rows drive the TOCTOU guard and the status writes below.+ // If the recheck itself fails, treating it as "no rows" would bypass both+ // guards and could tear down a provider enabled mid-sync β skip the whole+ // pass instead; next round retries with a healthy lookup.+ const rows = await AgentBotProviderModel.findByIds(serverDB, staleIds).catch((err) => {+ log('Gateway sync: stale provider recheck failed, skipping cleanup this round: %O', err);+ return null;+ });+ if (!rows) return 0;+ const rowById = new Map(rows.map((row) => [row.id, row]));+ let disconnected = 0;++ await pMap(+ staleIds,+ async (id) => {+ try {+ const row = rowById.get(id);++ // TOCTOU guard: a provider enabled (and connected) between the+ // desired snapshot and the actual fetch shows up in `actual` but not+ // in `desired`. These rows were queried after both snapshots, so+ // trust them: an enabled persistent-mode row is not stale β leave it+ // for the next round to classify with a fresh desired set.+ if (+ row?.enabled &&+ resolveConnectionMode(platformRegistry.getPlatform(row.platform), row.settings) !==+ 'webhook'+ ) {+ log('Gateway sync: %s enabled during sync, skipping stale disconnect', id);+ return;+ }++ await client.disconnect(id);+ disconnected++;++ // Only disabled rows get their runtime snapshot marked+ // disconnected. After the guard above, the remaining enabled rows+ // are webhook-mode: they just lost their old persistent DO, but the+ // webhook registration is what serves them now β and webhook-mode+ // refreshes return the cached snapshot, so overwriting it would+ // make a working channel look disconnected.+ if (row && !row.enabled) {await updateBotRuntimeStatus({- applicationId: provider.applicationId,- platform,- status: runtimeStatus,+ applicationId: row.applicationId,+ platform: row.platform,+ status: BOT_RUNTIME_STATUSES.disconnected,});-- synced++;- log('Gateway sync: %s %s:%s', result.status, platform, provider.applicationId);- } catch (err) {- failed++;- log('Gateway sync: failed to connect %s:%s: %O', platform, provider.applicationId, err);}+ log(+ 'Gateway sync: disconnected stale connection %s (%s)',+ id,+ row ? (row.enabled ? 'webhook-mode provider' : 'disabled provider') : 'no provider row',+ );+ } catch (err) {+ log('Gateway sync: failed to disconnect stale connection %s: %O', id, err);}+ },+ { concurrency: GATEWAY_SYNC_CONCURRENCY },+ );- log(- 'Gateway sync: %s β total=%d synced=%d skippedWebhook=%d skippedConnected=%d failed=%d',- platform,- providers.length,- synced,- skippedWebhook,- skippedConnected,- failed,- );+ return disconnected;+ }- totalSynced += synced;- totalSkipped += skippedWebhook + skippedConnected;- totalFailed += failed;- } catch (err) {- log('Gateway sync: error syncing platform %s: %O', platform, err);- }+ /**+ * Resolve a connection's gateway status from the reconciliation snapshot,+ * falling back to a per-connection status call when the snapshot is missing+ * (admin endpoints down) or only knows the id from the registered set.+ * Returns undefined when the status can't be determined β callers treat+ * that as "attempt connect" (the gateway upserts on connectionId, so a+ * redundant connect is safe).+ */+ private async resolveGatewayStatus(+ client: ReturnType<typeof getMessageGatewayClient>,+ connectionId: string,+ actual: ActualConnectionsSnapshot | null,+ ): Promise<string | undefined> {+ if (actual) {+ const snapshot = actual.connections.get(connectionId);+ // Unknown to the gateway entirely β connect. Only trustworthy when the+ // snapshot is complete β a stats-only snapshot misses dormant ids, and+ // treating those as disconnected would reconnect sparse-polling DOs.+ if (snapshot === undefined && actual.complete) return 'disconnected';+ // Known status from stats.+ if (snapshot !== undefined && snapshot !== null) return snapshot;+ // Registered but pruned from stats (likely dormant), or missing from an+ // incomplete snapshot β ask the DO itself.}- log(- 'Gateway sync complete: synced=%d skipped=%d failed=%d',- totalSynced,- totalSkipped,- totalFailed,- );+ try {+ const status = await client.getStatus(connectionId);+ return status.state.status;+ } catch {+ return undefined;+ }}async stop(): Promise<void> {diff --git a/apps/server/src/services/messenger/installations/index.ts b/apps/server/src/services/messenger/installations/index.tsindex c5f814940db..00316436af4 100644--- a/apps/server/src/services/messenger/installations/index.ts+++ b/apps/server/src/services/messenger/installations/index.ts@@ -43,6 +43,18 @@ export const getInstallationStore = (const SINGLETON_SUFFIX = ':singleton';+/**+ * Every messenger-owned gateway connection (per-user typing DOs and SystemBot+ * singletons) carries this prefix, while agent-bot-provider connections use+ * the bare provider uuid. The gateway reconciliation sync relies on this to+ * tell which gateway connections it owns β messenger connections must never+ * be treated as bot-provider zombies.+ */+const MESSENGER_CONNECTION_ID_PREFIX = 'messenger:';++export const isMessengerConnectionId = (connectionId: string): boolean =>+ connectionId.startsWith(MESSENGER_CONNECTION_ID_PREFIX);+/*** Singleton gateway connectionId for a platform-level install.*diff --git a/packages/database/src/models/agentBotProvider.ts b/packages/database/src/models/agentBotProvider.tsindex f6993b8268f..436a5419a84 100644--- a/packages/database/src/models/agentBotProvider.ts+++ b/packages/database/src/models/agentBotProvider.ts@@ -1,4 +1,4 @@-import { and, desc, eq } from 'drizzle-orm';+import { and, desc, eq, inArray } from 'drizzle-orm';import type { AgentBotProviderItem, NewAgentBotProvider } from '../schemas';import { agentBotProviders } from '../schemas';@@ -10,6 +10,8 @@ interface GateKeeper {encrypt: (plaintext: string) => Promise<string>;}+const UUID_RE = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;+export interface DecryptedBotProvider extends Omit<AgentBotProviderItem, 'credentials'> {credentials: Record<string, string>;}@@ -245,10 +247,51 @@ export class AgentBotProviderModel {return decrypted;};+ /**+ * Look up providers by connection id across all users, without decrypting+ * credentials. Used by the gateway reconciliation sync to map stale gateway+ * connections back to their (possibly disabled) provider rows.+ *+ * Non-UUID ids are filtered out before querying: the gateway also tracks+ * connection ids that are not provider rows (e.g. system-bot registrations),+ * and a single non-UUID value in `inArray` on the uuid column fails the+ * whole query with a Postgres cast error.+ */+ static findByIds = async (+ db: LobeChatDatabase,+ ids: string[],+ ): Promise<+ Array<Pick<AgentBotProviderItem, 'applicationId' | 'enabled' | 'id' | 'platform' | 'settings'>>+ > => {+ const uuidIds = ids.filter((id) => UUID_RE.test(id));+ if (uuidIds.length === 0) return [];++ return db+ .select({+ applicationId: agentBotProviders.applicationId,+ enabled: agentBotProviders.enabled,+ id: agentBotProviders.id,+ platform: agentBotProviders.platform,+ settings: agentBotProviders.settings,+ })+ .from(agentBotProviders)+ .where(inArray(agentBotProviders.id, uuidIds));+ };+static findEnabledByPlatform = async (db: LobeChatDatabase,platform: string,gateKeeper?: GateKeeper,+ options?: {+ /**+ * Keep rows whose credentials are missing or fail to decrypt, with+ * `credentials: {}`. The reconciliation sync needs the full enabled set+ * to decide which gateway connections are stale β silently dropping+ * undecryptable rows (e.g. during a KEY_VAULTS_SECRET mishap) would make+ * every healthy connection look stale and mass-disconnect them.+ */+ includeUndecryptable?: boolean;+ },): Promise<DecryptedBotProvider[]> => {const results = await db.select()@@ -258,7 +301,10 @@ export class AgentBotProviderModel {const decrypted: DecryptedBotProvider[] = [];for (const r of results) {- if (!r.credentials) continue;+ if (!r.credentials) {+ if (options?.includeUndecryptable) decrypted.push({ ...r, credentials: {} });+ continue;+ }try {const credentials = gateKeeper@@ -267,7 +313,8 @@ export class AgentBotProviderModel {decrypted.push({ ...r, credentials });} catch {- // skip rows with invalid / undecryptable credentials+ // Invalid / undecryptable credentials.+ if (options?.includeUndecryptable) decrypted.push({ ...r, credentials: {} });}}