π€― 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
β»οΈ refactor(server): split the 1918-line GatewayService into cohesive modules (#21154)
Arvin Xufe72448f1261
diff --git a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts b/apps/server/src/services/gateway/__tests__/GatewayService.test.tsdeleted file mode 100644index 31335d3be76..00000000000--- a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts+++ /dev/null@@ -1,2005 +0,0 @@-// @vitest-environment node-import { beforeEach, describe, expect, it, vi } from 'vitest';--// βββ Import after mocks βββ-import { GatewayService } from '../index';--// βββ Hoisted mocks βββ--const mockGatewayClient = vi.hoisted(() => ({- connect: vi.fn(),- disconnect: vi.fn(),- disconnectAll: vi.fn(),- getCapabilities: vi.fn(),- getRegisteredIds: vi.fn(),- getStats: vi.fn(),- getStatus: vi.fn(),- isConfigured: false,- isEnabled: false,-}));--const mockGatewayEnv = vi.hoisted(() => ({- MESSAGE_GATEWAY_ENABLED: undefined as string | undefined,- MESSAGE_GATEWAY_SERVICE_TOKEN: 'gateway-service-token' as string | undefined,-}));--// Second gateway host (Node). `configured` + `platforms` drive the mocked-// host-routing helpers below, mirroring MESSAGE_GATEWAY_NODE_URL /-// MESSAGE_GATEWAY_NODE_PLATFORMS.-const mockNodeGatewayClient = vi.hoisted(() => ({- connect: vi.fn(),- disconnect: vi.fn(),- disconnectAll: vi.fn(),- getCapabilities: vi.fn(),- getRegisteredIds: vi.fn(),- getStats: vi.fn(),- getStatus: vi.fn(),- isConfigured: false,- isEnabled: false,-}));-const mockNodeGateway = vi.hoisted(() => ({ configured: false, platforms: [] as string[] }));--const mockGatewayManager = vi.hoisted(() => ({- isRunning: false,- start: vi.fn(),- startClient: vi.fn(),- stop: vi.fn(),- stopClient: vi.fn(),-}));--const mockFindEnabledByPlatform = vi.hoisted(() => vi.fn());-const mockFindByAgentId = vi.hoisted(() => vi.fn());-const mockFindByIds = vi.hoisted(() => vi.fn());-const mockFindEnabledByPlatformAndAppId = vi.hoisted(() => vi.fn());-const mockGetServerDB = vi.hoisted(() => vi.fn());-const mockInitWithEnvKey = vi.hoisted(() => vi.fn());-const mockUpdateBotRuntimeStatus = vi.hoisted(() => vi.fn());-const mockResolveConnectionMode = vi.hoisted(() => vi.fn());-const mockIsBotFeatureAccessAllowed = vi.hoisted(() => vi.fn());-const mockGetBotFeatureBlockedMessage = vi.hoisted(() => vi.fn());-const mockGetBotRuntimeStatus = vi.hoisted(() => vi.fn());-const mockResolveMessengerInstallation = vi.hoisted(() => vi.fn());--// βββ Module mocks βββ--vi.mock('@/envs/gateway', () => ({- gatewayEnv: mockGatewayEnv,-}));--vi.mock('../MessageGatewayClient', () => {- const resolveMessageGatewayHost = (platform?: string) =>- mockNodeGateway.configured && platform && mockNodeGateway.platforms.includes(platform)- ? 'node'- : 'default';- return {- getConfiguredMessageGatewayHosts: () =>- mockNodeGateway.configured ? ['default', 'node'] : ['default'],- getMessageGatewayClient: (platform?: string) =>- resolveMessageGatewayHost(platform) === 'node' ? mockNodeGatewayClient : mockGatewayClient,- getMessageGatewayClientForHost: (host: string) =>- host === 'node' ? mockNodeGatewayClient : mockGatewayClient,- // Production anchors gateway mode on the DEFAULT host: every platform not- // routed to node falls back to it, and the node gateway cannot host those- // platform kinds at all.- isAnyMessageGatewayEnabled: () => mockGatewayClient.isEnabled,- isMessageGatewayHostConfigured: (host: string) => {- const client = host === 'node' ? mockNodeGatewayClient : mockGatewayClient;- // Production defines isEnabled as (ENABLED === '1' && isConfigured), so- // an enabled client is configured by construction. These fixtures set- // the two flags independently, so mirror the real implication here- // rather than letting a test express a state the runtime cannot reach.- return client.isConfigured || client.isEnabled;- },- resolveMessageGatewayHost,- };-});--const mockFindAllLinksByPlatform = vi.hoisted(() => vi.fn());--vi.mock('@/database/models/messengerAccountLink', () => ({- MessengerAccountLinkModel: {- findAllByPlatformWithCredentials: mockFindAllLinksByPlatform,- },-}));--vi.mock('../GatewayManager', () => ({- createGatewayManager: () => mockGatewayManager,- getGatewayManager: () => (mockGatewayManager.isRunning ? mockGatewayManager : null),-}));--vi.mock('@/database/core/db-adaptor', () => ({- getServerDB: mockGetServerDB,-}));--vi.mock('@/database/models/agentBotProvider', () => ({- AgentBotProviderModel: {- findByAgentId: mockFindByAgentId,- findByIds: mockFindByIds,- findEnabledByPlatform: mockFindEnabledByPlatform,- findEnabledByPlatformAndAppId: mockFindEnabledByPlatformAndAppId,- },-}));--vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({- KeyVaultsGateKeeper: { initWithEnvKey: mockInitWithEnvKey },-}));--vi.mock('../runtimeStatus', () => ({- BOT_RUNTIME_STATUSES: {- connected: 'connected',- disconnected: 'disconnected',- dormant: 'dormant',- failed: 'failed',- queued: 'queued',- starting: 'starting',- },- getBotRuntimeStatus: mockGetBotRuntimeStatus,- updateBotRuntimeStatus: mockUpdateBotRuntimeStatus,-}));--vi.mock('@/business/server/bot/featureAccess', () => ({- assertBotFeatureAccess: vi.fn(),- getBotFeatureBlockedMessage: mockGetBotFeatureBlockedMessage,- isBotFeatureAccessAllowed: mockIsBotFeatureAccessAllowed,-}));--vi.mock('@/server/services/messenger/installations', () => ({- getInstallationStore: vi.fn(() => ({ resolveByKey: mockResolveMessengerInstallation })),- isMessengerConnectionId: (connectionId: string) => connectionId.startsWith('messenger:'),- messengerConnectionIdForUser: ({- connectionMode,- installationKey,- userId,- }: {- connectionMode?: string;- installationKey: string;- userId: string;- }) => {- if (connectionMode === 'websocket' && installationKey.endsWith(':singleton')) {- return `messenger:${installationKey.slice(0, -':singleton'.length)}:singleton`;- }- return `messenger:${installationKey}:user-${userId}`;- },-}));--vi.mock('@/server/services/messenger/platforms', () => ({- messengerPlatformRegistry: {- getPlatform: (platform: string) => ({- connectionMode:- platform === 'wechat' ? 'polling' : platform === 'discord' ? 'websocket' : 'webhook',- }),- listPlatforms: () => [- { connectionMode: 'websocket', id: 'discord' },- { connectionMode: 'webhook', id: 'slack' },- { connectionMode: 'polling', id: 'wechat' },- ],- },-}));--vi.mock('../../bot/platforms', () => ({- extractWatchKeywordEntries: (settings?: Record<string, unknown>) =>- Array.isArray(settings?.watchKeywords)- ? settings.watchKeywords.filter((e: any) => typeof e?.keyword === 'string' && e.keyword)- : [],- platformRegistry: {- getPlatform: (platform: string) => ({ id: platform }),- listPlatforms: () => [{ id: 'discord' }, { id: 'telegram' }, { id: 'wechat' }],- },- resolveConnectionMode: mockResolveConnectionMode,-}));--describe('GatewayService', () => {- let service: GatewayService;-- beforeEach(() => {- vi.clearAllMocks();- mockGatewayClient.isConfigured = false;- mockGatewayClient.isEnabled = false;- mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = undefined;- mockGatewayManager.isRunning = false;- mockGetServerDB.mockResolvedValue({});- mockInitWithEnvKey.mockResolvedValue({});- mockFindEnabledByPlatform.mockResolvedValue([]);- mockFindByAgentId.mockResolvedValue([]);- mockFindByIds.mockResolvedValue([]);- mockFindEnabledByPlatformAndAppId.mockResolvedValue(null);- // Default: neither host describes itself. The Cloudflare gateway has no- // capabilities endpoint at all, so "makes no claim" is the normal case and- // must never be read as "serves nothing".- mockGatewayClient.getCapabilities.mockResolvedValue(null);- mockNodeGatewayClient.getCapabilities.mockResolvedValue(null);- // 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'));- mockNodeGateway.configured = false;- mockNodeGateway.platforms = [];- mockNodeGatewayClient.isConfigured = false;- mockNodeGatewayClient.isEnabled = false;- mockNodeGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });- mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });- mockFindAllLinksByPlatform.mockResolvedValue([]);- mockUpdateBotRuntimeStatus.mockResolvedValue({});- mockIsBotFeatureAccessAllowed.mockResolvedValue(true);- mockGetBotFeatureBlockedMessage.mockReturnValue('This bot channel requires a paid plan.');- mockGetBotRuntimeStatus.mockResolvedValue({});- mockResolveMessengerInstallation.mockResolvedValue(null);- service = new GatewayService();- });-- // βββ useMessageGateway βββ-- describe('useMessageGateway', () => {- it('returns false when client is not enabled', () => {- mockGatewayClient.isEnabled = false;- expect(service.useMessageGateway).toBe(false);- });-- it('returns true when client is enabled', () => {- mockGatewayClient.isEnabled = true;- expect(service.useMessageGateway).toBe(true);- });- });-- describe('runtime status refresh', () => {- beforeEach(() => {- mockGatewayClient.isEnabled = true;- mockResolveConnectionMode.mockReturnValue('websocket');- });-- it('preserves gateway error codes during a single refresh', async () => {- mockFindEnabledByPlatformAndAppId.mockResolvedValue({ id: 'prov-1', settings: {} });- mockGatewayClient.getStatus.mockResolvedValue({- state: { error: 'invalid token', errorCode: 'invalid_credentials', status: 'error' },- });-- await service.refreshBotRuntimeStatus('discord', 'app-1');-- expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({- applicationId: 'app-1',- errorCode: 'invalid_credentials',- errorMessage: 'invalid token',- platform: 'discord',- status: 'failed',- });- });-- it('preserves gateway error codes during an agent-wide refresh', async () => {- mockFindByAgentId.mockResolvedValue([- {- applicationId: 'app-1',- enabled: true,- id: 'prov-1',- platform: 'discord',- settings: {},- },- ]);- mockGatewayClient.getStatus.mockResolvedValue({- state: { error: 'invalid token', errorCode: 'invalid_credentials', status: 'error' },- });-- await service.refreshBotRuntimeStatusesByAgent('agent-1');-- expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({- applicationId: 'app-1',- errorCode: 'invalid_credentials',- errorMessage: 'invalid token',- platform: 'discord',- status: 'failed',- });- });- });-- // βββ ensureRunning βββ-- describe('ensureRunning', () => {- describe('in-process mode (gateway disabled)', () => {- it('starts local GatewayManager', async () => {- await service.ensureRunning();-- expect(mockGatewayManager.start).toHaveBeenCalled();- });-- it('skips start if GatewayManager already running', async () => {- mockGatewayManager.isRunning = true;-- await service.ensureRunning();-- expect(mockGatewayManager.start).not.toHaveBeenCalled();- });- });-- describe('gateway mode (ENABLED=1)', () => {- beforeEach(() => {- mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = '1';- mockGatewayClient.isConfigured = true;- mockGatewayClient.isEnabled = true;- });-- it('calls syncGatewayConnections instead of starting local manager', async () => {- await service.ensureRunning();-- expect(mockGatewayManager.start).not.toHaveBeenCalled();- });- });- });-- describe('per-user messenger lifecycle', () => {- it('registers WeChat as a real polling connection with the complete QR credential bundle', async () => {- mockGatewayClient.isEnabled = true;- mockResolveMessengerInstallation.mockResolvedValue({- applicationId: '[email protected]',- baseUrl: 'https://ilink.example.com',- botId: '[email protected]',- botToken: 'secret-token',- });-- const connectionId = await service.ensureUserMessengerConnected({- installationKey: 'wechat:[email protected]',- platform: 'wechat',- userId: 'user-1',- });-- expect(connectionId).toBe('messenger:wechat:[email protected]:user-user-1');- expect(mockGatewayClient.connect).toHaveBeenCalledWith({- applicationId: '[email protected]',- // Per-user messenger connections have no bot-provider settings row, so- // gated capabilities always resolve to disabled.- capabilities: { messageMonitoring: { enabled: false } },- connectionId,- connectionMode: 'polling',- credentials: {- baseUrl: 'https://ilink.example.com',- botId: '[email protected]',- botToken: 'secret-token',- webhookToken: 'gateway-service-token',- },- platform: 'wechat',- userId: 'user-1',- webhookPath: '/api/agent/messenger/webhooks/wechat',- });- });-- it('disconnects a user WeChat poller even when active gateway flows are disabled', async () => {- mockGatewayClient.isConfigured = true;- mockGatewayClient.isEnabled = false;-- await service.disconnectUserMessenger({- installationKey: 'wechat:[email protected]',- platform: 'wechat',- userId: 'user-1',- });-- expect(mockGatewayClient.disconnect).toHaveBeenCalledWith(- 'messenger:wechat:[email protected]:user-user-1',- );- });- });-- // βββ syncGatewayConnections βββ-- describe('syncGatewayConnections (via ensureRunning)', () => {- beforeEach(() => {- mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = '1';- mockGatewayClient.isConfigured = true;- mockGatewayClient.isEnabled = true;- mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });- });-- it('skips webhook-mode providers', async () => {- mockFindEnabledByPlatform.mockResolvedValue([- {- applicationId: 'app-1',- credentials: { token: 'x' },- id: 'prov-1',- settings: {},- userId: 'u1',- },- ]);- mockResolveConnectionMode.mockReturnValue('webhook');-- await service.ensureRunning();-- expect(mockGatewayClient.connect).not.toHaveBeenCalled();- });-- it('ensure-wakes a registered-only desired provider without probing status', async () => {- // Registered-only (pruned from stats) used to be skipped outright, but a- // stranded DO (alarm chain lost) looks exactly like this and sleeps- // forever unless woken. The wake is an `ensure` connect, never a status- // probe: parked connections answer 409 and keep their park.- mockFindEnabledByPlatform.mockResolvedValue([- {- applicationId: 'app-1',- credentials: { token: 'x' },- id: 'prov-1',- settings: {},- userId: 'u1',- },- ]);- mockResolveConnectionMode.mockReturnValue('websocket');- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });- mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });-- await service.ensureRunning();-- expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).toHaveBeenCalledWith(- expect.objectContaining({ connectionId: 'prov-1' }),- { ensure: true },- );- });-- it('connects disconnected providers', async () => {- 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.connect.mockResolvedValue({ status: 'connecting' });-- await service.ensureRunning();-- expect(mockGatewayClient.connect).toHaveBeenCalledWith(- expect.objectContaining({- applicationId: 'app-1',- connectionId: 'prov-1',- platform: 'discord',- }),- { ensure: true },- );- expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(- expect.objectContaining({ status: 'starting' }),- );- });-- it('persists a dormant ensure result as dormant, not starting', async () => {- // An `ensure` reconcile of a sparse-polling DO can legitimately return- // `dormant`; it must be mapped through the shared helper so it is not- // collapsed to `starting` (the DO sends no correcting callback).- 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.connect.mockResolvedValue({ status: 'dormant' });-- await service.ensureRunning();-- expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(- expect.objectContaining({ status: 'dormant' }),- );- expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalledWith(- expect.objectContaining({ status: 'starting' }),- );- });-- it('disconnects paid-only WeChat providers when the owner is on a free plan', async () => {- mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>- platform === 'wechat'- ? [- {- applicationId: 'wechat-app',- credentials: { botToken: 'token' },- id: 'wechat-provider',- settings: {},- userId: 'free-user',- },- ]- : [],- );- mockResolveConnectionMode.mockReturnValue('polling');- mockIsBotFeatureAccessAllowed.mockResolvedValue(false);- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });-- await service.ensureRunning();-- expect(mockIsBotFeatureAccessAllowed).toHaveBeenCalledWith({- applicationId: 'wechat-app',- platform: 'wechat',- userId: 'free-user',- workspaceId: undefined,- });- expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('wechat-provider');- expect(mockGatewayClient.connect).not.toHaveBeenCalled();- expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(- expect.objectContaining({- applicationId: 'wechat-app',- errorMessage: 'This bot channel requires a paid plan.',- platform: 'wechat',- status: 'failed',- }),- );- });-- it.each([- { snapshot: 'stats-only', statsUnavailable: false },- { snapshot: 'unavailable', statsUnavailable: true },- ])(- 'disconnects a paid-gated provider when the registry snapshot is $snapshot',- async ({ statsUnavailable }) => {- mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>- platform === 'wechat'- ? [- {- applicationId: 'wechat-app',- credentials: { botToken: 'token' },- id: 'wechat-provider',- settings: {},- userId: 'free-user',- },- ]- : [],- );- mockResolveConnectionMode.mockReturnValue('polling');- mockIsBotFeatureAccessAllowed.mockResolvedValue(false);- mockGatewayClient.getRegisteredIds.mockRejectedValue(- new Error('registered-ids unavailable'),- );- if (statsUnavailable) {- mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));- }-- await service.ensureRunning();-- expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('wechat-provider');- expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).not.toHaveBeenCalled();- },- );-- it('sets connected status for sync connect result', async () => {- mockFindEnabledByPlatform.mockResolvedValue([- {- applicationId: 'app-1',- credentials: { token: 'x' },- id: 'prov-1',- settings: {},- userId: 'u1',- },- ]);- mockResolveConnectionMode.mockReturnValue('websocket');- mockGatewayClient.connect.mockResolvedValue({ status: 'connected' });-- await service.ensureRunning();-- expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(- expect.objectContaining({ status: 'connected' }),- );- });-- it('defers desired providers when the gateway snapshot is unavailable', async () => {- mockFindEnabledByPlatform.mockResolvedValue([- {- applicationId: 'app-1',- credentials: { token: 'x' },- id: 'prov-1',- settings: {},- userId: 'u1',- },- ]);- mockResolveConnectionMode.mockReturnValue('websocket');- mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));- mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registered-ids unavailable'));-- await service.ensureRunning();-- expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).not.toHaveBeenCalled();- });-- it('handles connect failure gracefully', async () => {- mockFindEnabledByPlatform.mockResolvedValue([- {- applicationId: 'app-1',- credentials: { token: 'x' },- id: 'prov-1',- settings: {},- userId: 'u1',- },- ]);- mockResolveConnectionMode.mockReturnValue('websocket');- mockGatewayClient.connect.mockRejectedValue(new Error('timeout'));-- // Should not throw- 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.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });-- await service.ensureRunning();-- // Fail-open: no disconnect, provider stays in the desired set. As a- // desired registered-only id it may receive the idempotent ensure wake,- // which preserves whatever state the gateway holds.- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).not.toHaveBeenCalledWith(expect.anything(), {- ensure: false,- });- });-- it('does not repeatedly disconnect a gated provider absent from the gateway snapshot', async () => {- mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>- platform === 'wechat'- ? [- {- applicationId: 'wechat-app',- credentials: { botToken: 'token' },- id: 'wechat-provider',- settings: {},- userId: 'free-user',- },- ]- : [],- );- mockResolveConnectionMode.mockReturnValue('polling');- mockIsBotFeatureAccessAllowed.mockResolvedValue(false);-- await service.ensureRunning();-- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(- expect.objectContaining({- applicationId: 'wechat-app',- status: 'failed',- }),- );- });- });-- 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 are deferred- // instead of waking dormant DOs or being treated as disconnected.- 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');- expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- 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' }),- { ensure: true },- );- });-- 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('ensure-wakes registered-only desired ids instead of leaving them stranded', 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.connect.mockResolvedValue({ status: 'connecting' });-- await service.ensureRunning();-- expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).toHaveBeenCalledWith(- expect.objectContaining({ connectionId: 'prov-1' }),- { ensure: true },- );- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- });-- it('keeps a parked registered-only connection parked (ensure 409 is not a status reset)', 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.connect.mockRejectedValue(new Error('409 connection parked'));-- await service.ensureRunning();-- // The 409 must not overwrite the bot's runtime status with a fresh state.- expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalledWith(- expect.objectContaining({ applicationId: 'app-1', status: 'starting' }),- );- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- });-- it('reconnects a desired connection reported disconnected by stats without probing its DO', async () => {- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>- platform === 'discord' ? [provider] : [],- );- mockGatewayClient.getStats.mockResolvedValue({- byPlatform: {},- connections: [- {- connectionId: 'prov-1',- platform: 'discord',- state: { status: 'disconnected' },- userId: 'u1',- },- ],- total: 1,- });- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });- mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });-- await service.ensureRunning();-- expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).toHaveBeenCalledWith(- expect.objectContaining({ connectionId: 'prov-1' }),- { ensure: true },- );- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- });-- it('reconciles 2,000 registered connections with two snapshot requests and no per-connection probes', async () => {- const providers = Array.from({ length: 2000 }, (_, index) => ({- ...provider,- applicationId: `app-${index}`,- id: `prov-${index}`,- }));-- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>- platform === 'discord' ? providers : [],- );- mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });- mockGatewayClient.getRegisteredIds.mockResolvedValue({- ids: providers.map(({ id }) => id),- });-- mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });-- await service.ensureRunning();-- expect(mockGatewayClient.getStats).toHaveBeenCalledTimes(1);- expect(mockGatewayClient.getRegisteredIds).toHaveBeenCalledTimes(1);- expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- // Registered-only wakes are capped per round so a large fleet cannot- // turn the reconcile into a wake storm; the remainder waits for the- // next cron round.- expect(mockGatewayClient.connect).toHaveBeenCalledTimes(50);- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- });-- it('samples registered-only wakes instead of always burning the cap on the same prefix', async () => {- // A stable iteration order + head-first cap would starve ids after- // position 50 forever when the early ones stay registered-only (parked- // 409s). Force the sampler's rng to pick from the tail and assert the- // selection is not the head prefix.- const providers = Array.from({ length: 2000 }, (_, index) => ({- ...provider,- applicationId: `app-${index}`,- id: `prov-${index}`,- }));-- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>- platform === 'discord' ? providers : [],- );- mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });- mockGatewayClient.getRegisteredIds.mockResolvedValue({- ids: providers.map(({ id }) => id),- });- mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });-- const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0.999_999);- try {- await service.ensureRunning();- } finally {- randomSpy.mockRestore();- }-- expect(mockGatewayClient.connect).toHaveBeenCalledTimes(50);- const wokenIds = new Set(- mockGatewayClient.connect.mock.calls.map(- (call) => (call[0] as { connectionId: string }).connectionId,- ),- );- // rng pinned to ~1 β the sampler reaches the tail; the old head-first- // cap could only ever pick prov-0..prov-49 and would return exactly- // that prefix.- expect(wokenIds.has('prov-1999')).toBe(true);- const isHeadPrefix = [...wokenIds].every((id) => Number(id.split('-')[1]) < 50);- expect(isHeadPrefix).toBe(false);- });-- it('uses registered ids as a complete existence snapshot when stats is unavailable', async () => {- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>- platform === 'discord' ? [provider] : [],- );- mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });- mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });-- await service.ensureRunning();-- expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- // With no stats, every desired id is registered-only (status unknown) β- // still handled via the capped ensure wake, never a per-DO status probe.- expect(mockGatewayClient.connect).toHaveBeenCalledWith(- expect.objectContaining({ connectionId: 'prov-1' }),- { ensure: true },- );- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- });-- it('defers missing desired ids when registered ids are unavailable', async () => {- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>- platform === 'discord' ? [provider] : [],- );- mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });- mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registered unavailable'));-- await service.ensureRunning();-- expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).not.toHaveBeenCalled();- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- });- });-- describe('dual-host routing (node gateway configured)', () => {- beforeEach(() => {- mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = '1';- mockGatewayClient.isConfigured = true;- mockGatewayClient.isEnabled = true;- mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });- mockNodeGateway.configured = true;- mockNodeGateway.platforms = ['wechat'];- mockNodeGatewayClient.isConfigured = true;- mockNodeGatewayClient.isEnabled = true;- mockNodeGatewayClient.connect.mockResolvedValue({ status: 'connecting' });- });-- it('moves a bot provider to the node host: stale-disconnects on default, connects on node', 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');- // Provider row is enabled+polling, but routed to node β the TOCTOU- // guard must NOT protect it on the default host.- mockFindByIds.mockResolvedValue([- {- enabled: true,- id: 'wechat-provider',- platform: 'wechat',- settings: {},- },- ]);- // The connection currently lives on the default (CF) host.- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });-- await service.ensureRunning();-- expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('wechat-provider');- expect(mockGatewayClient.connect).not.toHaveBeenCalled();- expect(mockNodeGatewayClient.connect).toHaveBeenCalledWith(- expect.objectContaining({ connectionId: 'wechat-provider', platform: 'wechat' }),- { ensure: true },- );- });-- it('reconciles messenger polling links onto the node host and cleans the default host', async () => {- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: '[email protected]',- credentials: { baseUrl: 'https://ilink.example.com', botId: 'bot-1', botToken: 'tok' },- tenantId: '[email protected]',- userId: 'user-1',- },- // No token β never connectable, must be skipped.- { applicationId: '[email protected]', credentials: {}, tenantId: 'bob', userId: 'user-2' },- ]);- // A leftover per-user poller on the default host must be torn down- // (double-hosting a polling platform double-delivers messages)β¦- mockGatewayClient.getRegisteredIds.mockResolvedValue({- ids: ['messenger:wechat:[email protected]:user-user-1'],- });- // β¦while an unlinked account's connection on the owning host is stale.- mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({- ids: ['messenger:wechat:gone:user-user-9'],- });-- await service.ensureRunning();-- expect(mockGatewayClient.disconnect).toHaveBeenCalledWith(- 'messenger:wechat:[email protected]:user-user-1',- );- expect(mockNodeGatewayClient.connect).toHaveBeenCalledWith(- expect.objectContaining({- applicationId: '[email protected]',- connectionId: 'messenger:wechat:[email protected]:user-user-1',- connectionMode: 'polling',- credentials: expect.objectContaining({- botToken: 'tok',- webhookToken: 'gateway-service-token',- }),- platform: 'wechat',- userId: 'user-1',- webhookPath: '/api/agent/messenger/webhooks/wechat',- }),- { ensure: true },- );- expect(mockNodeGatewayClient.connect).toHaveBeenCalledTimes(1);- expect(mockNodeGatewayClient.disconnect).toHaveBeenCalledWith(- 'messenger:wechat:gone:user-user-9',- );- });-- it('skips live messenger connections and leaves other hosts untouched without a node gateway', async () => {- mockNodeGateway.configured = false;- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: '[email protected]',- credentials: { botToken: 'tok' },- tenantId: 'alice',- userId: 'user-1',- },- ]);- // Link already live on the default host β nothing to do.- mockGatewayClient.getStats.mockResolvedValue({- byPlatform: { wechat: 1 },- connections: [- {- connectionId: 'messenger:wechat:alice:user-user-1',- platform: 'wechat',- state: { status: 'connected' },- },- ],- total: 1,- });- mockGatewayClient.getRegisteredIds.mockResolvedValue({- ids: ['messenger:wechat:alice:user-user-1'],- });-- await service.ensureRunning();-- expect(mockGatewayClient.connect).not.toHaveBeenCalled();- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();- });-- it('routes per-user messenger registration to the node host', async () => {- mockResolveMessengerInstallation.mockResolvedValue({- applicationId: '[email protected]',- botToken: 'secret-token',- });-- // Fresh key/user β the module-level LRU cache persists across tests and- // a cached connectionId would skip the connect this test asserts on.- const connectionId = await service.ensureUserMessengerConnected({- installationKey: 'wechat:[email protected]',- platform: 'wechat',- userId: 'user-7',- });-- expect(connectionId).toBe('messenger:wechat:[email protected]:user-user-7');- expect(mockNodeGatewayClient.connect).toHaveBeenCalledWith(- expect.objectContaining({ connectionMode: 'polling', platform: 'wechat' }),- );- expect(mockGatewayClient.connect).not.toHaveBeenCalled();- });-- it('stays on the in-process runtime when the default host is unconfigured', async () => {- // Node-only deployment. Gateway mode is a whole-process switch and the- // Node gateway cannot host the webhook/websocket platforms that fall- // back to `default`, so entering it here would strand them with no- // in-process fallback. Out of scope by capability β see the note on- // `isAnyMessageGatewayEnabled`.- mockGatewayClient.isConfigured = false;- mockGatewayClient.isEnabled = false;- mockNodeGateway.platforms = ['wechat'];-- expect(service.useMessageGateway).toBe(false);- });-- it('defers a cross-host move while the destination host has no usable snapshot', 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');- mockFindByIds.mockResolvedValue([- { enabled: true, id: 'wechat-provider', platform: 'wechat', settings: {} },- ]);- // Live on the default host, routed to node β but node's admin surface is- // down, so its connect pass would defer. Disconnecting here first would- // take WeChat dark for the whole outage.- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });- mockNodeGatewayClient.getStats.mockRejectedValue(new Error('node stats unavailable'));- mockNodeGatewayClient.getRegisteredIds.mockRejectedValue(new Error('node registry down'));-- await service.ensureRunning();-- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();- });-- it('never connects a messenger link the capped migration left running on the old host', async () => {- // 60 linked users, all still polling on the default host. Cross-host- // cleanup is capped at 50 per round, so connecting all 60 on node would- // double-deliver for the 10 that were not drained.- const links = Array.from({ length: 60 }, (_, i) => ({- applicationId: '[email protected]',- credentials: { baseUrl: 'https://ilink.example.com', botId: 'bot-1', botToken: 'tok' },- tenantId: `tenant-${i}`,- userId: `user-${i}`,- }));- const strayIds = links.map((l) => `messenger:wechat:${l.tenantId}:user-${l.userId}`);- mockFindAllLinksByPlatform.mockResolvedValue(links);- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: strayIds });-- await service.ensureRunning();-- const drained = mockGatewayClient.disconnect.mock.calls.map((call) => call[0] as string);- const connected = mockNodeGatewayClient.connect.mock.calls.map(- (call) => (call[0] as { connectionId: string }).connectionId,- );-- expect(drained).toHaveLength(50);- // Every id connected on the new host was drained from the old one first,- // and the undrained remainder is left for the next round.- expect(connected.every((id: string) => drained.includes(id))).toBe(true);- expect(connected).toHaveLength(50);- });-- it('never connects a bot provider the capped stale pass left running on the old host', async () => {- // 60 wechat providers all live on the default host and all routed to- // node. Stale disconnects are capped at 50/round, so connecting all 60- // on node would leave 10 running on both gateways.- const providers = Array.from({ length: 60 }, (_, i) => ({- applicationId: `wechat-app-${i}`,- credentials: { botToken: 'token' },- id: `wechat-provider-${i}`,- settings: {},- userId: `u${i}`,- }));- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>- platform === 'wechat' ? providers : [],- );- mockResolveConnectionMode.mockReturnValue('polling');- mockFindByIds.mockImplementation(async (_db: unknown, ids: string[]) =>- ids.map((id) => ({ enabled: true, id, platform: 'wechat', settings: {} })),- );- mockGatewayClient.getRegisteredIds.mockResolvedValue({- ids: providers.map((p) => p.id),- });-- await service.ensureRunning();-- const drained = mockGatewayClient.disconnect.mock.calls.map((call) => call[0] as string);- const connected = mockNodeGatewayClient.connect.mock.calls.map(- (call) => (call[0] as { connectionId: string }).connectionId,- );-- expect(drained).toHaveLength(50);- expect(connected).toHaveLength(50);- expect(connected.every((id: string) => drained.includes(id))).toBe(true);- });-- it('completes a node-to-default rollback in one round, not the round after', async () => {- // Rollback shape: node gateway still configured, but wechat is no longer- // routed to it. `hosts` is ['default','node'], so a per-host sync would- // run the destination first (deferring everything, nothing drained yet),- // drain the source second, and never revisit the destination.- mockNodeGateway.platforms = [];- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>- platform === 'wechat'- ? [- {- applicationId: 'wechat-app',- credentials: { botToken: 'token' },- id: 'wechat-provider',- settings: {},- userId: 'u1',- },- ]- : [],- );- mockResolveConnectionMode.mockReturnValue('polling');- mockFindByIds.mockResolvedValue([- { enabled: true, id: 'wechat-provider', platform: 'wechat', settings: {} },- ]);- // Still live on node, which no longer owns it.- mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });-- await service.ensureRunning();-- expect(mockNodeGatewayClient.disconnect).toHaveBeenCalledWith('wechat-provider');- expect(mockGatewayClient.connect).toHaveBeenCalledWith(- expect.objectContaining({ connectionId: 'wechat-provider', platform: 'wechat' }),- { ensure: true },- );- });-- it('makes no cross-host change when the messenger link lookup fails', async () => {- mockFindAllLinksByPlatform.mockRejectedValue(new Error('db unavailable'));- // A stray poller on the default host would normally be drained here β- // draining it before discovering the links are unreadable would strand- // that user offline until a later round.- mockGatewayClient.getRegisteredIds.mockResolvedValue({- ids: ['messenger:wechat:[email protected]:user-user-1'],- });-- await service.ensureRunning();-- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();- });-- it('leaves an unusable link running on its current host instead of stranding the user', async () => {- // Credentials fail to decrypt, so this link cannot be rebuilt on the- // owning host. Draining it off the other host first would take the user- // offline with nothing able to bring them back.- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: '[email protected]',- credentials: {},- tenantId: '[email protected]',- userId: 'user-1',- },- ]);- mockGatewayClient.getRegisteredIds.mockResolvedValue({- ids: ['messenger:wechat:[email protected]:user-user-1'],- });-- await service.ensureRunning();-- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();- });-- it('keeps a linked account whose credentials are undecryptable out of the stale pass', async () => {- // decryptRow returns `credentials: {}` on a key-vault mismatch, which is- // indistinguishable from "never had a token". Treating that as unlinked- // would tear down every healthy poller in one round.- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: '[email protected]',- credentials: {},- tenantId: '[email protected]',- userId: 'user-1',- },- ]);- mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({- ids: ['messenger:wechat:[email protected]:user-user-1'],- });-- await service.ensureRunning();-- expect(mockNodeGatewayClient.disconnect).not.toHaveBeenCalled();- expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();- });- });-- // βββ Routing a platform to a host that cannot serve it βββ-- describe('platform capability guard', () => {- const CONNECTION_ID = 'messenger:wechat:t1:user-u1';-- beforeEach(() => {- mockGatewayClient.isEnabled = true;- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });- mockNodeGateway.configured = true;- mockNodeGatewayClient.isConfigured = true;- mockNodeGatewayClient.isEnabled = true;- mockResolveConnectionMode.mockReturnValue('polling');- mockFindEnabledByPlatform.mockResolvedValue([]);- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: 'wx-app',- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },- tenantId: 't1',- userId: 'u1',- },- ]);- });-- /** The default host is holding the WeChat poller; routing says it moves. */- const defaultHostHoldsIt = () => {- mockGatewayClient.getStats.mockResolvedValue({- byPlatform: { wechat: 1 },- connections: [- {- connectionId: CONNECTION_ID,- platform: 'wechat',- state: { status: 'connected' },- userId: 'u1',- },- ],- total: 1,- });- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [CONNECTION_ID] });- };-- // Draining into a host that rejects the platform is worse than doing- // nothing: the connect meant to replace the connection fails, so it ends- // up on neither host. A misrouted env var must be a no-op, not an outage.- it('refuses to drain a platform off its host when the destination declines it', async () => {- mockNodeGateway.platforms = ['wechat'];- mockNodeGatewayClient.getCapabilities.mockResolvedValue({- platforms: ['whatsapp-baileys'],- });- defaultHostHoldsIt();-- await service.ensureRunning();-- expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();- });-- // Same fixture, guard off β proves the case above is the guard talking and- // not a setup that never had a teardown to begin with.- it('performs the same move when the destination declares the platform', async () => {- mockNodeGateway.platforms = ['wechat'];- mockNodeGatewayClient.getCapabilities.mockResolvedValue({ platforms: ['wechat'] });- defaultHostHoldsIt();-- await service.ensureRunning();-- expect(mockGatewayClient.disconnect).toHaveBeenCalledWith(CONNECTION_ID);- });-- // The load-bearing half of the rule. The Cloudflare gateway has no- // capabilities endpoint, so a rollback β clearing the platform list to- // move connections BACK to it β targets a host that declares nothing.- // Reading that silence as a refusal would make rollback impossible.- it('does not treat a host that declares nothing as refusing anything', async () => {- mockNodeGateway.platforms = [];- mockGatewayClient.getCapabilities.mockResolvedValue(null);- // The node host is the one still holding it β this is the rollback.- mockNodeGatewayClient.getStats.mockResolvedValue({- byPlatform: { wechat: 1 },- connections: [- {- connectionId: CONNECTION_ID,- platform: 'wechat',- state: { status: 'connected' },- userId: 'u1',- },- ],- total: 1,- });- mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [CONNECTION_ID] });- mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });-- await service.ensureRunning();-- expect(mockNodeGatewayClient.disconnect).toHaveBeenCalledWith(CONNECTION_ID);- });-- it('skips the connect for a bot-channel platform the host declines', async () => {- mockNodeGateway.platforms = ['discord'];- mockNodeGatewayClient.getCapabilities.mockResolvedValue({ platforms: ['wechat'] });- mockResolveConnectionMode.mockReturnValue('websocket');- mockFindAllLinksByPlatform.mockResolvedValue([]);- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>- platform === 'discord'- ? [- {- applicationId: 'app-1',- credentials: { token: 'x' },- id: 'prov-1',- settings: {},- userId: 'u1',- },- ]- : [],- );- mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });-- await service.ensureRunning();-- expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();- });- });-- // βββ listDesiredConnectionsForHost (restart recovery, pull side) βββ-- describe('listDesiredConnectionsForHost', () => {- beforeEach(() => {- mockGatewayClient.isEnabled = true;- mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });- mockResolveConnectionMode.mockReturnValue('websocket');- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>- platform === 'discord'- ? [- {- applicationId: 'app-1',- credentials: { token: 'x' },- id: 'prov-1',- settings: { watchKeywords: [{ keyword: 'hi' }] },- userId: 'u1',- },- ]- : [],- );- });-- // The whole point of sharing one builder: whichever side establishes a- // connection, the gateway ends up holding the same config. A drifting- // second builder would show up here and nowhere else.- it('hands back exactly the payload the reconcile would have pushed', async () => {- mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });-- await service.ensureRunning();- const pushed = mockGatewayClient.connect.mock.calls[0][0];-- const { connections } = await service.listDesiredConnectionsForHost('default');-- expect(connections).toHaveLength(1);- expect(connections[0]).toEqual({ config: pushed, ensure: true });- });-- // A pull changes nothing and wakes nothing. It reads another host's- // registry to see what is still held there β two admin requests, no- // fan-out β but it must never mutate a gateway, and never probe a single- // connection's status, which is what would drag a dormant one up.- it('reads, but never mutates a gateway or probes a connection', async () => {- mockNodeGateway.configured = true;- mockNodeGateway.platforms = ['wechat'];- mockNodeGatewayClient.isConfigured = true;-- await service.listDesiredConnectionsForHost('node');-- for (const client of [mockGatewayClient, mockNodeGatewayClient]) {- expect(client.connect).not.toHaveBeenCalled();- expect(client.disconnect).not.toHaveBeenCalled();- expect(client.disconnectAll).not.toHaveBeenCalled();- expect(client.getStatus).not.toHaveBeenCalled();- }- // Its own host is never queried β the answer comes from the database.- expect(mockNodeGatewayClient.getStats).not.toHaveBeenCalled();- });-- it('returns only the requested host slice', async () => {- mockNodeGateway.configured = true;- mockNodeGateway.platforms = ['wechat'];- mockNodeGatewayClient.isConfigured = true;- mockResolveConnectionMode.mockReturnValue('polling');- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>- platform === 'wechat'- ? [- {- applicationId: 'wx-app',- credentials: { token: 'w' },- id: 'prov-wechat',- settings: {},- userId: 'u-wx',- },- ]- : [- {- applicationId: 'dc-app',- credentials: { token: 'd' },- id: `prov-${platform}`,- settings: {},- userId: 'u-dc',- },- ],- );-- const node = await service.listDesiredConnectionsForHost('node');- const def = await service.listDesiredConnectionsForHost('default');-- expect(node.connections.map((entry) => entry.config.connectionId)).toEqual(['prov-wechat']);- expect(def.connections.map((entry) => entry.config.connectionId)).not.toContain(- 'prov-wechat',- );- });-- // One unreadable row used to be able to fail the whole recovery. A row- // that can never connect is data we exclude, not a reason to leave a- // gateway empty.- it('excludes an undecryptable row without failing the call', async () => {- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>- platform === 'discord'- ? [- { applicationId: 'app-1', credentials: {}, id: 'prov-1', settings: {}, userId: 'u1' },- {- applicationId: 'app-2',- credentials: { token: 'x' },- id: 'prov-2',- settings: {},- userId: 'u2',- },- ]- : [],- );-- const result = await service.listDesiredConnectionsForHost('default');-- expect(result.complete).toBe(true);- expect(result.excluded).toBe(1);- expect(result.connections.map((entry) => entry.config.connectionId)).toEqual(['prov-2']);- });-- it('reports complete:false when a platform fails to load', async () => {- mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) => {- if (platform === 'telegram') throw new Error('key vault unavailable');- return [];- });-- const result = await service.listDesiredConnectionsForHost('default');-- expect(result.complete).toBe(false);- });-- it('includes messenger polling links and excludes ones with no usable token', async () => {- mockFindEnabledByPlatform.mockResolvedValue([]);- mockResolveConnectionMode.mockReturnValue('polling');- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: 'wx-app',- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },- tenantId: 't1',- userId: 'u1',- },- { applicationId: 'wx-app', credentials: {}, tenantId: 't2', userId: 'u2' },- ]);-- const result = await service.listDesiredConnectionsForHost('default');-- expect(result.excluded).toBe(1);- expect(result.connections).toHaveLength(1);- expect(result.connections[0].config).toMatchObject({- connectionId: 'messenger:wechat:t1:user-u1',- connectionMode: 'polling',- credentials: {- baseUrl: 'https://ilink',- botId: 'bot-1',- botToken: 'tok-1',- webhookToken: 'gateway-service-token',- },- webhookPath: '/api/agent/messenger/webhooks/wechat',- });- });-- // Routing a platform here does not mean this host can run it. Handing over- // credentials for a connection it will reject arms nothing and exposes- // them for no reason β and the reconcile already refuses to move such a- // platform, so leaving the gap here would put the two out of step.- it('withholds credentials for a platform this host says it cannot serve', async () => {- mockNodeGateway.configured = true;- mockNodeGateway.platforms = ['wechat'];- mockNodeGatewayClient.isConfigured = true;- mockNodeGatewayClient.getCapabilities.mockResolvedValue({- platforms: ['whatsapp-baileys'],- });- mockResolveConnectionMode.mockReturnValue('polling');- mockFindEnabledByPlatform.mockResolvedValue([]);- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: 'wx-app',- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },- tenantId: 't1',- userId: 'u1',- },- ]);- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });-- const result = await service.listDesiredConnectionsForHost('node');-- expect(result.connections).toEqual([]);- });-- // Today's production shape: the node URL is configured but no platform is- // routed there yet. Deploying the node gateway must not drag the other- // host's fleet over β it should be handed nothing at all.- it('hands a host nothing while no platform is routed to it', async () => {- mockNodeGateway.configured = true;- mockNodeGateway.platforms = [];- mockNodeGatewayClient.isConfigured = true;- mockResolveConnectionMode.mockReturnValue('polling');- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: 'wx-app',- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },- tenantId: 't1',- userId: 'u1',- },- ]);-- const result = await service.listDesiredConnectionsForHost('node');-- expect(result.connections).toEqual([]);- expect(result.deferred).toBe(0);- });-- // Routing a platform here does not make its connections safe to build: the- // host that owned them a moment ago is still polling. Handing one over- // before that host is drained double-delivers every message.- it('withholds a connection the previous host has not released yet', async () => {- mockNodeGateway.configured = true;- mockNodeGateway.platforms = ['wechat'];- mockNodeGatewayClient.isConfigured = true;- mockResolveConnectionMode.mockReturnValue('polling');- mockFindEnabledByPlatform.mockResolvedValue([]);- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: 'wx-app',- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },- tenantId: 't1',- userId: 'u1',- },- ]);- // The default host still holds it β mid-migration.- mockGatewayClient.getRegisteredIds.mockResolvedValue({- ids: ['messenger:wechat:t1:user-u1'],- });-- const result = await service.listDesiredConnectionsForHost('node');-- expect(result.connections).toEqual([]);- expect(result.deferred).toBe(1);- // Partial answer, so the caller keeps asking rather than settling.- expect(result.complete).toBe(false);- });-- // A stats-only snapshot omits dormant registrations, so an id missing from- // it proves nothing about whether the other host released it. Marking the- // answer incomplete is not enough on its own: the caller applies what it- // receives and only then asks again, so the flag would land after the- // duplicate it was meant to prevent. The connection has to be withheld.- it('withholds a connection the other host cannot be proven to have released', async () => {- mockNodeGateway.configured = true;- mockNodeGateway.platforms = ['wechat'];- mockNodeGatewayClient.isConfigured = true;- mockResolveConnectionMode.mockReturnValue('polling');- mockFindEnabledByPlatform.mockResolvedValue([]);- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: 'wx-app',- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },- tenantId: 't1',- userId: 'u1',- },- ]);- // Stats answered, registered-ids did not: a live host we can only half see.- mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });- mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registry unavailable'));-- const result = await service.listDesiredConnectionsForHost('node');-- expect(result.connections).toEqual([]);- expect(result.deferred).toBe(1);- expect(result.complete).toBe(false);- });-- it('hands the connection over once the previous host has released it', async () => {- mockNodeGateway.configured = true;- mockNodeGateway.platforms = ['wechat'];- mockNodeGatewayClient.isConfigured = true;- mockResolveConnectionMode.mockReturnValue('polling');- mockFindEnabledByPlatform.mockResolvedValue([]);- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: 'wx-app',- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },- tenantId: 't1',- userId: 'u1',- },- ]);- mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });-- const result = await service.listDesiredConnectionsForHost('node');-- expect(result.connections).toHaveLength(1);- expect(result.deferred).toBe(0);- expect(result.complete).toBe(true);- });-- // Same rule from the other direction: a host we could not reach shows- // nothing, which is no more proof of release than a half-seen one. Restart- // recovery is an optimisation over the reconcile, so when it cannot be done- // safely the right move is not to do it.- it('withholds when the other host cannot be read at all', async () => {- mockNodeGateway.configured = true;- mockNodeGateway.platforms = ['wechat'];- mockNodeGatewayClient.isConfigured = true;- mockResolveConnectionMode.mockReturnValue('polling');- mockFindEnabledByPlatform.mockResolvedValue([]);- mockFindAllLinksByPlatform.mockResolvedValue([- {- applicationId: 'wx-app',- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },- tenantId: 't1',- userId: 'u1',- },- ]);- mockGatewayClient.getStats.mockRejectedValue(new Error('admin down'));- mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('admin down'));-- const result = await service.listDesiredConnectionsForHost('node');-- expect(result.connections).toEqual([]);- expect(result.deferred).toBe(1);- });-- it('reports complete:false when messenger links fail to load', async () => {- mockFindEnabledByPlatform.mockResolvedValue([]);- mockFindAllLinksByPlatform.mockRejectedValue(new Error('link listing failed'));-- const result = await service.listDesiredConnectionsForHost('default');-- expect(result.complete).toBe(false);- });- });-});diff --git a/apps/server/src/services/gateway/gatewayMapping.ts b/apps/server/src/services/gateway/gatewayMapping.tsnew file mode 100644index 00000000000..72179e0fb3d--- /dev/null+++ b/apps/server/src/services/gateway/gatewayMapping.ts@@ -0,0 +1,116 @@+/**+ * Translation between bot-provider / messenger-link rows and the message+ * gateway: connect payloads out, connection status in.+ */+import type { DecryptedMessengerAccountLink } from '@/database/models/messengerAccountLink';+import { gatewayEnv } from '@/envs/gateway';+import type { BotRuntimeStatus } from '@/types/botRuntimeStatus';++import { extractWatchKeywordEntries } from '../bot/platforms';+import type {+ MessageGatewayCapabilities,+ MessageGatewayConnectionConfig,+ MessageGatewayConnectionStatus,+} from './MessageGatewayClient';+import { BOT_RUNTIME_STATUSES } from './runtimeStatus';+import type { DesiredGatewayConnection } from './sync/types';++export function mapGatewayStatusToRuntimeStatus(+ status: MessageGatewayConnectionStatus['state']['status'],+): BotRuntimeStatus {+ switch (status) {+ case 'connected': {+ return BOT_RUNTIME_STATUSES.connected;+ }+ case 'connecting': {+ return BOT_RUNTIME_STATUSES.starting;+ }+ case 'disconnected': {+ return BOT_RUNTIME_STATUSES.disconnected;+ }+ case 'dormant': {+ return BOT_RUNTIME_STATUSES.dormant;+ }+ case 'error': {+ return BOT_RUNTIME_STATUSES.failed;+ }+ }+}++/**+ * Derive edge-filtering capabilities for a bot-channel connection from its+ * settings. Monitoring is enabled purely by "has watch keywords configured":+ * feature-access gating stays server-side (BotMessageRouter), so access+ * changes never require a gateway reconnect and operators with existing+ * rules are never cut off by a stale edge config.+ */+export const resolveBotGatewayCapabilities = (+ settings?: Record<string, unknown> | null,+): MessageGatewayCapabilities => ({+ messageMonitoring: { enabled: extractWatchKeywordEntries(settings ?? undefined).length > 0 },+});++/**+ * The connect payload for one bot-channel provider.+ *+ * Extracted because two callers build it now: the periodic reconcile, which+ * pushes it to the gateway, and the gateway's own boot-time pull, which+ * receives it and connects itself. A second builder would drift, and the+ * connection the gateway ends up holding would then depend on which side+ * established it.+ *+ * Payload only, deliberately no side effects. The push path also writes a+ * runtime status from the connect result, but that belongs to whoever+ * actually connected: on the pull path the gateway does, so its state+ * callback is what reports the real status back. Guessing a status here would+ * record a connection as live that nothing has established yet.+ */+export const buildBotProviderConnectConfig = ({+ connectionMode,+ platform,+ provider,+}: DesiredGatewayConnection): MessageGatewayConnectionConfig => ({+ applicationId: provider.applicationId,+ capabilities: resolveBotGatewayCapabilities(provider.settings),+ connectionId: provider.id,+ connectionMode,+ credentials: provider.credentials,+ platform,+ userId: provider.userId,+ webhookPath: `/api/agent/webhooks/${platform}/${provider.applicationId}`,+});++/** The connect payload for one messenger polling link. Same rationale as above. */+export const buildMessengerPollingConnectConfig = ({+ connectionId,+ link,+ platform,+}: {+ connectionId: string;+ link: DecryptedMessengerAccountLink;+ platform: string;+}): MessageGatewayConnectionConfig => {+ const credentials = link.credentials as {+ baseUrl?: string;+ botId?: string;+ botToken?: string;+ };++ return {+ applicationId: link.applicationId!,+ // Messenger-owned connections never consume passive channel monitoring β+ // the shared bot only reacts to DMs and explicit mentions.+ capabilities: { messageMonitoring: { enabled: false } },+ connectionId,+ connectionMode: 'polling',+ credentials: {+ baseUrl: credentials.baseUrl,+ botId: credentials.botId,+ botToken: credentials.botToken,+ webhookToken: gatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN,+ },+ platform,+ userId: link.userId,+ webhookPath: `/api/agent/messenger/webhooks/${platform}`,+ };+};diff --git a/apps/server/src/services/gateway/index.clientLifecycle.test.ts b/apps/server/src/services/gateway/index.clientLifecycle.test.tsnew file mode 100644index 00000000000..f6adb7e8b25--- /dev/null+++ b/apps/server/src/services/gateway/index.clientLifecycle.test.ts@@ -0,0 +1,199 @@+// @vitest-environment node+/**+ * Characterization of the per-provider client lifecycle (`startClient`,+ * `stopClient`, `stop`) in gateway mode and in the in-process (non-Vercel)+ * legacy mode.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GatewayService } from '.';+import {+ mockAssertBotFeatureAccess,+ mockFindByPlatformAndAppId,+ mockFindEnabledByPlatformAndAppId,+ mockGatewayClient,+ mockGatewayManager,+ mockResolveConnectionMode,+ mockUpdateBotRuntimeStatus,+ resetGatewayServiceMocks,+} from './testUtils';++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => m.envsGatewayModule()));+vi.mock('./MessageGatewayClient', () =>+ import('./testUtils').then((m) => m.messageGatewayClientModule()),+);+vi.mock('@/database/models/messengerAccountLink', () =>+ import('./testUtils').then((m) => m.messengerAccountLinkModule()),+);+vi.mock('./GatewayManager', () => import('./testUtils').then((m) => m.gatewayManagerModule()));+vi.mock('@/database/core/db-adaptor', () => import('./testUtils').then((m) => m.dbAdaptorModule()));+vi.mock('@/database/models/agentBotProvider', () =>+ import('./testUtils').then((m) => m.agentBotProviderModule()),+);+vi.mock('@/server/modules/KeyVaultsEncrypt', () =>+ import('./testUtils').then((m) => m.keyVaultsEncryptModule()),+);+vi.mock('./runtimeStatus', () => import('./testUtils').then((m) => m.runtimeStatusModule()));+vi.mock('@/business/server/bot/featureAccess', () =>+ import('./testUtils').then((m) => m.featureAccessModule()),+);+vi.mock('@/server/services/messenger/installations', () =>+ import('./testUtils').then((m) => m.messengerInstallationsModule()),+);+vi.mock('@/server/services/messenger/platforms', () =>+ import('./testUtils').then((m) => m.messengerPlatformsModule()),+);+vi.mock('../bot/platforms', () => import('./testUtils').then((m) => m.botPlatformsModule()));++const provider = {+ applicationId: 'app-1',+ credentials: { botToken: 'bot-token' },+ id: 'prov-1',+ settings: { watchKeywords: [{ keyword: 'deploy' }] },+ userId: 'owner-1',+ workspaceId: null,+};++describe('GatewayService client lifecycle', () => {+ let service: GatewayService;++ beforeEach(() => {+ resetGatewayServiceMocks();+ service = new GatewayService();+ });++ describe('via the message gateway', () => {+ beforeEach(() => {+ mockGatewayClient.isEnabled = true;+ });++ it('connects a persistent provider with its capabilities and marks it connected', async () => {+ mockFindEnabledByPlatformAndAppId.mockResolvedValue(provider);+ mockResolveConnectionMode.mockReturnValue('websocket');++ await expect(service.startClient('discord', 'app-1', 'user-1')).resolves.toBe('started');++ expect(mockAssertBotFeatureAccess).toHaveBeenCalledWith({+ action: 'manage',+ applicationId: 'app-1',+ platform: 'discord',+ userId: 'owner-1',+ workspaceId: undefined,+ });+ expect(mockGatewayClient.connect).toHaveBeenCalledWith({+ applicationId: 'app-1',+ capabilities: { messageMonitoring: { enabled: true } },+ connectionId: 'prov-1',+ connectionMode: 'websocket',+ credentials: { botToken: 'bot-token' },+ platform: 'discord',+ userId: 'user-1',+ webhookPath: '/api/agent/webhooks/discord/app-1',+ });+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({+ applicationId: 'app-1',+ platform: 'discord',+ status: 'connected',+ });+ expect(mockGatewayManager.startClient).not.toHaveBeenCalled();+ });++ it('runs a webhook-mode provider locally instead of on the gateway', async () => {+ mockFindEnabledByPlatformAndAppId.mockResolvedValue(provider);+ mockResolveConnectionMode.mockReturnValue('webhook');++ await expect(service.startClient('telegram', 'app-1', 'user-1')).resolves.toBe('started');++ expect(mockGatewayManager.startClient).toHaveBeenCalledWith('telegram', 'app-1');+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalled();+ });++ it('refuses to start a provider that is not enabled', async () => {+ await expect(service.startClient('discord', 'app-1', 'user-1')).rejects.toThrow(+ 'No enabled provider found for discord:app-1',+ );+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('stops the local client, disconnects the provider and marks it disconnected', async () => {+ mockGatewayManager.isRunning = true;+ mockFindByPlatformAndAppId.mockResolvedValue({ id: 'prov-1' });++ await service.stopClient('discord', 'app-1');++ expect(mockGatewayManager.stopClient).toHaveBeenCalledWith('discord', 'app-1');+ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('prov-1');+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({+ applicationId: 'app-1',+ platform: 'discord',+ status: 'disconnected',+ });+ });++ it('still marks the provider disconnected when the gateway disconnect fails', async () => {+ mockFindByPlatformAndAppId.mockResolvedValue({ id: 'prov-1' });+ mockGatewayClient.disconnect.mockRejectedValue(new Error('gateway down'));++ await service.stopClient('discord', 'app-1');++ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({+ applicationId: 'app-1',+ platform: 'discord',+ status: 'disconnected',+ });+ });++ it('skips the disconnect when no provider row exists', async () => {+ await service.stopClient('discord', 'app-1');++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledTimes(1);+ });+ });++ describe('in-process (gateway disabled, not on Vercel)', () => {+ it('starts the manager on demand, then the client', async () => {+ mockGatewayManager.start.mockImplementation(async () => {+ mockGatewayManager.isRunning = true;+ });++ await expect(service.startClient('discord', 'app-1', 'user-1')).resolves.toBe('started');++ expect(mockGatewayManager.start).toHaveBeenCalledTimes(1);+ expect(mockGatewayManager.startClient).toHaveBeenCalledWith('discord', 'app-1');+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('reuses a running manager', async () => {+ mockGatewayManager.isRunning = true;++ await service.startClient('discord', 'app-1', 'user-1');++ expect(mockGatewayManager.start).not.toHaveBeenCalled();+ expect(mockGatewayManager.startClient).toHaveBeenCalledWith('discord', 'app-1');+ });++ it('stops the client on a running manager and marks it disconnected', async () => {+ mockGatewayManager.isRunning = true;++ await service.stopClient('discord', 'app-1', 'user-1');++ expect(mockGatewayManager.stopClient).toHaveBeenCalledWith('discord', 'app-1');+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({+ applicationId: 'app-1',+ platform: 'discord',+ status: 'disconnected',+ });+ });++ it('stop() stops a running manager and is a no-op otherwise', async () => {+ await service.stop();+ expect(mockGatewayManager.stop).not.toHaveBeenCalled();++ mockGatewayManager.isRunning = true;+ await service.stop();+ expect(mockGatewayManager.stop).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/apps/server/src/services/gateway/index.desiredForHost.test.ts b/apps/server/src/services/gateway/index.desiredForHost.test.tsnew file mode 100644index 00000000000..a63bf5df06e--- /dev/null+++ b/apps/server/src/services/gateway/index.desiredForHost.test.ts@@ -0,0 +1,382 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GatewayService } from '.';+import {+ mockFindAllLinksByPlatform,+ mockFindEnabledByPlatform,+ mockGatewayClient,+ mockNodeGateway,+ mockNodeGatewayClient,+ mockResolveConnectionMode,+ resetGatewayServiceMocks,+} from './testUtils';++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => m.envsGatewayModule()));+vi.mock('./MessageGatewayClient', () =>+ import('./testUtils').then((m) => m.messageGatewayClientModule()),+);+vi.mock('@/database/models/messengerAccountLink', () =>+ import('./testUtils').then((m) => m.messengerAccountLinkModule()),+);+vi.mock('./GatewayManager', () => import('./testUtils').then((m) => m.gatewayManagerModule()));+vi.mock('@/database/core/db-adaptor', () => import('./testUtils').then((m) => m.dbAdaptorModule()));+vi.mock('@/database/models/agentBotProvider', () =>+ import('./testUtils').then((m) => m.agentBotProviderModule()),+);+vi.mock('@/server/modules/KeyVaultsEncrypt', () =>+ import('./testUtils').then((m) => m.keyVaultsEncryptModule()),+);+vi.mock('./runtimeStatus', () => import('./testUtils').then((m) => m.runtimeStatusModule()));+vi.mock('@/business/server/bot/featureAccess', () =>+ import('./testUtils').then((m) => m.featureAccessModule()),+);+vi.mock('@/server/services/messenger/installations', () =>+ import('./testUtils').then((m) => m.messengerInstallationsModule()),+);+vi.mock('@/server/services/messenger/platforms', () =>+ import('./testUtils').then((m) => m.messengerPlatformsModule()),+);+vi.mock('../bot/platforms', () => import('./testUtils').then((m) => m.botPlatformsModule()));++describe('GatewayService', () => {+ let service: GatewayService;++ beforeEach(() => {+ resetGatewayServiceMocks();+ service = new GatewayService();+ });++ // βββ listDesiredConnectionsForHost (restart recovery, pull side) βββ++ describe('listDesiredConnectionsForHost', () => {+ beforeEach(() => {+ mockGatewayClient.isEnabled = true;+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord'+ ? [+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: { watchKeywords: [{ keyword: 'hi' }] },+ userId: 'u1',+ },+ ]+ : [],+ );+ });++ // The whole point of sharing one builder: whichever side establishes a+ // connection, the gateway ends up holding the same config. A drifting+ // second builder would show up here and nowhere else.+ it('hands back exactly the payload the reconcile would have pushed', async () => {+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });++ await service.ensureRunning();+ const pushed = mockGatewayClient.connect.mock.calls[0][0];++ const { connections } = await service.listDesiredConnectionsForHost('default');++ expect(connections).toHaveLength(1);+ expect(connections[0]).toEqual({ config: pushed, ensure: true });+ });++ // A pull changes nothing and wakes nothing. It reads another host's+ // registry to see what is still held there β two admin requests, no+ // fan-out β but it must never mutate a gateway, and never probe a single+ // connection's status, which is what would drag a dormant one up.+ it('reads, but never mutates a gateway or probes a connection', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;++ await service.listDesiredConnectionsForHost('node');++ for (const client of [mockGatewayClient, mockNodeGatewayClient]) {+ expect(client.connect).not.toHaveBeenCalled();+ expect(client.disconnect).not.toHaveBeenCalled();+ expect(client.disconnectAll).not.toHaveBeenCalled();+ expect(client.getStatus).not.toHaveBeenCalled();+ }+ // Its own host is never queried β the answer comes from the database.+ expect(mockNodeGatewayClient.getStats).not.toHaveBeenCalled();+ });++ it('returns only the requested host slice', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'wechat'+ ? [+ {+ applicationId: 'wx-app',+ credentials: { token: 'w' },+ id: 'prov-wechat',+ settings: {},+ userId: 'u-wx',+ },+ ]+ : [+ {+ applicationId: 'dc-app',+ credentials: { token: 'd' },+ id: `prov-${platform}`,+ settings: {},+ userId: 'u-dc',+ },+ ],+ );++ const node = await service.listDesiredConnectionsForHost('node');+ const def = await service.listDesiredConnectionsForHost('default');++ expect(node.connections.map((entry) => entry.config.connectionId)).toEqual(['prov-wechat']);+ expect(def.connections.map((entry) => entry.config.connectionId)).not.toContain(+ 'prov-wechat',+ );+ });++ // One unreadable row used to be able to fail the whole recovery. A row+ // that can never connect is data we exclude, not a reason to leave a+ // gateway empty.+ it('excludes an undecryptable row without failing the call', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord'+ ? [+ { applicationId: 'app-1', credentials: {}, id: 'prov-1', settings: {}, userId: 'u1' },+ {+ applicationId: 'app-2',+ credentials: { token: 'x' },+ id: 'prov-2',+ settings: {},+ userId: 'u2',+ },+ ]+ : [],+ );++ const result = await service.listDesiredConnectionsForHost('default');++ expect(result.complete).toBe(true);+ expect(result.excluded).toBe(1);+ expect(result.connections.map((entry) => entry.config.connectionId)).toEqual(['prov-2']);+ });++ it('reports complete:false when a platform fails to load', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) => {+ if (platform === 'telegram') throw new Error('key vault unavailable');+ return [];+ });++ const result = await service.listDesiredConnectionsForHost('default');++ expect(result.complete).toBe(false);+ });++ it('includes messenger polling links and excludes ones with no usable token', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ { applicationId: 'wx-app', credentials: {}, tenantId: 't2', userId: 'u2' },+ ]);++ const result = await service.listDesiredConnectionsForHost('default');++ expect(result.excluded).toBe(1);+ expect(result.connections).toHaveLength(1);+ expect(result.connections[0].config).toMatchObject({+ connectionId: 'messenger:wechat:t1:user-u1',+ connectionMode: 'polling',+ credentials: {+ baseUrl: 'https://ilink',+ botId: 'bot-1',+ botToken: 'tok-1',+ webhookToken: 'gateway-service-token',+ },+ webhookPath: '/api/agent/messenger/webhooks/wechat',+ });+ });++ // Routing a platform here does not mean this host can run it. Handing over+ // credentials for a connection it will reject arms nothing and exposes+ // them for no reason β and the reconcile already refuses to move such a+ // platform, so leaving the gap here would put the two out of step.+ it('withholds credentials for a platform this host says it cannot serve', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockNodeGatewayClient.getCapabilities.mockResolvedValue({+ platforms: ['whatsapp-baileys'],+ });+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toEqual([]);+ });++ // Today's production shape: the node URL is configured but no platform is+ // routed there yet. Deploying the node gateway must not drag the other+ // host's fleet over β it should be handed nothing at all.+ it('hands a host nothing while no platform is routed to it', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = [];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toEqual([]);+ expect(result.deferred).toBe(0);+ });++ // Routing a platform here does not make its connections safe to build: the+ // host that owned them a moment ago is still polling. Handing one over+ // before that host is drained double-delivers every message.+ it('withholds a connection the previous host has not released yet', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ // The default host still holds it β mid-migration.+ mockGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: ['messenger:wechat:t1:user-u1'],+ });++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toEqual([]);+ expect(result.deferred).toBe(1);+ // Partial answer, so the caller keeps asking rather than settling.+ expect(result.complete).toBe(false);+ });++ // A stats-only snapshot omits dormant registrations, so an id missing from+ // it proves nothing about whether the other host released it. Marking the+ // answer incomplete is not enough on its own: the caller applies what it+ // receives and only then asks again, so the flag would land after the+ // duplicate it was meant to prevent. The connection has to be withheld.+ it('withholds a connection the other host cannot be proven to have released', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ // Stats answered, registered-ids did not: a live host we can only half see.+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registry unavailable'));++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toEqual([]);+ expect(result.deferred).toBe(1);+ expect(result.complete).toBe(false);+ });++ it('hands the connection over once the previous host has released it', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toHaveLength(1);+ expect(result.deferred).toBe(0);+ expect(result.complete).toBe(true);+ });++ // Same rule from the other direction: a host we could not reach shows+ // nothing, which is no more proof of release than a half-seen one. Restart+ // recovery is an optimisation over the reconcile, so when it cannot be done+ // safely the right move is not to do it.+ it('withholds when the other host cannot be read at all', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ mockGatewayClient.getStats.mockRejectedValue(new Error('admin down'));+ mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('admin down'));++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toEqual([]);+ expect(result.deferred).toBe(1);+ });++ it('reports complete:false when messenger links fail to load', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockRejectedValue(new Error('link listing failed'));++ const result = await service.listDesiredConnectionsForHost('default');++ expect(result.complete).toBe(false);+ });+ });+});diff --git a/apps/server/src/services/gateway/index.dualHost.test.ts b/apps/server/src/services/gateway/index.dualHost.test.tsnew file mode 100644index 00000000000..bee9048c6f7--- /dev/null+++ b/apps/server/src/services/gateway/index.dualHost.test.ts@@ -0,0 +1,528 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GatewayService } from '.';+import {+ mockFindAllLinksByPlatform,+ mockFindByIds,+ mockFindEnabledByPlatform,+ mockGatewayClient,+ mockGatewayEnv,+ mockNodeGateway,+ mockNodeGatewayClient,+ mockResolveConnectionMode,+ mockResolveMessengerInstallation,+ resetGatewayServiceMocks,+} from './testUtils';++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => m.envsGatewayModule()));+vi.mock('./MessageGatewayClient', () =>+ import('./testUtils').then((m) => m.messageGatewayClientModule()),+);+vi.mock('@/database/models/messengerAccountLink', () =>+ import('./testUtils').then((m) => m.messengerAccountLinkModule()),+);+vi.mock('./GatewayManager', () => import('./testUtils').then((m) => m.gatewayManagerModule()));+vi.mock('@/database/core/db-adaptor', () => import('./testUtils').then((m) => m.dbAdaptorModule()));+vi.mock('@/database/models/agentBotProvider', () =>+ import('./testUtils').then((m) => m.agentBotProviderModule()),+);+vi.mock('@/server/modules/KeyVaultsEncrypt', () =>+ import('./testUtils').then((m) => m.keyVaultsEncryptModule()),+);+vi.mock('./runtimeStatus', () => import('./testUtils').then((m) => m.runtimeStatusModule()));+vi.mock('@/business/server/bot/featureAccess', () =>+ import('./testUtils').then((m) => m.featureAccessModule()),+);+vi.mock('@/server/services/messenger/installations', () =>+ import('./testUtils').then((m) => m.messengerInstallationsModule()),+);+vi.mock('@/server/services/messenger/platforms', () =>+ import('./testUtils').then((m) => m.messengerPlatformsModule()),+);+vi.mock('../bot/platforms', () => import('./testUtils').then((m) => m.botPlatformsModule()));++describe('GatewayService', () => {+ let service: GatewayService;++ beforeEach(() => {+ resetGatewayServiceMocks();+ service = new GatewayService();+ });++ describe('dual-host routing (node gateway configured)', () => {+ beforeEach(() => {+ mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = '1';+ mockGatewayClient.isConfigured = true;+ mockGatewayClient.isEnabled = true;+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockNodeGatewayClient.isEnabled = true;+ mockNodeGatewayClient.connect.mockResolvedValue({ status: 'connecting' });+ });++ it('moves a bot provider to the node host: stale-disconnects on default, connects on node', 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');+ // Provider row is enabled+polling, but routed to node β the TOCTOU+ // guard must NOT protect it on the default host.+ mockFindByIds.mockResolvedValue([+ {+ enabled: true,+ id: 'wechat-provider',+ platform: 'wechat',+ settings: {},+ },+ ]);+ // The connection currently lives on the default (CF) host.+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('wechat-provider');+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockNodeGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'wechat-provider', platform: 'wechat' }),+ { ensure: true },+ );+ });++ it('reconciles messenger polling links onto the node host and cleans the default host', async () => {+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: '[email protected]',+ credentials: { baseUrl: 'https://ilink.example.com', botId: 'bot-1', botToken: 'tok' },+ tenantId: '[email protected]',+ userId: 'user-1',+ },+ // No token β never connectable, must be skipped.+ { applicationId: '[email protected]', credentials: {}, tenantId: 'bob', userId: 'user-2' },+ ]);+ // A leftover per-user poller on the default host must be torn down+ // (double-hosting a polling platform double-delivers messages)β¦+ mockGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: ['messenger:wechat:[email protected]:user-user-1'],+ });+ // β¦while an unlinked account's connection on the owning host is stale.+ mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: ['messenger:wechat:gone:user-user-9'],+ });++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith(+ 'messenger:wechat:[email protected]:user-user-1',+ );+ expect(mockNodeGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({+ applicationId: '[email protected]',+ connectionId: 'messenger:wechat:[email protected]:user-user-1',+ connectionMode: 'polling',+ credentials: expect.objectContaining({+ botToken: 'tok',+ webhookToken: 'gateway-service-token',+ }),+ platform: 'wechat',+ userId: 'user-1',+ webhookPath: '/api/agent/messenger/webhooks/wechat',+ }),+ { ensure: true },+ );+ expect(mockNodeGatewayClient.connect).toHaveBeenCalledTimes(1);+ expect(mockNodeGatewayClient.disconnect).toHaveBeenCalledWith(+ 'messenger:wechat:gone:user-user-9',+ );+ });++ it('skips live messenger connections and leaves other hosts untouched without a node gateway', async () => {+ mockNodeGateway.configured = false;+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: '[email protected]',+ credentials: { botToken: 'tok' },+ tenantId: 'alice',+ userId: 'user-1',+ },+ ]);+ // Link already live on the default host β nothing to do.+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: { wechat: 1 },+ connections: [+ {+ connectionId: 'messenger:wechat:alice:user-user-1',+ platform: 'wechat',+ state: { status: 'connected' },+ },+ ],+ total: 1,+ });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: ['messenger:wechat:alice:user-user-1'],+ });++ await service.ensureRunning();++ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('routes per-user messenger registration to the node host', async () => {+ mockResolveMessengerInstallation.mockResolvedValue({+ applicationId: '[email protected]',+ botToken: 'secret-token',+ });++ // Fresh key/user β the module-level LRU cache persists across tests and+ // a cached connectionId would skip the connect this test asserts on.+ const connectionId = await service.ensureUserMessengerConnected({+ installationKey: 'wechat:[email protected]',+ platform: 'wechat',+ userId: 'user-7',+ });++ expect(connectionId).toBe('messenger:wechat:[email protected]:user-user-7');+ expect(mockNodeGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({ connectionMode: 'polling', platform: 'wechat' }),+ );+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('stays on the in-process runtime when the default host is unconfigured', async () => {+ // Node-only deployment. Gateway mode is a whole-process switch and the+ // Node gateway cannot host the webhook/websocket platforms that fall+ // back to `default`, so entering it here would strand them with no+ // in-process fallback. Out of scope by capability β see the note on+ // `isAnyMessageGatewayEnabled`.+ mockGatewayClient.isConfigured = false;+ mockGatewayClient.isEnabled = false;+ mockNodeGateway.platforms = ['wechat'];++ expect(service.useMessageGateway).toBe(false);+ });++ it('defers a cross-host move while the destination host has no usable snapshot', 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');+ mockFindByIds.mockResolvedValue([+ { enabled: true, id: 'wechat-provider', platform: 'wechat', settings: {} },+ ]);+ // Live on the default host, routed to node β but node's admin surface is+ // down, so its connect pass would defer. Disconnecting here first would+ // take WeChat dark for the whole outage.+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });+ mockNodeGatewayClient.getStats.mockRejectedValue(new Error('node stats unavailable'));+ mockNodeGatewayClient.getRegisteredIds.mockRejectedValue(new Error('node registry down'));++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('never connects a messenger link the capped migration left running on the old host', async () => {+ // 60 linked users, all still polling on the default host. Cross-host+ // cleanup is capped at 50 per round, so connecting all 60 on node would+ // double-deliver for the 10 that were not drained.+ const links = Array.from({ length: 60 }, (_, i) => ({+ applicationId: '[email protected]',+ credentials: { baseUrl: 'https://ilink.example.com', botId: 'bot-1', botToken: 'tok' },+ tenantId: `tenant-${i}`,+ userId: `user-${i}`,+ }));+ const strayIds = links.map((l) => `messenger:wechat:${l.tenantId}:user-${l.userId}`);+ mockFindAllLinksByPlatform.mockResolvedValue(links);+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: strayIds });++ await service.ensureRunning();++ const drained = mockGatewayClient.disconnect.mock.calls.map((call) => call[0] as string);+ const connected = mockNodeGatewayClient.connect.mock.calls.map(+ (call) => (call[0] as { connectionId: string }).connectionId,+ );++ expect(drained).toHaveLength(50);+ // Every id connected on the new host was drained from the old one first,+ // and the undrained remainder is left for the next round.+ expect(connected.every((id: string) => drained.includes(id))).toBe(true);+ expect(connected).toHaveLength(50);+ });++ it('never connects a bot provider the capped stale pass left running on the old host', async () => {+ // 60 wechat providers all live on the default host and all routed to+ // node. Stale disconnects are capped at 50/round, so connecting all 60+ // on node would leave 10 running on both gateways.+ const providers = Array.from({ length: 60 }, (_, i) => ({+ applicationId: `wechat-app-${i}`,+ credentials: { botToken: 'token' },+ id: `wechat-provider-${i}`,+ settings: {},+ userId: `u${i}`,+ }));+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'wechat' ? providers : [],+ );+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindByIds.mockImplementation(async (_db: unknown, ids: string[]) =>+ ids.map((id) => ({ enabled: true, id, platform: 'wechat', settings: {} })),+ );+ mockGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: providers.map((p) => p.id),+ });++ await service.ensureRunning();++ const drained = mockGatewayClient.disconnect.mock.calls.map((call) => call[0] as string);+ const connected = mockNodeGatewayClient.connect.mock.calls.map(+ (call) => (call[0] as { connectionId: string }).connectionId,+ );++ expect(drained).toHaveLength(50);+ expect(connected).toHaveLength(50);+ expect(connected.every((id: string) => drained.includes(id))).toBe(true);+ });++ it('completes a node-to-default rollback in one round, not the round after', async () => {+ // Rollback shape: node gateway still configured, but wechat is no longer+ // routed to it. `hosts` is ['default','node'], so a per-host sync would+ // run the destination first (deferring everything, nothing drained yet),+ // drain the source second, and never revisit the destination.+ mockNodeGateway.platforms = [];+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'wechat'+ ? [+ {+ applicationId: 'wechat-app',+ credentials: { botToken: 'token' },+ id: 'wechat-provider',+ settings: {},+ userId: 'u1',+ },+ ]+ : [],+ );+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindByIds.mockResolvedValue([+ { enabled: true, id: 'wechat-provider', platform: 'wechat', settings: {} },+ ]);+ // Still live on node, which no longer owns it.+ mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });++ await service.ensureRunning();++ expect(mockNodeGatewayClient.disconnect).toHaveBeenCalledWith('wechat-provider');+ expect(mockGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'wechat-provider', platform: 'wechat' }),+ { ensure: true },+ );+ });++ it('makes no cross-host change when the messenger link lookup fails', async () => {+ mockFindAllLinksByPlatform.mockRejectedValue(new Error('db unavailable'));+ // A stray poller on the default host would normally be drained here β+ // draining it before discovering the links are unreadable would strand+ // that user offline until a later round.+ mockGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: ['messenger:wechat:[email protected]:user-user-1'],+ });++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('leaves an unusable link running on its current host instead of stranding the user', async () => {+ // Credentials fail to decrypt, so this link cannot be rebuilt on the+ // owning host. Draining it off the other host first would take the user+ // offline with nothing able to bring them back.+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: '[email protected]',+ credentials: {},+ tenantId: '[email protected]',+ userId: 'user-1',+ },+ ]);+ mockGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: ['messenger:wechat:[email protected]:user-user-1'],+ });++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('keeps a linked account whose credentials are undecryptable out of the stale pass', async () => {+ // decryptRow returns `credentials: {}` on a key-vault mismatch, which is+ // indistinguishable from "never had a token". Treating that as unlinked+ // would tear down every healthy poller in one round.+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: '[email protected]',+ credentials: {},+ tenantId: '[email protected]',+ userId: 'user-1',+ },+ ]);+ mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: ['messenger:wechat:[email protected]:user-user-1'],+ });++ await service.ensureRunning();++ expect(mockNodeGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();+ });+ });++ // βββ Routing a platform to a host that cannot serve it βββ++ describe('platform capability guard', () => {+ const CONNECTION_ID = 'messenger:wechat:t1:user-u1';++ beforeEach(() => {+ mockGatewayClient.isEnabled = true;+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });+ mockNodeGateway.configured = true;+ mockNodeGatewayClient.isConfigured = true;+ mockNodeGatewayClient.isEnabled = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ });++ /** The default host is holding the WeChat poller; routing says it moves. */+ const defaultHostHoldsIt = () => {+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: { wechat: 1 },+ connections: [+ {+ connectionId: CONNECTION_ID,+ platform: 'wechat',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [CONNECTION_ID] });+ };++ // Draining into a host that rejects the platform is worse than doing+ // nothing: the connect meant to replace the connection fails, so it ends+ // up on neither host. A misrouted env var must be a no-op, not an outage.+ it('refuses to drain a platform off its host when the destination declines it', async () => {+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.getCapabilities.mockResolvedValue({+ platforms: ['whatsapp-baileys'],+ });+ defaultHostHoldsIt();++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();+ });++ // Same fixture, guard off β proves the case above is the guard talking and+ // not a setup that never had a teardown to begin with.+ it('performs the same move when the destination declares the platform', async () => {+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.getCapabilities.mockResolvedValue({ platforms: ['wechat'] });+ defaultHostHoldsIt();++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith(CONNECTION_ID);+ });++ // The load-bearing half of the rule. The Cloudflare gateway has no+ // capabilities endpoint, so a rollback β clearing the platform list to+ // move connections BACK to it β targets a host that declares nothing.+ // Reading that silence as a refusal would make rollback impossible.+ it('does not treat a host that declares nothing as refusing anything', async () => {+ mockNodeGateway.platforms = [];+ mockGatewayClient.getCapabilities.mockResolvedValue(null);+ // The node host is the one still holding it β this is the rollback.+ mockNodeGatewayClient.getStats.mockResolvedValue({+ byPlatform: { wechat: 1 },+ connections: [+ {+ connectionId: CONNECTION_ID,+ platform: 'wechat',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });+ mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [CONNECTION_ID] });+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });++ await service.ensureRunning();++ expect(mockNodeGatewayClient.disconnect).toHaveBeenCalledWith(CONNECTION_ID);+ });++ it('skips the connect for a bot-channel platform the host declines', async () => {+ mockNodeGateway.platforms = ['discord'];+ mockNodeGatewayClient.getCapabilities.mockResolvedValue({ platforms: ['wechat'] });+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockFindAllLinksByPlatform.mockResolvedValue([]);+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord'+ ? [+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },+ ]+ : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });++ await service.ensureRunning();++ expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/gateway/index.reconcile.test.ts b/apps/server/src/services/gateway/index.reconcile.test.tsnew file mode 100644index 00000000000..9bc9fb77fc0--- /dev/null+++ b/apps/server/src/services/gateway/index.reconcile.test.ts@@ -0,0 +1,560 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GatewayService } from '.';+import {+ mockFindByIds,+ mockFindEnabledByPlatform,+ mockGatewayClient,+ mockGatewayEnv,+ mockResolveConnectionMode,+ mockUpdateBotRuntimeStatus,+ resetGatewayServiceMocks,+} from './testUtils';++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => m.envsGatewayModule()));+vi.mock('./MessageGatewayClient', () =>+ import('./testUtils').then((m) => m.messageGatewayClientModule()),+);+vi.mock('@/database/models/messengerAccountLink', () =>+ import('./testUtils').then((m) => m.messengerAccountLinkModule()),+);+vi.mock('./GatewayManager', () => import('./testUtils').then((m) => m.gatewayManagerModule()));+vi.mock('@/database/core/db-adaptor', () => import('./testUtils').then((m) => m.dbAdaptorModule()));+vi.mock('@/database/models/agentBotProvider', () =>+ import('./testUtils').then((m) => m.agentBotProviderModule()),+);+vi.mock('@/server/modules/KeyVaultsEncrypt', () =>+ import('./testUtils').then((m) => m.keyVaultsEncryptModule()),+);+vi.mock('./runtimeStatus', () => import('./testUtils').then((m) => m.runtimeStatusModule()));+vi.mock('@/business/server/bot/featureAccess', () =>+ import('./testUtils').then((m) => m.featureAccessModule()),+);+vi.mock('@/server/services/messenger/installations', () =>+ import('./testUtils').then((m) => m.messengerInstallationsModule()),+);+vi.mock('@/server/services/messenger/platforms', () =>+ import('./testUtils').then((m) => m.messengerPlatformsModule()),+);+vi.mock('../bot/platforms', () => import('./testUtils').then((m) => m.botPlatformsModule()));++describe('GatewayService', () => {+ let service: GatewayService;++ beforeEach(() => {+ resetGatewayServiceMocks();+ service = new GatewayService();+ });++ 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 are deferred+ // instead of waking dormant DOs or being treated as disconnected.+ 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');+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ 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' }),+ { ensure: true },+ );+ });++ 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('ensure-wakes registered-only desired ids instead of leaving them stranded', 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.connect.mockResolvedValue({ status: 'connecting' });++ await service.ensureRunning();++ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'prov-1' }),+ { ensure: true },+ );+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });++ it('keeps a parked registered-only connection parked (ensure 409 is not a status reset)', 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.connect.mockRejectedValue(new Error('409 connection parked'));++ await service.ensureRunning();++ // The 409 must not overwrite the bot's runtime status with a fresh state.+ expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalledWith(+ expect.objectContaining({ applicationId: 'app-1', status: 'starting' }),+ );+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });++ it('reconnects a desired connection reported disconnected by stats without probing its DO', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? [provider] : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: {},+ connections: [+ {+ connectionId: 'prov-1',+ platform: 'discord',+ state: { status: 'disconnected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });++ await service.ensureRunning();++ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'prov-1' }),+ { ensure: true },+ );+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });++ it('reconciles 2,000 registered connections with two snapshot requests and no per-connection probes', async () => {+ const providers = Array.from({ length: 2000 }, (_, index) => ({+ ...provider,+ applicationId: `app-${index}`,+ id: `prov-${index}`,+ }));++ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? providers : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: providers.map(({ id }) => id),+ });++ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });++ await service.ensureRunning();++ expect(mockGatewayClient.getStats).toHaveBeenCalledTimes(1);+ expect(mockGatewayClient.getRegisteredIds).toHaveBeenCalledTimes(1);+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ // Registered-only wakes are capped per round so a large fleet cannot+ // turn the reconcile into a wake storm; the remainder waits for the+ // next cron round.+ expect(mockGatewayClient.connect).toHaveBeenCalledTimes(50);+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });++ it('samples registered-only wakes instead of always burning the cap on the same prefix', async () => {+ // A stable iteration order + head-first cap would starve ids after+ // position 50 forever when the early ones stay registered-only (parked+ // 409s). Force the sampler's rng to pick from the tail and assert the+ // selection is not the head prefix.+ const providers = Array.from({ length: 2000 }, (_, index) => ({+ ...provider,+ applicationId: `app-${index}`,+ id: `prov-${index}`,+ }));++ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? providers : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: providers.map(({ id }) => id),+ });+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });++ const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0.999_999);+ try {+ await service.ensureRunning();+ } finally {+ randomSpy.mockRestore();+ }++ expect(mockGatewayClient.connect).toHaveBeenCalledTimes(50);+ const wokenIds = new Set(+ mockGatewayClient.connect.mock.calls.map(+ (call) => (call[0] as { connectionId: string }).connectionId,+ ),+ );+ // rng pinned to ~1 β the sampler reaches the tail; the old head-first+ // cap could only ever pick prov-0..prov-49 and would return exactly+ // that prefix.+ expect(wokenIds.has('prov-1999')).toBe(true);+ const isHeadPrefix = [...wokenIds].every((id) => Number(id.split('-')[1]) < 50);+ expect(isHeadPrefix).toBe(false);+ });++ it('uses registered ids as a complete existence snapshot when stats is unavailable', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? [provider] : [],+ );+ mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });++ await service.ensureRunning();++ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ // With no stats, every desired id is registered-only (status unknown) β+ // still handled via the capped ensure wake, never a per-DO status probe.+ expect(mockGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'prov-1' }),+ { ensure: true },+ );+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });++ it('defers missing desired ids when registered ids are unavailable', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? [provider] : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registered unavailable'));++ await service.ensureRunning();++ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/gateway/index.runtime.test.ts b/apps/server/src/services/gateway/index.runtime.test.tsnew file mode 100644index 00000000000..0ad2c074b2e--- /dev/null+++ b/apps/server/src/services/gateway/index.runtime.test.ts@@ -0,0 +1,200 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GatewayService } from '.';+import {+ mockFindByAgentId,+ mockFindEnabledByPlatformAndAppId,+ mockGatewayClient,+ mockGatewayEnv,+ mockGatewayManager,+ mockResolveConnectionMode,+ mockResolveMessengerInstallation,+ mockUpdateBotRuntimeStatus,+ resetGatewayServiceMocks,+} from './testUtils';++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => m.envsGatewayModule()));+vi.mock('./MessageGatewayClient', () =>+ import('./testUtils').then((m) => m.messageGatewayClientModule()),+);+vi.mock('@/database/models/messengerAccountLink', () =>+ import('./testUtils').then((m) => m.messengerAccountLinkModule()),+);+vi.mock('./GatewayManager', () => import('./testUtils').then((m) => m.gatewayManagerModule()));+vi.mock('@/database/core/db-adaptor', () => import('./testUtils').then((m) => m.dbAdaptorModule()));+vi.mock('@/database/models/agentBotProvider', () =>+ import('./testUtils').then((m) => m.agentBotProviderModule()),+);+vi.mock('@/server/modules/KeyVaultsEncrypt', () =>+ import('./testUtils').then((m) => m.keyVaultsEncryptModule()),+);+vi.mock('./runtimeStatus', () => import('./testUtils').then((m) => m.runtimeStatusModule()));+vi.mock('@/business/server/bot/featureAccess', () =>+ import('./testUtils').then((m) => m.featureAccessModule()),+);+vi.mock('@/server/services/messenger/installations', () =>+ import('./testUtils').then((m) => m.messengerInstallationsModule()),+);+vi.mock('@/server/services/messenger/platforms', () =>+ import('./testUtils').then((m) => m.messengerPlatformsModule()),+);+vi.mock('../bot/platforms', () => import('./testUtils').then((m) => m.botPlatformsModule()));++describe('GatewayService', () => {+ let service: GatewayService;++ beforeEach(() => {+ resetGatewayServiceMocks();+ service = new GatewayService();+ });++ // βββ useMessageGateway βββ++ describe('useMessageGateway', () => {+ it('returns false when client is not enabled', () => {+ mockGatewayClient.isEnabled = false;+ expect(service.useMessageGateway).toBe(false);+ });++ it('returns true when client is enabled', () => {+ mockGatewayClient.isEnabled = true;+ expect(service.useMessageGateway).toBe(true);+ });+ });++ describe('runtime status refresh', () => {+ beforeEach(() => {+ mockGatewayClient.isEnabled = true;+ mockResolveConnectionMode.mockReturnValue('websocket');+ });++ it('preserves gateway error codes during a single refresh', async () => {+ mockFindEnabledByPlatformAndAppId.mockResolvedValue({ id: 'prov-1', settings: {} });+ mockGatewayClient.getStatus.mockResolvedValue({+ state: { error: 'invalid token', errorCode: 'invalid_credentials', status: 'error' },+ });++ await service.refreshBotRuntimeStatus('discord', 'app-1');++ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({+ applicationId: 'app-1',+ errorCode: 'invalid_credentials',+ errorMessage: 'invalid token',+ platform: 'discord',+ status: 'failed',+ });+ });++ it('preserves gateway error codes during an agent-wide refresh', async () => {+ mockFindByAgentId.mockResolvedValue([+ {+ applicationId: 'app-1',+ enabled: true,+ id: 'prov-1',+ platform: 'discord',+ settings: {},+ },+ ]);+ mockGatewayClient.getStatus.mockResolvedValue({+ state: { error: 'invalid token', errorCode: 'invalid_credentials', status: 'error' },+ });++ await service.refreshBotRuntimeStatusesByAgent('agent-1');++ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({+ applicationId: 'app-1',+ errorCode: 'invalid_credentials',+ errorMessage: 'invalid token',+ platform: 'discord',+ status: 'failed',+ });+ });+ });++ // βββ ensureRunning βββ++ describe('ensureRunning', () => {+ describe('in-process mode (gateway disabled)', () => {+ it('starts local GatewayManager', async () => {+ await service.ensureRunning();++ expect(mockGatewayManager.start).toHaveBeenCalled();+ });++ it('skips start if GatewayManager already running', async () => {+ mockGatewayManager.isRunning = true;++ await service.ensureRunning();++ expect(mockGatewayManager.start).not.toHaveBeenCalled();+ });+ });++ describe('gateway mode (ENABLED=1)', () => {+ beforeEach(() => {+ mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = '1';+ mockGatewayClient.isConfigured = true;+ mockGatewayClient.isEnabled = true;+ });++ it('calls syncGatewayConnections instead of starting local manager', async () => {+ await service.ensureRunning();++ expect(mockGatewayManager.start).not.toHaveBeenCalled();+ });+ });+ });++ describe('per-user messenger lifecycle', () => {+ it('registers WeChat as a real polling connection with the complete QR credential bundle', async () => {+ mockGatewayClient.isEnabled = true;+ mockResolveMessengerInstallation.mockResolvedValue({+ applicationId: '[email protected]',+ baseUrl: 'https://ilink.example.com',+ botId: '[email protected]',+ botToken: 'secret-token',+ });++ const connectionId = await service.ensureUserMessengerConnected({+ installationKey: 'wechat:[email protected]',+ platform: 'wechat',+ userId: 'user-1',+ });++ expect(connectionId).toBe('messenger:wechat:[email protected]:user-user-1');+ expect(mockGatewayClient.connect).toHaveBeenCalledWith({+ applicationId: '[email protected]',+ // Per-user messenger connections have no bot-provider settings row, so+ // gated capabilities always resolve to disabled.+ capabilities: { messageMonitoring: { enabled: false } },+ connectionId,+ connectionMode: 'polling',+ credentials: {+ baseUrl: 'https://ilink.example.com',+ botId: '[email protected]',+ botToken: 'secret-token',+ webhookToken: 'gateway-service-token',+ },+ platform: 'wechat',+ userId: 'user-1',+ webhookPath: '/api/agent/messenger/webhooks/wechat',+ });+ });++ it('disconnects a user WeChat poller even when active gateway flows are disabled', async () => {+ mockGatewayClient.isConfigured = true;+ mockGatewayClient.isEnabled = false;++ await service.disconnectUserMessenger({+ installationKey: 'wechat:[email protected]',+ platform: 'wechat',+ userId: 'user-1',+ });++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith(+ 'messenger:wechat:[email protected]:user-user-1',+ );+ });+ });+});diff --git a/apps/server/src/services/gateway/index.sync.test.ts b/apps/server/src/services/gateway/index.sync.test.tsnew file mode 100644index 00000000000..6a7c939d68c--- /dev/null+++ b/apps/server/src/services/gateway/index.sync.test.ts@@ -0,0 +1,356 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GatewayService } from '.';+import {+ mockFindEnabledByPlatform,+ mockGatewayClient,+ mockGatewayEnv,+ mockIsBotFeatureAccessAllowed,+ mockResolveConnectionMode,+ mockUpdateBotRuntimeStatus,+ resetGatewayServiceMocks,+} from './testUtils';++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => m.envsGatewayModule()));+vi.mock('./MessageGatewayClient', () =>+ import('./testUtils').then((m) => m.messageGatewayClientModule()),+);+vi.mock('@/database/models/messengerAccountLink', () =>+ import('./testUtils').then((m) => m.messengerAccountLinkModule()),+);+vi.mock('./GatewayManager', () => import('./testUtils').then((m) => m.gatewayManagerModule()));+vi.mock('@/database/core/db-adaptor', () => import('./testUtils').then((m) => m.dbAdaptorModule()));+vi.mock('@/database/models/agentBotProvider', () =>+ import('./testUtils').then((m) => m.agentBotProviderModule()),+);+vi.mock('@/server/modules/KeyVaultsEncrypt', () =>+ import('./testUtils').then((m) => m.keyVaultsEncryptModule()),+);+vi.mock('./runtimeStatus', () => import('./testUtils').then((m) => m.runtimeStatusModule()));+vi.mock('@/business/server/bot/featureAccess', () =>+ import('./testUtils').then((m) => m.featureAccessModule()),+);+vi.mock('@/server/services/messenger/installations', () =>+ import('./testUtils').then((m) => m.messengerInstallationsModule()),+);+vi.mock('@/server/services/messenger/platforms', () =>+ import('./testUtils').then((m) => m.messengerPlatformsModule()),+);+vi.mock('../bot/platforms', () => import('./testUtils').then((m) => m.botPlatformsModule()));++describe('GatewayService', () => {+ let service: GatewayService;++ beforeEach(() => {+ resetGatewayServiceMocks();+ service = new GatewayService();+ });++ // βββ syncGatewayConnections βββ++ describe('syncGatewayConnections (via ensureRunning)', () => {+ beforeEach(() => {+ mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = '1';+ mockGatewayClient.isConfigured = true;+ mockGatewayClient.isEnabled = true;+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });+ });++ it('skips webhook-mode providers', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },+ ]);+ mockResolveConnectionMode.mockReturnValue('webhook');++ await service.ensureRunning();++ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('ensure-wakes a registered-only desired provider without probing status', async () => {+ // Registered-only (pruned from stats) used to be skipped outright, but a+ // stranded DO (alarm chain lost) looks exactly like this and sleeps+ // forever unless woken. The wake is an `ensure` connect, never a status+ // probe: parked connections answer 409 and keep their park.+ mockFindEnabledByPlatform.mockResolvedValue([+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },+ ]);+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });++ await service.ensureRunning();++ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'prov-1' }),+ { ensure: true },+ );+ });++ it('connects disconnected providers', async () => {+ 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.connect.mockResolvedValue({ status: 'connecting' });++ await service.ensureRunning();++ expect(mockGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({+ applicationId: 'app-1',+ connectionId: 'prov-1',+ platform: 'discord',+ }),+ { ensure: true },+ );+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'starting' }),+ );+ });++ it('persists a dormant ensure result as dormant, not starting', async () => {+ // An `ensure` reconcile of a sparse-polling DO can legitimately return+ // `dormant`; it must be mapped through the shared helper so it is not+ // collapsed to `starting` (the DO sends no correcting callback).+ 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.connect.mockResolvedValue({ status: 'dormant' });++ await service.ensureRunning();++ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'dormant' }),+ );+ expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalledWith(+ expect.objectContaining({ status: 'starting' }),+ );+ });++ it('disconnects paid-only WeChat providers when the owner is on a free plan', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>+ platform === 'wechat'+ ? [+ {+ applicationId: 'wechat-app',+ credentials: { botToken: 'token' },+ id: 'wechat-provider',+ settings: {},+ userId: 'free-user',+ },+ ]+ : [],+ );+ mockResolveConnectionMode.mockReturnValue('polling');+ mockIsBotFeatureAccessAllowed.mockResolvedValue(false);+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });++ await service.ensureRunning();++ expect(mockIsBotFeatureAccessAllowed).toHaveBeenCalledWith({+ applicationId: 'wechat-app',+ platform: 'wechat',+ userId: 'free-user',+ workspaceId: undefined,+ });+ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('wechat-provider');+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(+ expect.objectContaining({+ applicationId: 'wechat-app',+ errorMessage: 'This bot channel requires a paid plan.',+ platform: 'wechat',+ status: 'failed',+ }),+ );+ });++ it.each([+ { snapshot: 'stats-only', statsUnavailable: false },+ { snapshot: 'unavailable', statsUnavailable: true },+ ])(+ 'disconnects a paid-gated provider when the registry snapshot is $snapshot',+ async ({ statsUnavailable }) => {+ mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>+ platform === 'wechat'+ ? [+ {+ applicationId: 'wechat-app',+ credentials: { botToken: 'token' },+ id: 'wechat-provider',+ settings: {},+ userId: 'free-user',+ },+ ]+ : [],+ );+ mockResolveConnectionMode.mockReturnValue('polling');+ mockIsBotFeatureAccessAllowed.mockResolvedValue(false);+ mockGatewayClient.getRegisteredIds.mockRejectedValue(+ new Error('registered-ids unavailable'),+ );+ if (statsUnavailable) {+ mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));+ }++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('wechat-provider');+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ },+ );++ it('sets connected status for sync connect result', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },+ ]);+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockGatewayClient.connect.mockResolvedValue({ status: 'connected' });++ await service.ensureRunning();++ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'connected' }),+ );+ });++ it('defers desired providers when the gateway snapshot is unavailable', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },+ ]);+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));+ mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registered-ids unavailable'));++ await service.ensureRunning();++ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('handles connect failure gracefully', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },+ ]);+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockGatewayClient.connect.mockRejectedValue(new Error('timeout'));++ // Should not throw+ 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.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });++ await service.ensureRunning();++ // Fail-open: no disconnect, provider stays in the desired set. As a+ // desired registered-only id it may receive the idempotent ensure wake,+ // which preserves whatever state the gateway holds.+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).not.toHaveBeenCalledWith(expect.anything(), {+ ensure: false,+ });+ });++ it('does not repeatedly disconnect a gated provider absent from the gateway snapshot', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>+ platform === 'wechat'+ ? [+ {+ applicationId: 'wechat-app',+ credentials: { botToken: 'token' },+ id: 'wechat-provider',+ settings: {},+ userId: 'free-user',+ },+ ]+ : [],+ );+ mockResolveConnectionMode.mockReturnValue('polling');+ mockIsBotFeatureAccessAllowed.mockResolvedValue(false);++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(+ expect.objectContaining({+ applicationId: 'wechat-app',+ status: 'failed',+ }),+ );+ });+ });+});diff --git a/apps/server/src/services/gateway/index.ts b/apps/server/src/services/gateway/index.tsindex 28daa6a6627..28c3ee503f6 100644--- a/apps/server/src/services/gateway/index.ts+++ b/apps/server/src/services/gateway/index.ts@@ -1,240 +1,30 @@import debug from 'debug';-import pMap from 'p-map';-import {- assertBotFeatureAccess,- getBotFeatureBlockedMessage,- isBotFeatureAccessAllowed,-} from '@/business/server/bot/featureAccess';-import type { MessengerPlatform } from '@/config/messenger';+import { assertBotFeatureAccess } from '@/business/server/bot/featureAccess';import { getServerDB } from '@/database/core/db-adaptor';-import {- AgentBotProviderModel,- type DecryptedBotProvider,-} from '@/database/models/agentBotProvider';-import {- type DecryptedMessengerAccountLink,- MessengerAccountLinkModel,-} from '@/database/models/messengerAccountLink';-import { gatewayEnv } from '@/envs/gateway';+import { AgentBotProviderModel } 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';-import { type BotRuntimeStatus, type BotRuntimeStatusSnapshot } from '@/types/botRuntimeStatus';+import type { BotRuntimeStatusSnapshot } from '@/types/botRuntimeStatus';-import type { ConnectionMode } from '../bot/platforms';-import {- extractWatchKeywordEntries,- platformRegistry,- resolveConnectionMode,-} from '../bot/platforms';+import { type ConnectionMode, platformRegistry, resolveConnectionMode } from '../bot/platforms';import { BOT_CONNECT_QUEUE_EXPIRE_MS, BotConnectQueue } from './botConnectQueue';import { createGatewayManager, getGatewayManager } from './GatewayManager';+import { mapGatewayStatusToRuntimeStatus, resolveBotGatewayCapabilities } from './gatewayMapping';import {getConfiguredMessageGatewayHosts,getMessageGatewayClient,getMessageGatewayClientForHost,isAnyMessageGatewayEnabled,- type MessageGatewayCapabilities,- type MessageGatewayConnectionConfig,- type MessageGatewayConnectionStatus,type MessageGatewayHost,- resolveMessageGatewayHost,} from './MessageGatewayClient';import { BOT_RUNTIME_STATUSES, getBotRuntimeStatus, updateBotRuntimeStatus } from './runtimeStatus';--/**- * Per-user messenger gateway connections live on the gateway as webhook-mode- * DOs that only exist to receive `startTyping` / `stopTyping`. We keep an- * in-process map of `connectionId β expireAt` so a hot conversation only- * triggers one `client.connect` per process per TTL window. LRU cap defends- * against unbounded growth in a long-running replica with a wide active set.- *- * Module-scoped (not instance-scoped) because `new GatewayService()` is built- * fresh on every call site β instance state would defeat the cache.- */-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;--/**- * Cap on registered-only wake-up connects per sync round. A registered-only id- * (in the registry but pruned from live stats) is usually a parked or- * self-waking dormant DO, but a stranded DO β alarm chain lost after a deploy- * cancelled its in-flight alarm invocation β looks identical and sleeps- * forever unless something wakes it. The `ensure` connect is that wake: parked- * connections answer 409 and keep their park, healthy ones no-op. The cap- * keeps a large parked backlog from turning every cron round into a fleet-wide- * wake storm; the remainder is retried on later rounds.- */-const GATEWAY_SYNC_REGISTERED_ONLY_WAKE_LIMIT = 50;--/**- * Uniformly sample up to `limit` ids via a partial Fisher-Yates shuffle.- * Stateless by design β the gateway cron runs in fresh serverless invocations,- * so a persisted round-robin cursor would need external storage; uniform- * sampling gives every candidate an expected candidates/limit-round latency- * without any state.- */-const sampleIds = (ids: string[], limit: number): Set<string> => {- if (ids.length <= limit) return new Set(ids);- const pool = [...ids];- const picked = new Set<string>();- for (let i = 0; i < limit; i++) {- const j = i + Math.floor(Math.random() * (pool.length - i));- [pool[i], pool[j]] = [pool[j], pool[i]];- picked.add(pool[i]);- }- return picked;-};--interface DesiredGatewayConnection {- connectionMode: ConnectionMode;- platform: string;- provider: DecryptedBotProvider;-}--interface ActualConnectionsSnapshot {- /**- * True when registered ids were loaded successfully, making absence from- * `connections` authoritative. False means the snapshot only covers live- * stats, so 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>;-}--/** What one host's drain phase removed, carried into its connect-phase log line. */-interface HostDrainCounts {- gatedDisconnected: number;- gatedSize: number;- stale: number;-}--function mapGatewayStatusToRuntimeStatus(- status: MessageGatewayConnectionStatus['state']['status'],-): BotRuntimeStatus {- switch (status) {- case 'connected': {- return BOT_RUNTIME_STATUSES.connected;- }- case 'connecting': {- return BOT_RUNTIME_STATUSES.starting;- }- case 'disconnected': {- return BOT_RUNTIME_STATUSES.disconnected;- }- case 'dormant': {- return BOT_RUNTIME_STATUSES.dormant;- }- case 'error': {- return BOT_RUNTIME_STATUSES.failed;- }- }-}+import { syncGatewayConnections } from './sync';+import * as desiredForHost from './sync/desiredForHost';+import type { UserMessengerConnectionParams } from './userMessenger';+import * as userMessenger from './userMessenger';const log = debug('lobe-server:service:gateway');-/**- * Derive edge-filtering capabilities for a bot-channel connection from its- * settings. Monitoring is enabled purely by "has watch keywords configured":- * feature-access gating stays server-side (BotMessageRouter), so access- * changes never require a gateway reconnect and operators with existing- * rules are never cut off by a stale edge config.- */-const resolveBotGatewayCapabilities = (- settings?: Record<string, unknown> | null,-): MessageGatewayCapabilities => ({- messageMonitoring: { enabled: extractWatchKeywordEntries(settings ?? undefined).length > 0 },-});--/**- * The connect payload for one bot-channel provider.- *- * Extracted because two callers build it now: the periodic reconcile, which- * pushes it to the gateway, and the gateway's own boot-time pull, which- * receives it and connects itself. A second builder would drift, and the- * connection the gateway ends up holding would then depend on which side- * established it.- *- * Payload only, deliberately no side effects. The push path also writes a- * runtime status from the connect result, but that belongs to whoever- * actually connected: on the pull path the gateway does, so its state- * callback is what reports the real status back. Guessing a status here would- * record a connection as live that nothing has established yet.- */-const buildBotProviderConnectConfig = ({- connectionMode,- platform,- provider,-}: DesiredGatewayConnection): MessageGatewayConnectionConfig => ({- applicationId: provider.applicationId,- capabilities: resolveBotGatewayCapabilities(provider.settings),- connectionId: provider.id,- connectionMode,- credentials: provider.credentials,- platform,- userId: provider.userId,- webhookPath: `/api/agent/webhooks/${platform}/${provider.applicationId}`,-});--/** The connect payload for one messenger polling link. Same rationale as above. */-const buildMessengerPollingConnectConfig = ({- connectionId,- link,- platform,-}: {- connectionId: string;- link: DecryptedMessengerAccountLink;- platform: string;-}): MessageGatewayConnectionConfig => {- const credentials = link.credentials as {- baseUrl?: string;- botId?: string;- botToken?: string;- };-- return {- applicationId: link.applicationId!,- // Messenger-owned connections never consume passive channel monitoring β- // the shared bot only reacts to DMs and explicit mentions.- capabilities: { messageMonitoring: { enabled: false } },- connectionId,- connectionMode: 'polling',- credentials: {- baseUrl: credentials.baseUrl,- botId: credentials.botId,- botToken: credentials.botToken,- webhookToken: gatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN,- },- platform,- userId: link.userId,- webhookPath: `/api/agent/messenger/webhooks/${platform}`,- };-};-const isVercel = !!process.env.VERCEL_ENV;export class GatewayService {@@ -250,7 +40,7 @@ export class GatewayService {async ensureRunning(): Promise<void> {if (this.useMessageGateway) {- await this.syncGatewayConnections();+ await syncGatewayConnections();return;}@@ -281,1184 +71,6 @@ export class GatewayService {}}- /**- * 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 serverDB = await getServerDB();- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();-- // Each configured host gets its own desired slice and its own actual- // snapshot, then runs the full diff independently. Cross-host moves fall- // out of the partition: a platform routed away from a host leaves its ids- // absent from that host's desired slice β the stale pass disconnects them- // there while the new host's connect pass builds them up.- const hosts = getConfiguredMessageGatewayHosts();-- // A platform name nothing recognises is a typo, and its only visible- // effect is that the migration silently does not happen β the name simply- // never matches, so everything stays on the default host. Say so once per- // round instead of leaving someone to wonder why the flip did nothing.- const routedNames = (gatewayEnv.MESSAGE_GATEWAY_NODE_PLATFORMS ?? '')- .split(',')- .map((entry) => entry.trim())- .filter(Boolean);- if (routedNames.length > 0) {- const known = new Set([- ...platformRegistry.listPlatforms().map((definition) => definition.id),- ...messengerPlatformRegistry.listPlatforms().map((definition) => definition.id),- ]);- const unknown = routedNames.filter((name) => !known.has(name));- if (unknown.length > 0) {- log(- 'Gateway sync: MESSAGE_GATEWAY_NODE_PLATFORMS names %o, which match no known platform β those entries do nothing',- unknown,- );- }- }-- // What each host says it can serve. Routing a platform to a host it cannot- // serve is otherwise an outage, not a no-op: the stale pass drains the- // connections off their old host, and the connect that should replace them- // is rejected β so they end up nowhere. One request per host per round.- const declaredPlatforms = new Map<MessageGatewayHost, Set<string> | null>();- for (const host of hosts) {- const capabilities = await getMessageGatewayClientForHost(host).getCapabilities();- declaredPlatforms.set(host, capabilities ? new Set(capabilities.platforms ?? []) : null);- }-- const { desired, desiredComplete, gated } = await this.buildDesiredConnections(- serverDB,- gateKeeper,- hosts,- );-- const snapshots = new Map<MessageGatewayHost, ActualConnectionsSnapshot | null>();- for (const host of hosts) {- snapshots.set(host, await this.fetchActualConnections(getMessageGatewayClientForHost(host)));- }-- // A cross-host move must not tear the source down before the destination- // can take over. A host whose snapshot is missing or incomplete defers- // every connect for an id it cannot see (absence doesn't prove absence),- // so disconnecting there first would take the platform dark until some- // later round. Only hosts with a complete snapshot are safe destinations.- const hostsReadyToReceive = new Set(- hosts.filter((host) => snapshots.get(host)?.complete === true),- );-- // Ids a snapshot shows on a host that no longer owns them β i.e. mid-move.- // Draining them is capped per round, so without this the destination's- // connect pass would happily build up every id the source pass had no- // budget to remove, and the overflow would run on both hosts at once.- const currentlyElsewhere = new Set<string>();- for (const [host, snapshot] of snapshots) {- if (!snapshot) continue;- for (const id of snapshot.connections.keys()) {- const entry = desired.get(id);- if (entry && resolveMessageGatewayHost(entry.platform) !== host) currentlyElsewhere.add(id);- }- }- // Filled in by each host's stale pass as it actually removes an id, which- // is what releases that id for connecting on its new owner.- const drainedThisRound = new Set<string>();-- // Two phases across ALL hosts rather than a full sync per host: every- // drain completes before any build-up. Interleaving them makes correctness- // depend on the order `hosts` happens to be in β with `['default','node']`- // a nodeβdefault rollback would run the destination's connect pass first- // (deferring everything, since nothing is drained yet), then drain the- // source, and never revisit the destination, leaving every migrated bot- // down for a whole round. Splitting the phases makes the ordering- // structural instead of emergent, in both directions.- const drainCounts = new Map<MessageGatewayHost, HostDrainCounts>();- for (const host of hosts) {- drainCounts.set(- host,- await this.drainHostConnections({- declaredPlatforms,- desired,- desiredComplete,- drainedThisRound,- gated,- host,- hostsReadyToReceive,- serverDB,- snapshot: snapshots.get(host) ?? null,- }),- );- }-- for (const host of hosts) {- await this.connectHostConnections({- counts: drainCounts.get(host) ?? { gatedDisconnected: 0, gatedSize: 0, stale: 0 },- currentlyElsewhere,- declaredPlatforms,- desired,- drainedThisRound,- host,- snapshot: snapshots.get(host) ?? null,- });- }-- await this.syncMessengerPollingConnections(- serverDB,- gateKeeper,- snapshots,- hostsReadyToReceive,- declaredPlatforms,- );-- log(- 'Gateway sync complete in %dms across %d host(s): desired=%d gated=%d',- Date.now() - startedAt,- hosts.length,- desired.size,- gated.size,- );- }-- /** Slice of the desired set whose platforms route to `host`. */- private hostDesiredSlice(- desired: Map<string, DesiredGatewayConnection>,- host: MessageGatewayHost,- ): Map<string, DesiredGatewayConnection> {- return new Map(- [...desired].filter(([, entry]) => resolveMessageGatewayHost(entry.platform) === host),- );- }-- /**- * Whether `host` has told us it cannot serve `platform`.- *- * Only an explicit declaration counts. A gateway that does not describe- * itself makes no claim, and absence of information must never be read as a- * refusal β the Cloudflare gateway has no capabilities endpoint at all, and- * treating that as "refuses everything" would block the rollback path,- * where connections move BACK to it.- */- private hostRefusesPlatform(- declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>,- host: MessageGatewayHost,- platform: string,- ): boolean {- const declared = declaredPlatforms.get(host);- return !!declared && !declared.has(platform);- }-- /** Slice of the gated set whose platforms route to `host`. */- private hostGatedSlice(gated: Map<string, string>, host: MessageGatewayHost): Set<string> {- return new Set(- [...gated]- .filter(([, platform]) => resolveMessageGatewayHost(platform) === host)- .map(([id]) => id),- );- }-- /**- * The connect payloads one host should currently be holding.- *- * This is the read half of restart recovery: a gateway that just came back- * up holds nothing, asks for this list, and builds it itself. Nothing here- * calls a gateway, so it wakes no connection and can be retried freely β- * the one write it does make is the runtime status of a paid-gated- * provider, which `buildDesiredConnections` records on the way past and- * which is true no matter who asked.- *- * `complete: false` means the desired set could not be computed in full (a- * platform's rows failed to load, key vault unavailable). The caller should- * apply what it got and ask again rather than treat a short list as the- * whole truth. Refusing to answer at all would be worse: it leaves the- * gateway holding nothing for the length of an unrelated outage.- *- * Rows that can never connect β credentials missing or undecryptable β are- * counted into `excluded` and left out. They must not fail the call: a- * single unreadable row would otherwise keep a whole gateway empty forever.- *- * Connections another host still holds are withheld and counted into- * `deferred`. Routing alone does not make a connection safe to build: right- * after a platform is routed here, the previous host is still polling it,- * and handing it over before that host is drained double-delivers every- * message until a later reconcile catches up. The periodic reconcile owns- * the hand-off; this call only refuses to race it.- */- async listDesiredConnectionsForHost(host: MessageGatewayHost): Promise<{- complete: boolean;- connections: { config: MessageGatewayConnectionConfig; ensure: true }[];- deferred: number;- excluded: number;- }> {- const serverDB = await getServerDB();- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();-- const connections: { config: MessageGatewayConnectionConfig; ensure: true }[] = [];- let excluded = 0;- let deferred = 0;-- // What every OTHER host still holds. Read-only, and only two admin- // requests per host β they reach the gateway's own registry, not the- // individual connections, so asking wakes nothing.- //- // A host whose admin surface is unreachable is treated as holding- // nothing, deliberately, and matching the reconcile's own rule: a- // steady-state deployment has no connections on the wrong host at all, so- // blocking every restart recovery on an unrelated host's outage costs far- // more availability than the duplicate window it would avoid β and that- // window only opens if the outage overlaps an actual migration.- // What this host says it can serve. Routing a platform here does not mean- // it can run it, and handing over credentials for a connection it will- // reject is handing them over for nothing. The reconcile already refuses- // to move such a platform; this refuses to arm it.- const declared = await getMessageGatewayClientForHost(host).getCapabilities();- const declaredPlatforms = new Map<MessageGatewayHost, Set<string> | null>([- [host, declared ? new Set(declared.platforms ?? []) : null],- ]);-- const elsewhere = new Set<string>();- let peersProven = true;- for (const other of getConfiguredMessageGatewayHosts()) {- if (other === host) continue;- const snapshot = await this.fetchActualConnections(getMessageGatewayClientForHost(other));-- // Absence is only evidence when the view was complete. A snapshot we- // could not fetch shows nothing, and a stats-only one omits dormant- // registrations β in both cases an id missing from it says nothing about- // whether that host released it, so nothing here can be handed over.- // Marking the answer incomplete does not substitute: the caller applies- // what it receives and only then asks again, so a flag arrives after the- // duplicate it was supposed to prevent.- if (!snapshot?.complete) {- peersProven = false;- log(- 'Gateway pull[%s]: %s host view is %s, cannot prove it released anything',- host,- other,- snapshot ? 'incomplete' : 'unavailable',- );- }-- snapshot?.connections.forEach((_status, id) => elsewhere.add(id));- }-- // Paid-gated providers never enter the desired set, so nothing here can- // hand back a connection the next reconcile round would tear down again.- const { desired, desiredComplete } = await this.buildDesiredConnections(serverDB, gateKeeper, [- host,- ]);- let complete = desiredComplete;-- for (const entry of this.hostDesiredSlice(desired, host).values()) {- if (this.hostRefusesPlatform(declaredPlatforms, host, entry.platform)) {- excluded++;- continue;- }- if (Object.keys(entry.provider.credentials).length === 0) {- excluded++;- continue;- }- if (!peersProven || elsewhere.has(entry.provider.id)) {- deferred++;- log(- 'Gateway pull[%s]: %s not proven released elsewhere, withholding',- host,- entry.provider.id,- );- continue;- }- connections.push({ config: buildBotProviderConnectConfig(entry), ensure: true });- }-- for (const definition of messengerPlatformRegistry.listPlatforms()) {- if (definition.connectionMode !== 'polling') continue;- const platform = definition.id;- if (resolveMessageGatewayHost(platform) !== host) continue;- if (this.hostRefusesPlatform(declaredPlatforms, host, platform)) {- log(- 'Gateway pull[%s]: host does not serve %s, withholding its credentials',- host,- platform,- );- continue;- }-- let links: DecryptedMessengerAccountLink[];- try {- links = await MessengerAccountLinkModel.findAllByPlatformWithCredentials(- serverDB,- platform,- gateKeeper,- );- } catch (err) {- // Same rule as the desired set: a platform we could not read makes the- // answer incomplete, not empty.- complete = false;- log('Gateway pull[%s]: messenger link listing failed for %s: %O', host, platform, err);- continue;- }-- for (const link of links) {- const credentials = link.credentials as { botToken?: string };- const connectionId = messengerConnectionIdForUser({- connectionMode: 'polling',- installationKey: `${platform}:${link.tenantId}`,- userId: link.userId,- });- if (!link.applicationId || !credentials.botToken) {- excluded++;- continue;- }- if (!peersProven || elsewhere.has(connectionId)) {- deferred++;- log(- 'Gateway pull[%s]: %s not proven released elsewhere, withholding',- host,- connectionId,- );- continue;- }- connections.push({- config: buildMessengerPollingConnectConfig({ connectionId, link, platform }),- ensure: true,- });- }- }-- // Audit surface: this is the one place that hands out a host's whole- // credential set, and it doubles as the signal that the host restarted.- // Withheld entries make this a partial answer, so the caller keeps asking- // instead of settling for the set it got. It will run out of attempts long- // before a hand-off finishes β that is fine: finishing one is the periodic- // reconcile's job, not this call's. Restart recovery is an optimisation- // over that reconcile, so when it cannot be done safely the right move is- // not to do it.- if (deferred > 0) complete = false;-- log(- 'Gateway pull[%s]: %d connection(s), excluded=%d, deferred=%d, complete=%s',- host,- connections.length,- excluded,- deferred,- complete,- );-- return { complete, connections, deferred, excluded };- }-- /**- * Phase 1 for one host: remove what should no longer be there (paid-gated- * connections, then stale ones). Runs for every host before any host's- * connect pass, so a connection is always gone from its old owner before it- * is built on its new one.- */- private async drainHostConnections(params: {- declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>;- desired: Map<string, DesiredGatewayConnection>;- desiredComplete: boolean;- drainedThisRound: Set<string>;- gated: Map<string, string>;- host: MessageGatewayHost;- hostsReadyToReceive: Set<MessageGatewayHost>;- serverDB: Awaited<ReturnType<typeof getServerDB>>;- snapshot: ActualConnectionsSnapshot | null;- }): Promise<HostDrainCounts> {- const {- declaredPlatforms,- desiredComplete,- drainedThisRound,- host,- hostsReadyToReceive,- serverDB,- snapshot: actual,- } = params;- const client = getMessageGatewayClientForHost(host);- const desired = this.hostDesiredSlice(params.desired, host);- const gated = this.hostGatedSlice(params.gated, host);-- const gatedDisconnected = await this.disconnectGatedConnections(client, actual, gated);-- // 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,- gated,- host,- hostsReadyToReceive,- drainedThisRound,- declaredPlatforms,- );- } else if (actual) {- log('Gateway sync: desired set incomplete, skipping stale-connection cleanup this round');- }-- return { gatedDisconnected, gatedSize: gated.size, stale };- }-- /**- * Phase 2 for one host: `desired β actual β connect`. Every host has already- * been drained by the time this runs.- */- private async connectHostConnections(params: {- counts: HostDrainCounts;- currentlyElsewhere: Set<string>;- declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>;- desired: Map<string, DesiredGatewayConnection>;- drainedThisRound: Set<string>;- host: MessageGatewayHost;- snapshot: ActualConnectionsSnapshot | null;- }): Promise<void> {- const {- counts,- currentlyElsewhere,- declaredPlatforms,- drainedThisRound,- host,- snapshot: actual,- } = params;- const client = getMessageGatewayClientForHost(host);- const desired = this.hostDesiredSlice(params.desired, host);-- let connected = 0;- let deferred = 0;- let skipped = 0;- let failed = 0;-- // Registered-only wake candidates are SAMPLED, not taken head-first: the- // desired map iterates in a stable order, and parked connections (409,- // stay registered-only until their 7d expiry) would otherwise burn the- // whole cap on the same prefix every round, starving stranded DOs that- // sort after position N. Uniform sampling reaches every candidate within- // an expected candidates/limit rounds with no persisted cursor.- const registeredOnlyCandidates = [...desired.values()]- .map(({ provider }) => provider.id)- .filter(- (id) => (actual?.connections.has(id) ?? false) && actual?.connections.get(id) === null,- );- const registeredOnlyWakeIds = sampleIds(- registeredOnlyCandidates,- GATEWAY_SYNC_REGISTERED_ONLY_WAKE_LIMIT,- );- const registeredOnlyDeferred = registeredOnlyCandidates.length - registeredOnlyWakeIds.size;- let registeredOnlyWakes = 0;-- await pMap(- desired.values(),- async ({ connectionMode, platform, provider }) => {- try {- // Told us it cannot serve this platform. The connect would be- // rejected anyway; skipping keeps one clear line in the log instead- // of an error per connection, and pairs with the stale pass, which- // leaves these running wherever they already are.- if (this.hostRefusesPlatform(declaredPlatforms, host, platform)) {- skipped++;- return;- }-- // 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;- }-- // Mid-move and STILL not drained, even though every host's drain- // phase has already run β so it is over this round's disconnect cap- // or its disconnect failed. Connecting now would leave the provider- // live on both gateways, double-delivering until a later round- // catches up.- if (currentlyElsewhere.has(provider.id) && !drainedThisRound.has(provider.id)) {- deferred++;- log(- 'Gateway sync[%s]: %s not yet drained from its previous host, deferring connect',- host,- provider.id,- );- return;- }-- // Registered ids are the gateway's authoritative existence set. Use- // the status already present in live stats to recover an explicitly- // disconnected connection. Registered-only ids (status null β pruned- // from stats) get a capped ensure-connect wake instead of a skip:- // see GATEWAY_SYNC_REGISTERED_ONLY_WAKE_LIMIT. Never probe per-DO- // status here.- const exists = actual?.connections.has(provider.id) ?? false;- const snapshotStatus = actual?.connections.get(provider.id);- if (exists && snapshotStatus !== 'disconnected') {- if (snapshotStatus !== null) {- skipped++;- log('Gateway sync: %s already registered, skipping', provider.id);- return;- }- if (!registeredOnlyWakeIds.has(provider.id)) {- log(- 'Gateway sync: %s registered-only, not sampled this round, deferring',- provider.id,- );- return;- }- registeredOnlyWakes++;- log('Gateway sync: %s registered-only, ensure-waking', provider.id);- }-- // Without a complete registry snapshot, absence from live stats does- // not prove the connection is missing. Fail safe and retry next round- // instead of degrading to an unbounded per-DO status probe fan-out.- if (!exists && !actual?.complete) {- deferred++;- log('Gateway sync: %s absent from incomplete snapshot, deferring', provider.id);- return;- }-- if (snapshotStatus === 'disconnected') {- log('Gateway sync: %s reported disconnected in stats, reconnecting', provider.id);- }-- // `ensure` marks this as a reconcile connect: the gateway preserves- // its park/backoff state when the config is unchanged (a parked- // connection answers 409 β counted as failed below), instead of- // letting every sync round reset stuck connections to fast retry.- const result = await client.connect(- buildBotProviderConnectConfig({ connectionMode, platform, provider }),- { ensure: true },- );-- // Gateway returns "connecting" for async persistent connections- // (e.g. Discord WebSocket), "connected" for sync webhook-mode. An- // `ensure` reconcile can also legitimately return "dormant" (the DO is- // sparse-polling and won't send a correcting callback), so map through- // the shared helper instead of collapsing every non-connected result- // to "starting" β otherwise a dormant connection is persisted as- // starting and never corrected.- await updateBotRuntimeStatus({- applicationId: provider.applicationId,- platform,- status: mapGatewayStatusToRuntimeStatus(result.status),- });-- 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[%s]: desired=%d actual=%s snapshotComplete=%s connected=%d skipped=%d deferred=%d gated=%d gatedDisconnected=%d stale=%d failed=%d registeredOnlyWakes=%d registeredOnlyDeferred=%d',- host,- desired.size,- actual ? actual.connections.size : 'unavailable',- actual?.complete ?? false,- connected,- skipped,- deferred,- counts.gatedSize,- counts.gatedDisconnected,- counts.stale,- failed,- registeredOnlyWakes,- registeredOnlyDeferred,- );- }-- /**- * Reconcile per-user polling messenger connections (WeChat today) onto the- * gateway host that owns their platform.- *- * Bot-provider connections are covered by the desired/actual diff above,- * but messenger-owned ids (`messenger:<platform>:β¦`) were historically- * excluded from reconciliation: on the default gateway they are durable- * Durable Objects, lazily created at link time. Two things break that- * model:- *- * - the Node gateway keeps connections in process memory, so without a- * reconcile every redeploy would silently stop all polling until each- * user re-linked;- * - moving a platform between hosts needs the old host's connections torn- * down and the new host's rebuilt, link by link.- *- * Webhook typing shards and websocket singletons stay excluded β they are- * lazily managed (`ensureUserMessengerConnected`) and harmless to lose.- */- private async syncMessengerPollingConnections(- serverDB: Awaited<ReturnType<typeof getServerDB>>,- gateKeeper: KeyVaultsGateKeeper,- snapshots: Map<MessageGatewayHost, ActualConnectionsSnapshot | null>,- hostsReadyToReceive: Set<MessageGatewayHost>,- declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>,- ): Promise<void> {- for (const definition of messengerPlatformRegistry.listPlatforms()) {- if (definition.connectionMode !== 'polling') continue;- const platform = definition.id;- const host = resolveMessageGatewayHost(platform);- const client = getMessageGatewayClientForHost(host);- if (!client.isEnabled) continue;-- // Routed to a host that says it cannot serve this platform. Skipping the- // whole platform leaves every connection where it already runs β the- // teardown below would otherwise strip them from their current host for- // a destination that will reject them.- if (this.hostRefusesPlatform(declaredPlatforms, host, platform)) {- log(- 'Gateway sync[%s]: host does not serve %s β leaving its connections where they are',- host,- platform,- );- continue;- }-- const prefix = `messenger:${platform}:`;-- // Load the links BEFORE touching any host. A migration that drains the- // old host and only then discovers it cannot read the account links- // leaves those users offline until a later round β so the lookup that- // can fail runs while a failure is still free.- let links: DecryptedMessengerAccountLink[];- try {- links = await MessengerAccountLinkModel.findAllByPlatformWithCredentials(- serverDB,- platform,- gateKeeper,- );- } catch (err) {- log('Gateway sync[%s]: messenger link listing failed for %s: %O', host, platform, err);- continue;- }-- // Classify BEFORE draining anything: the teardown below has to know- // which ids it must not touch, and a link is only safe to move once we- // know we can rebuild it on the other side.- const desired = new Map<string, DecryptedMessengerAccountLink>();- // Linked accounts we cannot connect but must not treat as unlinked.- const unusable = new Set<string>();- for (const link of links) {- const credentials = link.credentials as { botToken?: string };- const connectionId = messengerConnectionIdForUser({- connectionMode: 'polling',- installationKey: `${platform}:${link.tenantId}`,- userId: link.userId,- });- // A link whose credentials fail to decrypt comes back with an empty- // object, indistinguishable here from one that never had a token.- // Either way a connect can only fail β but the account IS still- // linked, so it must stay out of the stale pass: otherwise a- // key-vault mismatch reads as "everyone unlinked" and tears down- // every healthy poller in a single round.- if (!link.applicationId || !credentials.botToken) {- unusable.add(connectionId);- continue;- }- desired.set(connectionId, link);- }-- // Ids this round leaves running on a host that no longer owns them β- // past the per-round cap, failed to disconnect, or not attempted at all.- // The connect pass must skip these: connecting one while it still polls- // elsewhere is exactly the double-delivery this pass exists to prevent.- const stillElsewhere = new Set<string>();-- // Tear down this platform's per-user connections on every other host β- // a polling platform hosted twice double-delivers every message. Runs- // before the owning host's connect pass for the same reason- // (disconnect-then-connect ordering during a host migration).- for (const [otherHost, otherSnapshot] of snapshots) {- if (otherHost === host) continue;-- // A host we cannot see cannot be drained, and its admin surface being- // down does not mean its pollers stopped. Deliberate trade-off: we- // still connect on the owning host rather than block on it, because a- // steady-state deployment has no strays here at all, and holding every- // reconcile hostage to an unrelated host's admin outage costs far more- // availability than the duplicate-delivery window it would avoid β- // which only opens if that outage overlaps an actual migration.- if (!otherSnapshot) {- log(- 'Gateway sync[%s]: %s host snapshot unavailable β cannot confirm %s is drained there',- host,- otherHost,- platform,- );- continue;- }-- // An unusable link cannot be rebuilt on the owning host, so moving it- // is a one-way trip to offline. Leave its existing connection alone β- // wherever it currently runs, it is still serving that user.- const strayIds = [...otherSnapshot.connections.keys()].filter(- (id) => id.startsWith(prefix) && !unusable.has(id),- );- if (strayIds.length === 0) continue;-- // Same rule as the bot-provider stale pass: never strip the source- // while the destination cannot take over, or the platform goes dark- // for the length of the destination's outage.- if (!hostsReadyToReceive.has(host)) {- strayIds.forEach((id) => stillElsewhere.add(id));- log(- 'Gateway sync[%s]: %s host has no usable snapshot β leaving %d %s connection(s) on %s host',- host,- host,- strayIds.length,- platform,- otherHost,- );- continue;- }-- const batch = strayIds.slice(0, GATEWAY_SYNC_STALE_DISCONNECT_LIMIT);- strayIds.slice(GATEWAY_SYNC_STALE_DISCONNECT_LIMIT).forEach((id) => stillElsewhere.add(id));- if (batch.length < strayIds.length) {- log(- 'Gateway sync[%s]: capping cross-host %s migration to %d of %d this round',- host,- platform,- batch.length,- strayIds.length,- );- }-- const otherClient = getMessageGatewayClientForHost(otherHost);- await pMap(- batch,- async (id) => {- try {- await otherClient.disconnect(id);- log('Gateway sync[%s]: moved %s off %s host', host, id, otherHost);- } catch (err) {- stillElsewhere.add(id);- log('Gateway sync[%s]: cross-host disconnect failed %s: %O', host, id, err);- }- },- { concurrency: GATEWAY_SYNC_CONCURRENCY },- );- }-- const snapshot = snapshots.get(host) ?? null;-- let connected = 0;- let skipped = 0;- let failed = 0;-- await pMap(- [...desired],- async ([connectionId, link]) => {- // Without any snapshot we can't tell existing from missing β blind- // reconnects would churn healthy pollers, so wait for a round with- // a working admin surface.- if (!snapshot) {- skipped++;- return;- }- // Still polling on a host that no longer owns it (past this round's- // migration cap, or its disconnect failed). Connecting here too- // would double-deliver every inbound message until the next round- // finishes the move.- if (stillElsewhere.has(connectionId)) {- skipped++;- log(- 'Gateway sync[%s]: %s still live on another host, deferring connect',- host,- connectionId,- );- return;- }- const exists = snapshot.connections.has(connectionId);- const status = snapshot.connections.get(connectionId);- // Live and healthy β nothing to do. Registered-only (null) gets an- // ensure-connect wake (parked connections answer 409 and keep their- // park); missing from a complete snapshot gets a real connect.- if (exists && status !== null && status !== 'disconnected') {- skipped++;- return;- }- if (!exists && !snapshot.complete) {- skipped++;- return;- }- try {- await client.connect(- buildMessengerPollingConnectConfig({ connectionId, link, platform }),- { ensure: true },- );- connected++;- } catch (err) {- failed++;- log('Gateway sync[%s]: messenger connect failed %s: %O', host, connectionId, err);- }- },- { concurrency: GATEWAY_SYNC_CONCURRENCY },- );-- // Unlinked accounts whose connection still exists on the owning host.- // `unusable` ids are linked but unconnectable β they belong to neither- // set and must survive this pass untouched.- let stale = 0;- if (snapshot?.complete) {- const staleIds = [...snapshot.connections.keys()]- .filter((id) => id.startsWith(prefix) && !desired.has(id) && !unusable.has(id))- .slice(0, GATEWAY_SYNC_STALE_DISCONNECT_LIMIT);- await pMap(- staleIds,- async (id) => {- try {- await client.disconnect(id);- stale++;- log('Gateway sync[%s]: disconnected unlinked messenger connection %s', host, id);- } catch (err) {- log('Gateway sync[%s]: messenger stale disconnect failed %s: %O', host, id, err);- }- },- { concurrency: GATEWAY_SYNC_CONCURRENCY },- );- }-- log(- 'Gateway sync[%s]: messenger %s links=%d connected=%d skipped=%d stale=%d failed=%d',- host,- platform,- desired.size,- connected,- skipped,- 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 tracked separately and excluded from the desired- * set so the caller can disconnect only ids the gateway still holds. 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,- hosts: MessageGatewayHost[],- ): Promise<{- desired: Map<string, DesiredGatewayConnection>;- desiredComplete: boolean;- /** Paid-gated provider id β platform (platform drives host partitioning). */- gated: Map<string, string>;- }> {- const desired = new Map<string, DesiredGatewayConnection>();- let desiredComplete = true;- const gated = new Map<string, string>();-- for (const definition of platformRegistry.listPlatforms()) {- const platform = definition.id;-- // Only platforms owned by one of `hosts`. Loading the rest would decrypt- // credentials for connections this call is never going to look at β pure- // waste for a single-host pull, and a wider blast radius on failure.- if (!hosts.includes(resolveMessageGatewayHost(platform))) continue;-- 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 gatedOnPlatform = 0;- for (const provider of providers) {- 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') continue;-- let allowed = true;- try {- allowed = await isBotFeatureAccessAllowed({- applicationId: provider.applicationId,- platform,- userId: provider.userId,- workspaceId: provider.workspaceId ?? undefined,- });- } catch (err) {- log(- 'Gateway sync: feature gate check failed %s, keeping connection: %O',- provider.id,- err,- );- }-- if (!allowed) {- gated.set(provider.id, platform);- gatedOnPlatform++;- await updateBotRuntimeStatus({- applicationId: provider.applicationId,- errorMessage: getBotFeatureBlockedMessage(- platform,- provider.workspaceId ? 'workspace' : 'personal',- ),- platform,- status: BOT_RUNTIME_STATUSES.failed,- });- continue;- }-- desired.set(provider.id, { connectionMode, platform, provider });- }- // One line per platform, not per provider: a shared dev database holds- // hundreds of gated bots, and a line each drowned every other log in- // the sync. The per-id set still reaches the gated-disconnect step.- if (gatedOnPlatform > 0)- log(- 'Gateway sync: %d paid-gated %s provider(s) excluded from desired set',- gatedOnPlatform,- platform,- );- } catch (err) {- desiredComplete = false;- log('Gateway sync: error loading providers for platform %s: %O', platform, err);- }- }-- return { desired, desiredComplete, gated };- }-- /**- * With a complete registry snapshot, disconnect paid-gated providers only- * when the connection still exists. When the snapshot is partial or- * unavailable, preserve access enforcement by falling back to disconnecting- * every gated id; that bounded set is independent of the desired-connection- * status fan-out this reconciliation avoids.- */- private async disconnectGatedConnections(- client: ReturnType<typeof getMessageGatewayClient>,- actual: ActualConnectionsSnapshot | null,- gated: Set<string>,- ): Promise<number> {- const connectionIds = actual?.complete- ? [...gated].filter((id) => actual.connections.has(id))- : [...gated];- let disconnected = 0;-- await pMap(- connectionIds,- async (id) => {- try {- await client.disconnect(id);- disconnected++;- log('Gateway sync: paid-gated connection %s disconnected', id);- } catch (err) {- log('Gateway sync: paid-gated disconnect failed %s: %O', id, err);- }- },- { concurrency: GATEWAY_SYNC_CONCURRENCY },- );-- return disconnected;- }-- /**- * 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`).- *- * Registered ids are the authoritative existence set, so a successful call- * produces a complete snapshot even when stats are unavailable. When only- * stats succeed, the partial snapshot can still drive safe stale cleanup,- * but desired ids missing from it are deferred rather than probed one by one.- * Returns null only when neither endpoint is available.- */- private async fetchActualConnections(- client: ReturnType<typeof getMessageGatewayClient>,- ): Promise<ActualConnectionsSnapshot | null> {- const connections = new Map<string, string | null>();- let statsAvailable = false;-- try {- const stats = await client.getStats();- statsAvailable = true;- 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);- }-- try {- const { ids } = await client.getRegisteredIds();- for (const id of ids) {- if (!connections.has(id)) connections.set(id, null);- }- return { complete: true, connections };- } catch (err) {- log('Gateway sync: registered-ids unavailable, using stats-only snapshot: %O', err);- }-- return statsAvailable ? { complete: false, connections } : null;- }-- /**- * 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>,- gated: Set<string>,- host: MessageGatewayHost,- hostsReadyToReceive: Set<MessageGatewayHost>,- drainedThisRound: Set<string>,- declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>,- ): Promise<number> {- const allStaleIds = [...actual.keys()].filter(- (id) => !desired.has(id) && !gated.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);-- // An enabled persistent-mode row that shows up in `actual` but not- // in `desired` is one of two things, and only one of them is stale.- const livePersistentRow =- row?.enabled &&- resolveConnectionMode(platformRegistry.getPlatform(row.platform), row.settings) !==- 'webhook';-- if (livePersistentRow) {- const owner = resolveMessageGatewayHost(row.platform);-- // TOCTOU: enabled (and connected) between the desired snapshot and- // the actual fetch. This row was queried after both, so trust it β- // leave it for the next round to classify with a fresh desired set.- if (owner === host) {- log('Gateway sync: %s enabled during sync, skipping stale disconnect', id);- return;- }-- // Routed to another host: this IS the cross-host move the stale- // pass exists to perform β but only once the destination can- // actually take over. Disconnecting into a host that will defer- // every connect would take the connection dark for the whole- // outage, so hold it here and retry next round.- if (!hostsReadyToReceive.has(owner)) {- log(- 'Gateway sync[%s]: %s belongs on %s host, which has no usable snapshot β deferring move',- host,- id,- owner,- );- return;- }-- // Routed somewhere that has told us it cannot serve this platform.- // Draining here would be worse than doing nothing: the connect- // meant to replace it gets rejected, so the connection ends up on- // neither host. Leave it running and let the misrouting be fixed.- if (this.hostRefusesPlatform(declaredPlatforms, owner, row.platform)) {- log(- 'Gateway sync[%s]: %s is routed to the %s host, which does not serve %s β refusing to drain',- host,- id,- owner,- row.platform,- );- return;- }- }-- await client.disconnect(id);- disconnected++;- // Releases the id for its new owner's connect pass this same round.- drainedThisRound.add(id);-- // 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: row.applicationId,- platform: row.platform,- status: BOT_RUNTIME_STATUSES.disconnected,- });- }- 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 },- );-- return disconnected;- }-async stop(): Promise<void> {const manager = getGatewayManager();if (!manager) return;@@ -1676,144 +288,16 @@ export class GatewayService {});}- /**- * Lazy-register a per-user messenger connection on the gateway and return- * the connectionId. Idempotent within the in-process LRU TTL β repeat calls- * skip the network round-trip.- *- * Returns null when:- * - the gateway is disabled (`MESSAGE_GATEWAY_ENABLED !== '1'`)- * - the installation store can't resolve credentials for the given key- * - the gateway connect call throws (best-effort: messenger typing is a- * UX nicety, never block the agent run)- *- * Slack token rotation is handled passively by the LRU TTL: when a stale- * cached entry expires, the next call re-resolves credentials via- * `resolveByKey` (which transparently refreshes Slack OAuth) and pushes the- * fresh token to the gateway via a fresh `connect`. The DO upserts on- * connectionId so this is non-disruptive.- */- async ensureUserMessengerConnected(params: {- installationKey: string;- platform: MessengerPlatform;- userId: string;- }): Promise<string | null> {- if (!this.useMessageGateway) return null;-- const { installationKey, platform, userId } = params;-- // Websocket-mode singleton platforms (Discord SystemBot today): the WS- // is registered by dc-center at `messenger:<platform>:singleton` and- // there is no per-user DO to register here. Route typing to the- // singleton connectionId directly β opening a per-user webhook DO would- // (a) be rejected by the gateway and (b) not be where `triggerTyping`- // can actually fire, since only the singleton WS holds the live socket.- //- // SystemBot's transport is fixed per platform (e.g. Slack SystemBot is- // webhook even though a per-agent bot-channel Slack provider may run- // Socket Mode/websocket), so it lives on the messenger definition, not- // the bot-channel one.- const connectionMode = messengerPlatformRegistry.getPlatform(platform)?.connectionMode;- if (connectionMode === 'websocket') {- return messengerConnectionIdForUser({ connectionMode, installationKey, userId });- }-- const connectionId = messengerConnectionIdForUser({ connectionMode, installationKey, userId });-- const now = Date.now();- const expireAt = userMessengerConnections.get(connectionId);- if (expireAt && expireAt > now) {- // Re-touch on hit so the LRU eviction order tracks recency.- userMessengerConnections.delete(connectionId);- userMessengerConnections.set(connectionId, expireAt);- return connectionId;- }-- const store = getInstallationStore(platform);- if (!store) {- log('ensureUserMessengerConnected: no installation store for platform=%s', platform);- return null;- }-- const creds = await store.resolveByKey(installationKey);- if (!creds?.botToken) {- log(- 'ensureUserMessengerConnected: missing creds for key=%s (user=%s)',- installationKey,- userId,- );- return null;- }-- try {- const client = getMessageGatewayClient(platform);- const isPolling = connectionMode === 'polling';- await client.connect({- applicationId: creds.applicationId,- // Messenger-owned connections never consume passive channel- // monitoring β the shared bot only reacts to DMs and explicit- // mentions, so the gateway may drop ordinary channel messages.- capabilities: { messageMonitoring: { enabled: false } },- connectionId,- // Webhook platforms only need an outbound typing surface. Polling- // platforms (WeChat) own a real per-user inbound lifecycle and must- // receive the complete QR-issued credential bundle.- connectionMode: isPolling ? 'polling' : 'webhook',- credentials: isPolling- ? {- baseUrl: creds.baseUrl,- botId: creds.botId,- botToken: creds.botToken,- webhookToken: gatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN,- }- : { botToken: creds.botToken },- platform,- userId,- webhookPath: isPolling ? `/api/agent/messenger/webhooks/${platform}` : '',- });-- // Evict-on-add: the iterator yields keys in insertion order, so the- // first key is the oldest entry.- if (userMessengerConnections.size >= USER_MESSENGER_CONN_LRU_CAPACITY) {- const oldest = userMessengerConnections.keys().next().value;- if (oldest !== undefined) userMessengerConnections.delete(oldest);- }- userMessengerConnections.set(connectionId, now + USER_MESSENGER_CONN_TTL_MS);-- log('ensureUserMessengerConnected: registered %s', connectionId);- return connectionId;- } catch (err) {- log('ensureUserMessengerConnected: connect failed for %s: %O', connectionId, err);- return null;- }+ listDesiredConnectionsForHost(host: MessageGatewayHost) {+ return desiredForHost.listDesiredConnectionsForHost(host);}- /**- * Stop a user-owned messenger connection during unlink or credential- * replacement. Cleanup is allowed while the gateway feature flag is off so- * a rollout rollback cannot strand a long-polling WeChat connection.- */- async disconnectUserMessenger(params: {- installationKey: string;- platform: MessengerPlatform;- userId: string;- }): Promise<void> {- const { installationKey, platform, userId } = params;- const connectionMode = messengerPlatformRegistry.getPlatform(platform)?.connectionMode;- if (connectionMode === 'websocket') return;-- const connectionId = messengerConnectionIdForUser({ connectionMode, installationKey, userId });- userMessengerConnections.delete(connectionId);-- const client = getMessageGatewayClient(platform);- if (!client.isConfigured) return;+ ensureUserMessengerConnected(params: UserMessengerConnectionParams) {+ return userMessenger.ensureUserMessengerConnected(params);+ }- try {- await client.disconnect(connectionId);- log('disconnectUserMessenger: disconnected %s', connectionId);- } catch (error) {- log('disconnectUserMessenger: failed for %s: %O', connectionId, error);- }+ disconnectUserMessenger(params: UserMessengerConnectionParams) {+ return userMessenger.disconnectUserMessenger(params);}// βββ External Message Gateway βββdiff --git a/apps/server/src/services/gateway/sync/connect.ts b/apps/server/src/services/gateway/sync/connect.tsnew file mode 100644index 00000000000..73a3357e1b4--- /dev/null+++ b/apps/server/src/services/gateway/sync/connect.ts@@ -0,0 +1,212 @@+/**+ * Reconcile phase 2: connect what is desired but missing on a host.+ */+import debug from 'debug';+import pMap from 'p-map';++import { buildBotProviderConnectConfig, mapGatewayStatusToRuntimeStatus } from '../gatewayMapping';+import { getMessageGatewayClientForHost, type MessageGatewayHost } from '../MessageGatewayClient';+import { updateBotRuntimeStatus } from '../runtimeStatus';+import { GATEWAY_SYNC_CONCURRENCY } from './constants';+import { hostDesiredSlice, hostRefusesPlatform } from './state';+import type { ActualConnectionsSnapshot, DesiredGatewayConnection, HostDrainCounts } from './types';++/**+ * Cap on registered-only wake-up connects per sync round. A registered-only id+ * (in the registry but pruned from live stats) is usually a parked or+ * self-waking dormant DO, but a stranded DO β alarm chain lost after a deploy+ * cancelled its in-flight alarm invocation β looks identical and sleeps+ * forever unless something wakes it. The `ensure` connect is that wake: parked+ * connections answer 409 and keep their park, healthy ones no-op. The cap+ * keeps a large parked backlog from turning every cron round into a fleet-wide+ * wake storm; the remainder is retried on later rounds.+ */+const GATEWAY_SYNC_REGISTERED_ONLY_WAKE_LIMIT = 50;++/**+ * Uniformly sample up to `limit` ids via a partial Fisher-Yates shuffle.+ * Stateless by design β the gateway cron runs in fresh serverless invocations,+ * so a persisted round-robin cursor would need external storage; uniform+ * sampling gives every candidate an expected candidates/limit-round latency+ * without any state.+ */+const sampleIds = (ids: string[], limit: number): Set<string> => {+ if (ids.length <= limit) return new Set(ids);+ const pool = [...ids];+ const picked = new Set<string>();+ for (let i = 0; i < limit; i++) {+ const j = i + Math.floor(Math.random() * (pool.length - i));+ [pool[i], pool[j]] = [pool[j], pool[i]];+ picked.add(pool[i]);+ }+ return picked;+};++const log = debug('lobe-server:service:gateway');++/**+ * Phase 2 for one host: `desired β actual β connect`. Every host has already+ * been drained by the time this runs.+ */+export async function connectHostConnections(params: {+ counts: HostDrainCounts;+ currentlyElsewhere: Set<string>;+ declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>;+ desired: Map<string, DesiredGatewayConnection>;+ drainedThisRound: Set<string>;+ host: MessageGatewayHost;+ snapshot: ActualConnectionsSnapshot | null;+}): Promise<void> {+ const {+ counts,+ currentlyElsewhere,+ declaredPlatforms,+ drainedThisRound,+ host,+ snapshot: actual,+ } = params;+ const client = getMessageGatewayClientForHost(host);+ const desired = hostDesiredSlice(params.desired, host);++ let connected = 0;+ let deferred = 0;+ let skipped = 0;+ let failed = 0;++ // Registered-only wake candidates are SAMPLED, not taken head-first: the+ // desired map iterates in a stable order, and parked connections (409,+ // stay registered-only until their 7d expiry) would otherwise burn the+ // whole cap on the same prefix every round, starving stranded DOs that+ // sort after position N. Uniform sampling reaches every candidate within+ // an expected candidates/limit rounds with no persisted cursor.+ const registeredOnlyCandidates = [...desired.values()]+ .map(({ provider }) => provider.id)+ .filter((id) => (actual?.connections.has(id) ?? false) && actual?.connections.get(id) === null);+ const registeredOnlyWakeIds = sampleIds(+ registeredOnlyCandidates,+ GATEWAY_SYNC_REGISTERED_ONLY_WAKE_LIMIT,+ );+ const registeredOnlyDeferred = registeredOnlyCandidates.length - registeredOnlyWakeIds.size;+ let registeredOnlyWakes = 0;++ await pMap(+ desired.values(),+ async ({ connectionMode, platform, provider }) => {+ try {+ // Told us it cannot serve this platform. The connect would be+ // rejected anyway; skipping keeps one clear line in the log instead+ // of an error per connection, and pairs with the stale pass, which+ // leaves these running wherever they already are.+ if (hostRefusesPlatform(declaredPlatforms, host, platform)) {+ skipped++;+ return;+ }++ // 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;+ }++ // Mid-move and STILL not drained, even though every host's drain+ // phase has already run β so it is over this round's disconnect cap+ // or its disconnect failed. Connecting now would leave the provider+ // live on both gateways, double-delivering until a later round+ // catches up.+ if (currentlyElsewhere.has(provider.id) && !drainedThisRound.has(provider.id)) {+ deferred++;+ log(+ 'Gateway sync[%s]: %s not yet drained from its previous host, deferring connect',+ host,+ provider.id,+ );+ return;+ }++ // Registered ids are the gateway's authoritative existence set. Use+ // the status already present in live stats to recover an explicitly+ // disconnected connection. Registered-only ids (status null β pruned+ // from stats) get a capped ensure-connect wake instead of a skip:+ // see GATEWAY_SYNC_REGISTERED_ONLY_WAKE_LIMIT. Never probe per-DO+ // status here.+ const exists = actual?.connections.has(provider.id) ?? false;+ const snapshotStatus = actual?.connections.get(provider.id);+ if (exists && snapshotStatus !== 'disconnected') {+ if (snapshotStatus !== null) {+ skipped++;+ log('Gateway sync: %s already registered, skipping', provider.id);+ return;+ }+ if (!registeredOnlyWakeIds.has(provider.id)) {+ log('Gateway sync: %s registered-only, not sampled this round, deferring', provider.id);+ return;+ }+ registeredOnlyWakes++;+ log('Gateway sync: %s registered-only, ensure-waking', provider.id);+ }++ // Without a complete registry snapshot, absence from live stats does+ // not prove the connection is missing. Fail safe and retry next round+ // instead of degrading to an unbounded per-DO status probe fan-out.+ if (!exists && !actual?.complete) {+ deferred++;+ log('Gateway sync: %s absent from incomplete snapshot, deferring', provider.id);+ return;+ }++ if (snapshotStatus === 'disconnected') {+ log('Gateway sync: %s reported disconnected in stats, reconnecting', provider.id);+ }++ // `ensure` marks this as a reconcile connect: the gateway preserves+ // its park/backoff state when the config is unchanged (a parked+ // connection answers 409 β counted as failed below), instead of+ // letting every sync round reset stuck connections to fast retry.+ const result = await client.connect(+ buildBotProviderConnectConfig({ connectionMode, platform, provider }),+ { ensure: true },+ );++ // Gateway returns "connecting" for async persistent connections+ // (e.g. Discord WebSocket), "connected" for sync webhook-mode. An+ // `ensure` reconcile can also legitimately return "dormant" (the DO is+ // sparse-polling and won't send a correcting callback), so map through+ // the shared helper instead of collapsing every non-connected result+ // to "starting" β otherwise a dormant connection is persisted as+ // starting and never corrected.+ await updateBotRuntimeStatus({+ applicationId: provider.applicationId,+ platform,+ status: mapGatewayStatusToRuntimeStatus(result.status),+ });++ 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[%s]: desired=%d actual=%s snapshotComplete=%s connected=%d skipped=%d deferred=%d gated=%d gatedDisconnected=%d stale=%d failed=%d registeredOnlyWakes=%d registeredOnlyDeferred=%d',+ host,+ desired.size,+ actual ? actual.connections.size : 'unavailable',+ actual?.complete ?? false,+ connected,+ skipped,+ deferred,+ counts.gatedSize,+ counts.gatedDisconnected,+ counts.stale,+ failed,+ registeredOnlyWakes,+ registeredOnlyDeferred,+ );+}diff --git a/apps/server/src/services/gateway/sync/constants.ts b/apps/server/src/services/gateway/sync/constants.tsnew file mode 100644index 00000000000..3b68b3ba6b5--- /dev/null+++ b/apps/server/src/services/gateway/sync/constants.ts@@ -0,0 +1,16 @@+/**+ * 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.+ */+export 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.+ */+export const GATEWAY_SYNC_STALE_DISCONNECT_LIMIT = 50;diff --git a/apps/server/src/services/gateway/sync/desiredForHost.ts b/apps/server/src/services/gateway/sync/desiredForHost.tsnew file mode 100644index 00000000000..7d5d4d0251e--- /dev/null+++ b/apps/server/src/services/gateway/sync/desiredForHost.ts@@ -0,0 +1,213 @@+/**+ * Restart recovery, pull side: the connect payloads one host should hold.+ */+import debug from 'debug';++import { getServerDB } from '@/database/core/db-adaptor';+import {+ type DecryptedMessengerAccountLink,+ MessengerAccountLinkModel,+} from '@/database/models/messengerAccountLink';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { messengerConnectionIdForUser } from '@/server/services/messenger/installations';+import { messengerPlatformRegistry } from '@/server/services/messenger/platforms';++import {+ buildBotProviderConnectConfig,+ buildMessengerPollingConnectConfig,+} from '../gatewayMapping';+import {+ getConfiguredMessageGatewayHosts,+ getMessageGatewayClientForHost,+ type MessageGatewayConnectionConfig,+ type MessageGatewayHost,+ resolveMessageGatewayHost,+} from '../MessageGatewayClient';+import {+ buildDesiredConnections,+ fetchActualConnections,+ hostDesiredSlice,+ hostRefusesPlatform,+} from './state';++const log = debug('lobe-server:service:gateway');++/**+ * The connect payloads one host should currently be holding.+ *+ * This is the read half of restart recovery: a gateway that just came back+ * up holds nothing, asks for this list, and builds it itself. Nothing here+ * calls a gateway, so it wakes no connection and can be retried freely β+ * the one write it does make is the runtime status of a paid-gated+ * provider, which `buildDesiredConnections` records on the way past and+ * which is true no matter who asked.+ *+ * `complete: false` means the desired set could not be computed in full (a+ * platform's rows failed to load, key vault unavailable). The caller should+ * apply what it got and ask again rather than treat a short list as the+ * whole truth. Refusing to answer at all would be worse: it leaves the+ * gateway holding nothing for the length of an unrelated outage.+ *+ * Rows that can never connect β credentials missing or undecryptable β are+ * counted into `excluded` and left out. They must not fail the call: a+ * single unreadable row would otherwise keep a whole gateway empty forever.+ *+ * Connections another host still holds are withheld and counted into+ * `deferred`. Routing alone does not make a connection safe to build: right+ * after a platform is routed here, the previous host is still polling it,+ * and handing it over before that host is drained double-delivers every+ * message until a later reconcile catches up. The periodic reconcile owns+ * the hand-off; this call only refuses to race it.+ */+export async function listDesiredConnectionsForHost(host: MessageGatewayHost): Promise<{+ complete: boolean;+ connections: { config: MessageGatewayConnectionConfig; ensure: true }[];+ deferred: number;+ excluded: number;+}> {+ const serverDB = await getServerDB();+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();++ const connections: { config: MessageGatewayConnectionConfig; ensure: true }[] = [];+ let excluded = 0;+ let deferred = 0;++ // What every OTHER host still holds. Read-only, and only two admin+ // requests per host β they reach the gateway's own registry, not the+ // individual connections, so asking wakes nothing.+ //+ // A host whose admin surface is unreachable is treated as holding+ // nothing, deliberately, and matching the reconcile's own rule: a+ // steady-state deployment has no connections on the wrong host at all, so+ // blocking every restart recovery on an unrelated host's outage costs far+ // more availability than the duplicate window it would avoid β and that+ // window only opens if the outage overlaps an actual migration.+ // What this host says it can serve. Routing a platform here does not mean+ // it can run it, and handing over credentials for a connection it will+ // reject is handing them over for nothing. The reconcile already refuses+ // to move such a platform; this refuses to arm it.+ const declared = await getMessageGatewayClientForHost(host).getCapabilities();+ const declaredPlatforms = new Map<MessageGatewayHost, Set<string> | null>([+ [host, declared ? new Set(declared.platforms ?? []) : null],+ ]);++ const elsewhere = new Set<string>();+ let peersProven = true;+ for (const other of getConfiguredMessageGatewayHosts()) {+ if (other === host) continue;+ const snapshot = await fetchActualConnections(getMessageGatewayClientForHost(other));++ // Absence is only evidence when the view was complete. A snapshot we+ // could not fetch shows nothing, and a stats-only one omits dormant+ // registrations β in both cases an id missing from it says nothing about+ // whether that host released it, so nothing here can be handed over.+ // Marking the answer incomplete does not substitute: the caller applies+ // what it receives and only then asks again, so a flag arrives after the+ // duplicate it was supposed to prevent.+ if (!snapshot?.complete) {+ peersProven = false;+ log(+ 'Gateway pull[%s]: %s host view is %s, cannot prove it released anything',+ host,+ other,+ snapshot ? 'incomplete' : 'unavailable',+ );+ }++ snapshot?.connections.forEach((_status, id) => elsewhere.add(id));+ }++ // Paid-gated providers never enter the desired set, so nothing here can+ // hand back a connection the next reconcile round would tear down again.+ const { desired, desiredComplete } = await buildDesiredConnections(serverDB, gateKeeper, [host]);+ let complete = desiredComplete;++ for (const entry of hostDesiredSlice(desired, host).values()) {+ if (hostRefusesPlatform(declaredPlatforms, host, entry.platform)) {+ excluded++;+ continue;+ }+ if (Object.keys(entry.provider.credentials).length === 0) {+ excluded++;+ continue;+ }+ if (!peersProven || elsewhere.has(entry.provider.id)) {+ deferred++;+ log(+ 'Gateway pull[%s]: %s not proven released elsewhere, withholding',+ host,+ entry.provider.id,+ );+ continue;+ }+ connections.push({ config: buildBotProviderConnectConfig(entry), ensure: true });+ }++ for (const definition of messengerPlatformRegistry.listPlatforms()) {+ if (definition.connectionMode !== 'polling') continue;+ const platform = definition.id;+ if (resolveMessageGatewayHost(platform) !== host) continue;+ if (hostRefusesPlatform(declaredPlatforms, host, platform)) {+ log('Gateway pull[%s]: host does not serve %s, withholding its credentials', host, platform);+ continue;+ }++ let links: DecryptedMessengerAccountLink[];+ try {+ links = await MessengerAccountLinkModel.findAllByPlatformWithCredentials(+ serverDB,+ platform,+ gateKeeper,+ );+ } catch (err) {+ // Same rule as the desired set: a platform we could not read makes the+ // answer incomplete, not empty.+ complete = false;+ log('Gateway pull[%s]: messenger link listing failed for %s: %O', host, platform, err);+ continue;+ }++ for (const link of links) {+ const credentials = link.credentials as { botToken?: string };+ const connectionId = messengerConnectionIdForUser({+ connectionMode: 'polling',+ installationKey: `${platform}:${link.tenantId}`,+ userId: link.userId,+ });+ if (!link.applicationId || !credentials.botToken) {+ excluded++;+ continue;+ }+ if (!peersProven || elsewhere.has(connectionId)) {+ deferred++;+ log('Gateway pull[%s]: %s not proven released elsewhere, withholding', host, connectionId);+ continue;+ }+ connections.push({+ config: buildMessengerPollingConnectConfig({ connectionId, link, platform }),+ ensure: true,+ });+ }+ }++ // Audit surface: this is the one place that hands out a host's whole+ // credential set, and it doubles as the signal that the host restarted.+ // Withheld entries make this a partial answer, so the caller keeps asking+ // instead of settling for the set it got. It will run out of attempts long+ // before a hand-off finishes β that is fine: finishing one is the periodic+ // reconcile's job, not this call's. Restart recovery is an optimisation+ // over that reconcile, so when it cannot be done safely the right move is+ // not to do it.+ if (deferred > 0) complete = false;++ log(+ 'Gateway pull[%s]: %d connection(s), excluded=%d, deferred=%d, complete=%s',+ host,+ connections.length,+ excluded,+ deferred,+ complete,+ );++ return { complete, connections, deferred, excluded };+}diff --git a/apps/server/src/services/gateway/sync/drain.ts b/apps/server/src/services/gateway/sync/drain.tsnew file mode 100644index 00000000000..dfdf27839f2--- /dev/null+++ b/apps/server/src/services/gateway/sync/drain.ts@@ -0,0 +1,245 @@+/**+ * Reconcile phase 1: disconnect paid-gated and stale connections.+ */+import debug from 'debug';+import pMap from 'p-map';++import type { getServerDB } from '@/database/core/db-adaptor';+import { AgentBotProviderModel } from '@/database/models/agentBotProvider';+import { isMessengerConnectionId } from '@/server/services/messenger/installations';++import { platformRegistry, resolveConnectionMode } from '../../bot/platforms';+import {+ type getMessageGatewayClient,+ getMessageGatewayClientForHost,+ type MessageGatewayHost,+ resolveMessageGatewayHost,+} from '../MessageGatewayClient';+import { BOT_RUNTIME_STATUSES, updateBotRuntimeStatus } from '../runtimeStatus';+import { GATEWAY_SYNC_CONCURRENCY, GATEWAY_SYNC_STALE_DISCONNECT_LIMIT } from './constants';+import { hostDesiredSlice, hostGatedSlice, hostRefusesPlatform } from './state';+import type { ActualConnectionsSnapshot, DesiredGatewayConnection, HostDrainCounts } from './types';++const log = debug('lobe-server:service:gateway');++/**+ * Phase 1 for one host: remove what should no longer be there (paid-gated+ * connections, then stale ones). Runs for every host before any host's+ * connect pass, so a connection is always gone from its old owner before it+ * is built on its new one.+ */+export async function drainHostConnections(params: {+ declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>;+ desired: Map<string, DesiredGatewayConnection>;+ desiredComplete: boolean;+ drainedThisRound: Set<string>;+ gated: Map<string, string>;+ host: MessageGatewayHost;+ hostsReadyToReceive: Set<MessageGatewayHost>;+ serverDB: Awaited<ReturnType<typeof getServerDB>>;+ snapshot: ActualConnectionsSnapshot | null;+}): Promise<HostDrainCounts> {+ const {+ declaredPlatforms,+ desiredComplete,+ drainedThisRound,+ host,+ hostsReadyToReceive,+ serverDB,+ snapshot: actual,+ } = params;+ const client = getMessageGatewayClientForHost(host);+ const desired = hostDesiredSlice(params.desired, host);+ const gated = hostGatedSlice(params.gated, host);++ const gatedDisconnected = await disconnectGatedConnections(client, actual, gated);++ // 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 disconnectStaleConnections(+ client,+ serverDB,+ actual.connections,+ desired,+ gated,+ host,+ hostsReadyToReceive,+ drainedThisRound,+ declaredPlatforms,+ );+ } else if (actual) {+ log('Gateway sync: desired set incomplete, skipping stale-connection cleanup this round');+ }++ return { gatedDisconnected, gatedSize: gated.size, stale };+}++/**+ * With a complete registry snapshot, disconnect paid-gated providers only+ * when the connection still exists. When the snapshot is partial or+ * unavailable, preserve access enforcement by falling back to disconnecting+ * every gated id; that bounded set is independent of the desired-connection+ * status fan-out this reconciliation avoids.+ */+export async function disconnectGatedConnections(+ client: ReturnType<typeof getMessageGatewayClient>,+ actual: ActualConnectionsSnapshot | null,+ gated: Set<string>,+): Promise<number> {+ const connectionIds = actual?.complete+ ? [...gated].filter((id) => actual.connections.has(id))+ : [...gated];+ let disconnected = 0;++ await pMap(+ connectionIds,+ async (id) => {+ try {+ await client.disconnect(id);+ disconnected++;+ log('Gateway sync: paid-gated connection %s disconnected', id);+ } catch (err) {+ log('Gateway sync: paid-gated disconnect failed %s: %O', id, err);+ }+ },+ { concurrency: GATEWAY_SYNC_CONCURRENCY },+ );++ return disconnected;+}++/**+ * 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.+ */+export async function disconnectStaleConnections(+ client: ReturnType<typeof getMessageGatewayClient>,+ serverDB: Awaited<ReturnType<typeof getServerDB>>,+ actual: Map<string, string | null>,+ desired: Map<string, DesiredGatewayConnection>,+ gated: Set<string>,+ host: MessageGatewayHost,+ hostsReadyToReceive: Set<MessageGatewayHost>,+ drainedThisRound: Set<string>,+ declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>,+): Promise<number> {+ const allStaleIds = [...actual.keys()].filter(+ (id) => !desired.has(id) && !gated.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);++ // An enabled persistent-mode row that shows up in `actual` but not+ // in `desired` is one of two things, and only one of them is stale.+ const livePersistentRow =+ row?.enabled &&+ resolveConnectionMode(platformRegistry.getPlatform(row.platform), row.settings) !==+ 'webhook';++ if (livePersistentRow) {+ const owner = resolveMessageGatewayHost(row.platform);++ // TOCTOU: enabled (and connected) between the desired snapshot and+ // the actual fetch. This row was queried after both, so trust it β+ // leave it for the next round to classify with a fresh desired set.+ if (owner === host) {+ log('Gateway sync: %s enabled during sync, skipping stale disconnect', id);+ return;+ }++ // Routed to another host: this IS the cross-host move the stale+ // pass exists to perform β but only once the destination can+ // actually take over. Disconnecting into a host that will defer+ // every connect would take the connection dark for the whole+ // outage, so hold it here and retry next round.+ if (!hostsReadyToReceive.has(owner)) {+ log(+ 'Gateway sync[%s]: %s belongs on %s host, which has no usable snapshot β deferring move',+ host,+ id,+ owner,+ );+ return;+ }++ // Routed somewhere that has told us it cannot serve this platform.+ // Draining here would be worse than doing nothing: the connect+ // meant to replace it gets rejected, so the connection ends up on+ // neither host. Leave it running and let the misrouting be fixed.+ if (hostRefusesPlatform(declaredPlatforms, owner, row.platform)) {+ log(+ 'Gateway sync[%s]: %s is routed to the %s host, which does not serve %s β refusing to drain',+ host,+ id,+ owner,+ row.platform,+ );+ return;+ }+ }++ await client.disconnect(id);+ disconnected++;+ // Releases the id for its new owner's connect pass this same round.+ drainedThisRound.add(id);++ // 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: row.applicationId,+ platform: row.platform,+ status: BOT_RUNTIME_STATUSES.disconnected,+ });+ }+ 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 },+ );++ return disconnected;+}diff --git a/apps/server/src/services/gateway/sync/index.ts b/apps/server/src/services/gateway/sync/index.tsnew file mode 100644index 00000000000..4d3d86e6ccb--- /dev/null+++ b/apps/server/src/services/gateway/sync/index.ts@@ -0,0 +1,174 @@+/**+ * Periodic reconcile of the external message gateway(s) against the database.+ */+import debug from 'debug';++import { getServerDB } from '@/database/core/db-adaptor';+import { gatewayEnv } from '@/envs/gateway';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { messengerPlatformRegistry } from '@/server/services/messenger/platforms';++import { platformRegistry } from '../../bot/platforms';+import {+ getConfiguredMessageGatewayHosts,+ getMessageGatewayClientForHost,+ type MessageGatewayHost,+ resolveMessageGatewayHost,+} from '../MessageGatewayClient';+import { connectHostConnections } from './connect';+import { drainHostConnections } from './drain';+import { syncMessengerPollingConnections } from './messengerPolling';+import { buildDesiredConnections, fetchActualConnections } from './state';+import type { ActualConnectionsSnapshot, HostDrainCounts } from './types';++const log = debug('lobe-server:service:gateway');++/**+ * 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.+ */+export async function syncGatewayConnections(): Promise<void> {+ const startedAt = Date.now();+ const serverDB = await getServerDB();+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();++ // Each configured host gets its own desired slice and its own actual+ // snapshot, then runs the full diff independently. Cross-host moves fall+ // out of the partition: a platform routed away from a host leaves its ids+ // absent from that host's desired slice β the stale pass disconnects them+ // there while the new host's connect pass builds them up.+ const hosts = getConfiguredMessageGatewayHosts();++ // A platform name nothing recognises is a typo, and its only visible+ // effect is that the migration silently does not happen β the name simply+ // never matches, so everything stays on the default host. Say so once per+ // round instead of leaving someone to wonder why the flip did nothing.+ const routedNames = (gatewayEnv.MESSAGE_GATEWAY_NODE_PLATFORMS ?? '')+ .split(',')+ .map((entry) => entry.trim())+ .filter(Boolean);+ if (routedNames.length > 0) {+ const known = new Set([+ ...platformRegistry.listPlatforms().map((definition) => definition.id),+ ...messengerPlatformRegistry.listPlatforms().map((definition) => definition.id),+ ]);+ const unknown = routedNames.filter((name) => !known.has(name));+ if (unknown.length > 0) {+ log(+ 'Gateway sync: MESSAGE_GATEWAY_NODE_PLATFORMS names %o, which match no known platform β those entries do nothing',+ unknown,+ );+ }+ }++ // What each host says it can serve. Routing a platform to a host it cannot+ // serve is otherwise an outage, not a no-op: the stale pass drains the+ // connections off their old host, and the connect that should replace them+ // is rejected β so they end up nowhere. One request per host per round.+ const declaredPlatforms = new Map<MessageGatewayHost, Set<string> | null>();+ for (const host of hosts) {+ const capabilities = await getMessageGatewayClientForHost(host).getCapabilities();+ declaredPlatforms.set(host, capabilities ? new Set(capabilities.platforms ?? []) : null);+ }++ const { desired, desiredComplete, gated } = await buildDesiredConnections(+ serverDB,+ gateKeeper,+ hosts,+ );++ const snapshots = new Map<MessageGatewayHost, ActualConnectionsSnapshot | null>();+ for (const host of hosts) {+ snapshots.set(host, await fetchActualConnections(getMessageGatewayClientForHost(host)));+ }++ // A cross-host move must not tear the source down before the destination+ // can take over. A host whose snapshot is missing or incomplete defers+ // every connect for an id it cannot see (absence doesn't prove absence),+ // so disconnecting there first would take the platform dark until some+ // later round. Only hosts with a complete snapshot are safe destinations.+ const hostsReadyToReceive = new Set(+ hosts.filter((host) => snapshots.get(host)?.complete === true),+ );++ // Ids a snapshot shows on a host that no longer owns them β i.e. mid-move.+ // Draining them is capped per round, so without this the destination's+ // connect pass would happily build up every id the source pass had no+ // budget to remove, and the overflow would run on both hosts at once.+ const currentlyElsewhere = new Set<string>();+ for (const [host, snapshot] of snapshots) {+ if (!snapshot) continue;+ for (const id of snapshot.connections.keys()) {+ const entry = desired.get(id);+ if (entry && resolveMessageGatewayHost(entry.platform) !== host) currentlyElsewhere.add(id);+ }+ }+ // Filled in by each host's stale pass as it actually removes an id, which+ // is what releases that id for connecting on its new owner.+ const drainedThisRound = new Set<string>();++ // Two phases across ALL hosts rather than a full sync per host: every+ // drain completes before any build-up. Interleaving them makes correctness+ // depend on the order `hosts` happens to be in β with `['default','node']`+ // a nodeβdefault rollback would run the destination's connect pass first+ // (deferring everything, since nothing is drained yet), then drain the+ // source, and never revisit the destination, leaving every migrated bot+ // down for a whole round. Splitting the phases makes the ordering+ // structural instead of emergent, in both directions.+ const drainCounts = new Map<MessageGatewayHost, HostDrainCounts>();+ for (const host of hosts) {+ drainCounts.set(+ host,+ await drainHostConnections({+ declaredPlatforms,+ desired,+ desiredComplete,+ drainedThisRound,+ gated,+ host,+ hostsReadyToReceive,+ serverDB,+ snapshot: snapshots.get(host) ?? null,+ }),+ );+ }++ for (const host of hosts) {+ await connectHostConnections({+ counts: drainCounts.get(host) ?? { gatedDisconnected: 0, gatedSize: 0, stale: 0 },+ currentlyElsewhere,+ declaredPlatforms,+ desired,+ drainedThisRound,+ host,+ snapshot: snapshots.get(host) ?? null,+ });+ }++ await syncMessengerPollingConnections(+ serverDB,+ gateKeeper,+ snapshots,+ hostsReadyToReceive,+ declaredPlatforms,+ );++ log(+ 'Gateway sync complete in %dms across %d host(s): desired=%d gated=%d',+ Date.now() - startedAt,+ hosts.length,+ desired.size,+ gated.size,+ );+}diff --git a/apps/server/src/services/gateway/sync/messengerPolling.ts b/apps/server/src/services/gateway/sync/messengerPolling.tsnew file mode 100644index 00000000000..31ee2d6f71c--- /dev/null+++ b/apps/server/src/services/gateway/sync/messengerPolling.ts@@ -0,0 +1,290 @@+/**+ * Reconcile of per-user polling messenger connections across gateway hosts.+ */+import debug from 'debug';+import pMap from 'p-map';++import type { getServerDB } from '@/database/core/db-adaptor';+import {+ type DecryptedMessengerAccountLink,+ MessengerAccountLinkModel,+} from '@/database/models/messengerAccountLink';+import type { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { messengerConnectionIdForUser } from '@/server/services/messenger/installations';+import { messengerPlatformRegistry } from '@/server/services/messenger/platforms';++import { buildMessengerPollingConnectConfig } from '../gatewayMapping';+import {+ getMessageGatewayClientForHost,+ type MessageGatewayHost,+ resolveMessageGatewayHost,+} from '../MessageGatewayClient';+import { GATEWAY_SYNC_CONCURRENCY, GATEWAY_SYNC_STALE_DISCONNECT_LIMIT } from './constants';+import { hostRefusesPlatform } from './state';+import type { ActualConnectionsSnapshot } from './types';++const log = debug('lobe-server:service:gateway');++/**+ * Reconcile per-user polling messenger connections (WeChat today) onto the+ * gateway host that owns their platform.+ *+ * Bot-provider connections are covered by the desired/actual diff above,+ * but messenger-owned ids (`messenger:<platform>:β¦`) were historically+ * excluded from reconciliation: on the default gateway they are durable+ * Durable Objects, lazily created at link time. Two things break that+ * model:+ *+ * - the Node gateway keeps connections in process memory, so without a+ * reconcile every redeploy would silently stop all polling until each+ * user re-linked;+ * - moving a platform between hosts needs the old host's connections torn+ * down and the new host's rebuilt, link by link.+ *+ * Webhook typing shards and websocket singletons stay excluded β they are+ * lazily managed (`ensureUserMessengerConnected`) and harmless to lose.+ */+export async function syncMessengerPollingConnections(+ serverDB: Awaited<ReturnType<typeof getServerDB>>,+ gateKeeper: KeyVaultsGateKeeper,+ snapshots: Map<MessageGatewayHost, ActualConnectionsSnapshot | null>,+ hostsReadyToReceive: Set<MessageGatewayHost>,+ declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>,+): Promise<void> {+ for (const definition of messengerPlatformRegistry.listPlatforms()) {+ if (definition.connectionMode !== 'polling') continue;+ const platform = definition.id;+ const host = resolveMessageGatewayHost(platform);+ const client = getMessageGatewayClientForHost(host);+ if (!client.isEnabled) continue;++ // Routed to a host that says it cannot serve this platform. Skipping the+ // whole platform leaves every connection where it already runs β the+ // teardown below would otherwise strip them from their current host for+ // a destination that will reject them.+ if (hostRefusesPlatform(declaredPlatforms, host, platform)) {+ log(+ 'Gateway sync[%s]: host does not serve %s β leaving its connections where they are',+ host,+ platform,+ );+ continue;+ }++ const prefix = `messenger:${platform}:`;++ // Load the links BEFORE touching any host. A migration that drains the+ // old host and only then discovers it cannot read the account links+ // leaves those users offline until a later round β so the lookup that+ // can fail runs while a failure is still free.+ let links: DecryptedMessengerAccountLink[];+ try {+ links = await MessengerAccountLinkModel.findAllByPlatformWithCredentials(+ serverDB,+ platform,+ gateKeeper,+ );+ } catch (err) {+ log('Gateway sync[%s]: messenger link listing failed for %s: %O', host, platform, err);+ continue;+ }++ // Classify BEFORE draining anything: the teardown below has to know+ // which ids it must not touch, and a link is only safe to move once we+ // know we can rebuild it on the other side.+ const desired = new Map<string, DecryptedMessengerAccountLink>();+ // Linked accounts we cannot connect but must not treat as unlinked.+ const unusable = new Set<string>();+ for (const link of links) {+ const credentials = link.credentials as { botToken?: string };+ const connectionId = messengerConnectionIdForUser({+ connectionMode: 'polling',+ installationKey: `${platform}:${link.tenantId}`,+ userId: link.userId,+ });+ // A link whose credentials fail to decrypt comes back with an empty+ // object, indistinguishable here from one that never had a token.+ // Either way a connect can only fail β but the account IS still+ // linked, so it must stay out of the stale pass: otherwise a+ // key-vault mismatch reads as "everyone unlinked" and tears down+ // every healthy poller in a single round.+ if (!link.applicationId || !credentials.botToken) {+ unusable.add(connectionId);+ continue;+ }+ desired.set(connectionId, link);+ }++ // Ids this round leaves running on a host that no longer owns them β+ // past the per-round cap, failed to disconnect, or not attempted at all.+ // The connect pass must skip these: connecting one while it still polls+ // elsewhere is exactly the double-delivery this pass exists to prevent.+ const stillElsewhere = new Set<string>();++ // Tear down this platform's per-user connections on every other host β+ // a polling platform hosted twice double-delivers every message. Runs+ // before the owning host's connect pass for the same reason+ // (disconnect-then-connect ordering during a host migration).+ for (const [otherHost, otherSnapshot] of snapshots) {+ if (otherHost === host) continue;++ // A host we cannot see cannot be drained, and its admin surface being+ // down does not mean its pollers stopped. Deliberate trade-off: we+ // still connect on the owning host rather than block on it, because a+ // steady-state deployment has no strays here at all, and holding every+ // reconcile hostage to an unrelated host's admin outage costs far more+ // availability than the duplicate-delivery window it would avoid β+ // which only opens if that outage overlaps an actual migration.+ if (!otherSnapshot) {+ log(+ 'Gateway sync[%s]: %s host snapshot unavailable β cannot confirm %s is drained there',+ host,+ otherHost,+ platform,+ );+ continue;+ }++ // An unusable link cannot be rebuilt on the owning host, so moving it+ // is a one-way trip to offline. Leave its existing connection alone β+ // wherever it currently runs, it is still serving that user.+ const strayIds = [...otherSnapshot.connections.keys()].filter(+ (id) => id.startsWith(prefix) && !unusable.has(id),+ );+ if (strayIds.length === 0) continue;++ // Same rule as the bot-provider stale pass: never strip the source+ // while the destination cannot take over, or the platform goes dark+ // for the length of the destination's outage.+ if (!hostsReadyToReceive.has(host)) {+ strayIds.forEach((id) => stillElsewhere.add(id));+ log(+ 'Gateway sync[%s]: %s host has no usable snapshot β leaving %d %s connection(s) on %s host',+ host,+ host,+ strayIds.length,+ platform,+ otherHost,+ );+ continue;+ }++ const batch = strayIds.slice(0, GATEWAY_SYNC_STALE_DISCONNECT_LIMIT);+ strayIds.slice(GATEWAY_SYNC_STALE_DISCONNECT_LIMIT).forEach((id) => stillElsewhere.add(id));+ if (batch.length < strayIds.length) {+ log(+ 'Gateway sync[%s]: capping cross-host %s migration to %d of %d this round',+ host,+ platform,+ batch.length,+ strayIds.length,+ );+ }++ const otherClient = getMessageGatewayClientForHost(otherHost);+ await pMap(+ batch,+ async (id) => {+ try {+ await otherClient.disconnect(id);+ log('Gateway sync[%s]: moved %s off %s host', host, id, otherHost);+ } catch (err) {+ stillElsewhere.add(id);+ log('Gateway sync[%s]: cross-host disconnect failed %s: %O', host, id, err);+ }+ },+ { concurrency: GATEWAY_SYNC_CONCURRENCY },+ );+ }++ const snapshot = snapshots.get(host) ?? null;++ let connected = 0;+ let skipped = 0;+ let failed = 0;++ await pMap(+ [...desired],+ async ([connectionId, link]) => {+ // Without any snapshot we can't tell existing from missing β blind+ // reconnects would churn healthy pollers, so wait for a round with+ // a working admin surface.+ if (!snapshot) {+ skipped++;+ return;+ }+ // Still polling on a host that no longer owns it (past this round's+ // migration cap, or its disconnect failed). Connecting here too+ // would double-deliver every inbound message until the next round+ // finishes the move.+ if (stillElsewhere.has(connectionId)) {+ skipped++;+ log(+ 'Gateway sync[%s]: %s still live on another host, deferring connect',+ host,+ connectionId,+ );+ return;+ }+ const exists = snapshot.connections.has(connectionId);+ const status = snapshot.connections.get(connectionId);+ // Live and healthy β nothing to do. Registered-only (null) gets an+ // ensure-connect wake (parked connections answer 409 and keep their+ // park); missing from a complete snapshot gets a real connect.+ if (exists && status !== null && status !== 'disconnected') {+ skipped++;+ return;+ }+ if (!exists && !snapshot.complete) {+ skipped++;+ return;+ }+ try {+ await client.connect(+ buildMessengerPollingConnectConfig({ connectionId, link, platform }),+ { ensure: true },+ );+ connected++;+ } catch (err) {+ failed++;+ log('Gateway sync[%s]: messenger connect failed %s: %O', host, connectionId, err);+ }+ },+ { concurrency: GATEWAY_SYNC_CONCURRENCY },+ );++ // Unlinked accounts whose connection still exists on the owning host.+ // `unusable` ids are linked but unconnectable β they belong to neither+ // set and must survive this pass untouched.+ let stale = 0;+ if (snapshot?.complete) {+ const staleIds = [...snapshot.connections.keys()]+ .filter((id) => id.startsWith(prefix) && !desired.has(id) && !unusable.has(id))+ .slice(0, GATEWAY_SYNC_STALE_DISCONNECT_LIMIT);+ await pMap(+ staleIds,+ async (id) => {+ try {+ await client.disconnect(id);+ stale++;+ log('Gateway sync[%s]: disconnected unlinked messenger connection %s', host, id);+ } catch (err) {+ log('Gateway sync[%s]: messenger stale disconnect failed %s: %O', host, id, err);+ }+ },+ { concurrency: GATEWAY_SYNC_CONCURRENCY },+ );+ }++ log(+ 'Gateway sync[%s]: messenger %s links=%d connected=%d skipped=%d stale=%d failed=%d',+ host,+ platform,+ desired.size,+ connected,+ skipped,+ stale,+ failed,+ );+ }+}diff --git a/apps/server/src/services/gateway/sync/state.ts b/apps/server/src/services/gateway/sync/state.tsnew file mode 100644index 00000000000..30171a1d809--- /dev/null+++ b/apps/server/src/services/gateway/sync/state.ts@@ -0,0 +1,204 @@+/**+ * Desired and actual connection state for the reconcile: what the database+ * says should exist, what each gateway host holds, and per-host slices.+ */+import debug from 'debug';++import {+ getBotFeatureBlockedMessage,+ isBotFeatureAccessAllowed,+} from '@/business/server/bot/featureAccess';+import type { getServerDB } from '@/database/core/db-adaptor';+import { AgentBotProviderModel } from '@/database/models/agentBotProvider';+import type { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';++import { platformRegistry, resolveConnectionMode } from '../../bot/platforms';+import {+ type getMessageGatewayClient,+ type MessageGatewayHost,+ resolveMessageGatewayHost,+} from '../MessageGatewayClient';+import { BOT_RUNTIME_STATUSES, updateBotRuntimeStatus } from '../runtimeStatus';+import type { ActualConnectionsSnapshot, DesiredGatewayConnection } from './types';++const log = debug('lobe-server:service:gateway');++/** Slice of the desired set whose platforms route to `host`. */+export function hostDesiredSlice(+ desired: Map<string, DesiredGatewayConnection>,+ host: MessageGatewayHost,+): Map<string, DesiredGatewayConnection> {+ return new Map(+ [...desired].filter(([, entry]) => resolveMessageGatewayHost(entry.platform) === host),+ );+}++/**+ * Whether `host` has told us it cannot serve `platform`.+ *+ * Only an explicit declaration counts. A gateway that does not describe+ * itself makes no claim, and absence of information must never be read as a+ * refusal β the Cloudflare gateway has no capabilities endpoint at all, and+ * treating that as "refuses everything" would block the rollback path,+ * where connections move BACK to it.+ */+export function hostRefusesPlatform(+ declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>,+ host: MessageGatewayHost,+ platform: string,+): boolean {+ const declared = declaredPlatforms.get(host);+ return !!declared && !declared.has(platform);+}++/** Slice of the gated set whose platforms route to `host`. */+export function hostGatedSlice(gated: Map<string, string>, host: MessageGatewayHost): Set<string> {+ return new Set(+ [...gated]+ .filter(([, platform]) => resolveMessageGatewayHost(platform) === host)+ .map(([id]) => id),+ );+}++/**+ * 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 tracked separately and excluded from the desired+ * set so the caller can disconnect only ids the gateway still holds. If the+ * gate check itself errors, the provider is kept in desired β a flaky+ * subscription lookup must not tear down a healthy connection.+ */+export async function buildDesiredConnections(+ serverDB: Awaited<ReturnType<typeof getServerDB>>,+ gateKeeper: KeyVaultsGateKeeper,+ hosts: MessageGatewayHost[],+): Promise<{+ desired: Map<string, DesiredGatewayConnection>;+ desiredComplete: boolean;+ /** Paid-gated provider id β platform (platform drives host partitioning). */+ gated: Map<string, string>;+}> {+ const desired = new Map<string, DesiredGatewayConnection>();+ let desiredComplete = true;+ const gated = new Map<string, string>();++ for (const definition of platformRegistry.listPlatforms()) {+ const platform = definition.id;++ // Only platforms owned by one of `hosts`. Loading the rest would decrypt+ // credentials for connections this call is never going to look at β pure+ // waste for a single-host pull, and a wider blast radius on failure.+ if (!hosts.includes(resolveMessageGatewayHost(platform))) continue;++ 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 gatedOnPlatform = 0;+ for (const provider of providers) {+ 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') continue;++ let allowed = true;+ try {+ allowed = await isBotFeatureAccessAllowed({+ applicationId: provider.applicationId,+ platform,+ userId: provider.userId,+ workspaceId: provider.workspaceId ?? undefined,+ });+ } catch (err) {+ log(+ 'Gateway sync: feature gate check failed %s, keeping connection: %O',+ provider.id,+ err,+ );+ }++ if (!allowed) {+ gated.set(provider.id, platform);+ gatedOnPlatform++;+ await updateBotRuntimeStatus({+ applicationId: provider.applicationId,+ errorMessage: getBotFeatureBlockedMessage(+ platform,+ provider.workspaceId ? 'workspace' : 'personal',+ ),+ platform,+ status: BOT_RUNTIME_STATUSES.failed,+ });+ continue;+ }++ desired.set(provider.id, { connectionMode, platform, provider });+ }+ // One line per platform, not per provider: a shared dev database holds+ // hundreds of gated bots, and a line each drowned every other log in+ // the sync. The per-id set still reaches the gated-disconnect step.+ if (gatedOnPlatform > 0)+ log(+ 'Gateway sync: %d paid-gated %s provider(s) excluded from desired set',+ gatedOnPlatform,+ platform,+ );+ } 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`).+ *+ * Registered ids are the authoritative existence set, so a successful call+ * produces a complete snapshot even when stats are unavailable. When only+ * stats succeed, the partial snapshot can still drive safe stale cleanup,+ * but desired ids missing from it are deferred rather than probed one by one.+ * Returns null only when neither endpoint is available.+ */+export async function fetchActualConnections(+ client: ReturnType<typeof getMessageGatewayClient>,+): Promise<ActualConnectionsSnapshot | null> {+ const connections = new Map<string, string | null>();+ let statsAvailable = false;++ try {+ const stats = await client.getStats();+ statsAvailable = true;+ 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);+ }++ try {+ const { ids } = await client.getRegisteredIds();+ for (const id of ids) {+ if (!connections.has(id)) connections.set(id, null);+ }+ return { complete: true, connections };+ } catch (err) {+ log('Gateway sync: registered-ids unavailable, using stats-only snapshot: %O', err);+ }++ return statsAvailable ? { complete: false, connections } : null;+}diff --git a/apps/server/src/services/gateway/sync/types.ts b/apps/server/src/services/gateway/sync/types.tsnew file mode 100644index 00000000000..b96c0e271ec--- /dev/null+++ b/apps/server/src/services/gateway/sync/types.ts@@ -0,0 +1,27 @@+import type { DecryptedBotProvider } from '@/database/models/agentBotProvider';++import type { ConnectionMode } from '../../bot/platforms';++export interface DesiredGatewayConnection {+ connectionMode: ConnectionMode;+ platform: string;+ provider: DecryptedBotProvider;+}++export interface ActualConnectionsSnapshot {+ /**+ * True when registered ids were loaded successfully, making absence from+ * `connections` authoritative. False means the snapshot only covers live+ * stats, so 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>;+}++/** What one host's drain phase removed, carried into its connect-phase log line. */+export interface HostDrainCounts {+ gatedDisconnected: number;+ gatedSize: number;+ stale: number;+}diff --git a/apps/server/src/services/gateway/testUtils.ts b/apps/server/src/services/gateway/testUtils.tsnew file mode 100644index 00000000000..5fb7073594c--- /dev/null+++ b/apps/server/src/services/gateway/testUtils.ts@@ -0,0 +1,215 @@+/**+ * Shared fakes for the GatewayService scenario tests. Each test file keeps its+ * own `vi.mock` calls (Vitest hoists them per file) and points the factories+ * here, so every file drives the same gateway clients, models and registries.+ */+import { vi } from 'vitest';++const createGatewayClient = () => ({+ connect: vi.fn(),+ disconnect: vi.fn(),+ disconnectAll: vi.fn(),+ getCapabilities: vi.fn(),+ getRegisteredIds: vi.fn(),+ getStats: vi.fn(),+ getStatus: vi.fn(),+ isConfigured: false,+ isEnabled: false,+});++export const mockGatewayClient = createGatewayClient();++export const mockGatewayEnv = {+ MESSAGE_GATEWAY_ENABLED: undefined as string | undefined,+ MESSAGE_GATEWAY_SERVICE_TOKEN: 'gateway-service-token' as string | undefined,+};++// Second gateway host (Node). `configured` + `platforms` drive the mocked+// host-routing helpers below, mirroring MESSAGE_GATEWAY_NODE_URL /+// MESSAGE_GATEWAY_NODE_PLATFORMS.+export const mockNodeGatewayClient = createGatewayClient();+export const mockNodeGateway = { configured: false, platforms: [] as string[] };++export const mockGatewayManager = {+ isRunning: false,+ start: vi.fn(),+ startClient: vi.fn(),+ stop: vi.fn(),+ stopClient: vi.fn(),+};++export const mockFindEnabledByPlatform = vi.fn();+export const mockFindByAgentId = vi.fn();+export const mockFindByIds = vi.fn();+export const mockFindByPlatformAndAppId = vi.fn();+export const mockFindEnabledByPlatformAndAppId = vi.fn();+export const mockGetServerDB = vi.fn();+export const mockInitWithEnvKey = vi.fn();+export const mockUpdateBotRuntimeStatus = vi.fn();+export const mockResolveConnectionMode = vi.fn();+export const mockAssertBotFeatureAccess = vi.fn();+export const mockIsBotFeatureAccessAllowed = vi.fn();+export const mockGetBotFeatureBlockedMessage = vi.fn();+export const mockGetBotRuntimeStatus = vi.fn();+export const mockResolveMessengerInstallation = vi.fn();+export const mockFindAllLinksByPlatform = vi.fn();++// βββ Module factories (point each file's `vi.mock` here) βββ++export const envsGatewayModule = () => ({ gatewayEnv: mockGatewayEnv });++export const messageGatewayClientModule = () => {+ const resolveMessageGatewayHost = (platform?: string) =>+ mockNodeGateway.configured && platform && mockNodeGateway.platforms.includes(platform)+ ? 'node'+ : 'default';+ return {+ getConfiguredMessageGatewayHosts: () =>+ mockNodeGateway.configured ? ['default', 'node'] : ['default'],+ getMessageGatewayClient: (platform?: string) =>+ resolveMessageGatewayHost(platform) === 'node' ? mockNodeGatewayClient : mockGatewayClient,+ getMessageGatewayClientForHost: (host: string) =>+ host === 'node' ? mockNodeGatewayClient : mockGatewayClient,+ // Production anchors gateway mode on the DEFAULT host: every platform not+ // routed to node falls back to it, and the node gateway cannot host those+ // platform kinds at all.+ isAnyMessageGatewayEnabled: () => mockGatewayClient.isEnabled,+ isMessageGatewayHostConfigured: (host: string) => {+ const client = host === 'node' ? mockNodeGatewayClient : mockGatewayClient;+ // Production defines isEnabled as (ENABLED === '1' && isConfigured), so+ // an enabled client is configured by construction. These fixtures set+ // the two flags independently, so mirror the real implication here+ // rather than letting a test express a state the runtime cannot reach.+ return client.isConfigured || client.isEnabled;+ },+ resolveMessageGatewayHost,+ };+};++export const messengerAccountLinkModule = () => ({+ MessengerAccountLinkModel: {+ findAllByPlatformWithCredentials: mockFindAllLinksByPlatform,+ },+});++export const gatewayManagerModule = () => ({+ createGatewayManager: () => mockGatewayManager,+ getGatewayManager: () => (mockGatewayManager.isRunning ? mockGatewayManager : null),+});++export const dbAdaptorModule = () => ({ getServerDB: mockGetServerDB });++export const agentBotProviderModule = () => ({+ AgentBotProviderModel: {+ findByAgentId: mockFindByAgentId,+ findByIds: mockFindByIds,+ findByPlatformAndAppId: mockFindByPlatformAndAppId,+ findEnabledByPlatform: mockFindEnabledByPlatform,+ findEnabledByPlatformAndAppId: mockFindEnabledByPlatformAndAppId,+ },+});++export const keyVaultsEncryptModule = () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: mockInitWithEnvKey },+});++export const runtimeStatusModule = () => ({+ BOT_RUNTIME_STATUSES: {+ connected: 'connected',+ disconnected: 'disconnected',+ dormant: 'dormant',+ failed: 'failed',+ queued: 'queued',+ starting: 'starting',+ },+ getBotRuntimeStatus: mockGetBotRuntimeStatus,+ updateBotRuntimeStatus: mockUpdateBotRuntimeStatus,+});++export const featureAccessModule = () => ({+ assertBotFeatureAccess: mockAssertBotFeatureAccess,+ getBotFeatureBlockedMessage: mockGetBotFeatureBlockedMessage,+ isBotFeatureAccessAllowed: mockIsBotFeatureAccessAllowed,+});++export const messengerInstallationsModule = () => ({+ getInstallationStore: vi.fn(() => ({ resolveByKey: mockResolveMessengerInstallation })),+ isMessengerConnectionId: (connectionId: string) => connectionId.startsWith('messenger:'),+ messengerConnectionIdForUser: ({+ connectionMode,+ installationKey,+ userId,+ }: {+ connectionMode?: string;+ installationKey: string;+ userId: string;+ }) => {+ if (connectionMode === 'websocket' && installationKey.endsWith(':singleton')) {+ return `messenger:${installationKey.slice(0, -':singleton'.length)}:singleton`;+ }+ return `messenger:${installationKey}:user-${userId}`;+ },+});++export const messengerPlatformsModule = () => ({+ messengerPlatformRegistry: {+ getPlatform: (platform: string) => ({+ connectionMode:+ platform === 'wechat' ? 'polling' : platform === 'discord' ? 'websocket' : 'webhook',+ }),+ listPlatforms: () => [+ { connectionMode: 'websocket', id: 'discord' },+ { connectionMode: 'webhook', id: 'slack' },+ { connectionMode: 'polling', id: 'wechat' },+ ],+ },+});++export const botPlatformsModule = () => ({+ extractWatchKeywordEntries: (settings?: Record<string, unknown>) =>+ Array.isArray(settings?.watchKeywords)+ ? settings.watchKeywords.filter((e: any) => typeof e?.keyword === 'string' && e.keyword)+ : [],+ platformRegistry: {+ getPlatform: (platform: string) => ({ id: platform }),+ listPlatforms: () => [{ id: 'discord' }, { id: 'telegram' }, { id: 'wechat' }],+ },+ resolveConnectionMode: mockResolveConnectionMode,+});++/** Per-test reset: clear call history and restore every default answer. */+export const resetGatewayServiceMocks = () => {+ vi.clearAllMocks();+ mockGatewayClient.isConfigured = false;+ mockGatewayClient.isEnabled = false;+ mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = undefined;+ mockGatewayManager.isRunning = false;+ mockGetServerDB.mockResolvedValue({});+ mockInitWithEnvKey.mockResolvedValue({});+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindByAgentId.mockResolvedValue([]);+ mockFindByIds.mockResolvedValue([]);+ mockFindEnabledByPlatformAndAppId.mockResolvedValue(null);+ mockFindByPlatformAndAppId.mockResolvedValue(null);+ // Default: neither host describes itself. The Cloudflare gateway has no+ // capabilities endpoint at all, so "makes no claim" is the normal case and+ // must never be read as "serves nothing".+ mockGatewayClient.getCapabilities.mockResolvedValue(null);+ mockNodeGatewayClient.getCapabilities.mockResolvedValue(null);+ // 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'));+ mockNodeGateway.configured = false;+ mockNodeGateway.platforms = [];+ mockNodeGatewayClient.isConfigured = false;+ mockNodeGatewayClient.isEnabled = false;+ mockNodeGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });+ mockFindAllLinksByPlatform.mockResolvedValue([]);+ mockUpdateBotRuntimeStatus.mockResolvedValue({});+ mockIsBotFeatureAccessAllowed.mockResolvedValue(true);+ mockGetBotFeatureBlockedMessage.mockReturnValue('This bot channel requires a paid plan.');+ mockGetBotRuntimeStatus.mockResolvedValue({});+ mockResolveMessengerInstallation.mockResolvedValue(null);+};diff --git a/apps/server/src/services/gateway/userMessenger.ts b/apps/server/src/services/gateway/userMessenger.tsnew file mode 100644index 00000000000..02c782efdd5--- /dev/null+++ b/apps/server/src/services/gateway/userMessenger.ts@@ -0,0 +1,172 @@+/**+ * Per-user messenger connections on the gateway (typing surface, polling links).+ */+import debug from 'debug';++import type { MessengerPlatform } from '@/config/messenger';+import { gatewayEnv } from '@/envs/gateway';+import {+ getInstallationStore,+ messengerConnectionIdForUser,+} from '@/server/services/messenger/installations';+import { messengerPlatformRegistry } from '@/server/services/messenger/platforms';++import { getMessageGatewayClient, isAnyMessageGatewayEnabled } from './MessageGatewayClient';++/**+ * Per-user messenger gateway connections live on the gateway as webhook-mode+ * DOs that only exist to receive `startTyping` / `stopTyping`. We keep an+ * in-process map of `connectionId β expireAt` so a hot conversation only+ * triggers one `client.connect` per process per TTL window. LRU cap defends+ * against unbounded growth in a long-running replica with a wide active set.+ *+ * Module-scoped (not instance-scoped) because `new GatewayService()` is built+ * fresh on every call site β instance state would defeat the cache.+ */+const USER_MESSENGER_CONN_TTL_MS = 30 * 60 * 1000;+const USER_MESSENGER_CONN_LRU_CAPACITY = 5000;+const userMessengerConnections = new Map<string, number>();++export interface UserMessengerConnectionParams {+ installationKey: string;+ platform: MessengerPlatform;+ userId: string;+}++const log = debug('lobe-server:service:gateway');++/**+ * Lazy-register a per-user messenger connection on the gateway and return+ * the connectionId. Idempotent within the in-process LRU TTL β repeat calls+ * skip the network round-trip.+ *+ * Returns null when:+ * - the gateway is disabled (`MESSAGE_GATEWAY_ENABLED !== '1'`)+ * - the installation store can't resolve credentials for the given key+ * - the gateway connect call throws (best-effort: messenger typing is a+ * UX nicety, never block the agent run)+ *+ * Slack token rotation is handled passively by the LRU TTL: when a stale+ * cached entry expires, the next call re-resolves credentials via+ * `resolveByKey` (which transparently refreshes Slack OAuth) and pushes the+ * fresh token to the gateway via a fresh `connect`. The DO upserts on+ * connectionId so this is non-disruptive.+ */+export async function ensureUserMessengerConnected(+ params: UserMessengerConnectionParams,+): Promise<string | null> {+ if (!isAnyMessageGatewayEnabled()) return null;++ const { installationKey, platform, userId } = params;++ // Websocket-mode singleton platforms (Discord SystemBot today): the WS+ // is registered by dc-center at `messenger:<platform>:singleton` and+ // there is no per-user DO to register here. Route typing to the+ // singleton connectionId directly β opening a per-user webhook DO would+ // (a) be rejected by the gateway and (b) not be where `triggerTyping`+ // can actually fire, since only the singleton WS holds the live socket.+ //+ // SystemBot's transport is fixed per platform (e.g. Slack SystemBot is+ // webhook even though a per-agent bot-channel Slack provider may run+ // Socket Mode/websocket), so it lives on the messenger definition, not+ // the bot-channel one.+ const connectionMode = messengerPlatformRegistry.getPlatform(platform)?.connectionMode;+ if (connectionMode === 'websocket') {+ return messengerConnectionIdForUser({ connectionMode, installationKey, userId });+ }++ const connectionId = messengerConnectionIdForUser({ connectionMode, installationKey, userId });++ const now = Date.now();+ const expireAt = userMessengerConnections.get(connectionId);+ if (expireAt && expireAt > now) {+ // Re-touch on hit so the LRU eviction order tracks recency.+ userMessengerConnections.delete(connectionId);+ userMessengerConnections.set(connectionId, expireAt);+ return connectionId;+ }++ const store = getInstallationStore(platform);+ if (!store) {+ log('ensureUserMessengerConnected: no installation store for platform=%s', platform);+ return null;+ }++ const creds = await store.resolveByKey(installationKey);+ if (!creds?.botToken) {+ log(+ 'ensureUserMessengerConnected: missing creds for key=%s (user=%s)',+ installationKey,+ userId,+ );+ return null;+ }++ try {+ const client = getMessageGatewayClient(platform);+ const isPolling = connectionMode === 'polling';+ await client.connect({+ applicationId: creds.applicationId,+ // Messenger-owned connections never consume passive channel+ // monitoring β the shared bot only reacts to DMs and explicit+ // mentions, so the gateway may drop ordinary channel messages.+ capabilities: { messageMonitoring: { enabled: false } },+ connectionId,+ // Webhook platforms only need an outbound typing surface. Polling+ // platforms (WeChat) own a real per-user inbound lifecycle and must+ // receive the complete QR-issued credential bundle.+ connectionMode: isPolling ? 'polling' : 'webhook',+ credentials: isPolling+ ? {+ baseUrl: creds.baseUrl,+ botId: creds.botId,+ botToken: creds.botToken,+ webhookToken: gatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN,+ }+ : { botToken: creds.botToken },+ platform,+ userId,+ webhookPath: isPolling ? `/api/agent/messenger/webhooks/${platform}` : '',+ });++ // Evict-on-add: the iterator yields keys in insertion order, so the+ // first key is the oldest entry.+ if (userMessengerConnections.size >= USER_MESSENGER_CONN_LRU_CAPACITY) {+ const oldest = userMessengerConnections.keys().next().value;+ if (oldest !== undefined) userMessengerConnections.delete(oldest);+ }+ userMessengerConnections.set(connectionId, now + USER_MESSENGER_CONN_TTL_MS);++ log('ensureUserMessengerConnected: registered %s', connectionId);+ return connectionId;+ } catch (err) {+ log('ensureUserMessengerConnected: connect failed for %s: %O', connectionId, err);+ return null;+ }+}++/**+ * Stop a user-owned messenger connection during unlink or credential+ * replacement. Cleanup is allowed while the gateway feature flag is off so+ * a rollout rollback cannot strand a long-polling WeChat connection.+ */+export async function disconnectUserMessenger(+ params: UserMessengerConnectionParams,+): Promise<void> {+ const { installationKey, platform, userId } = params;+ const connectionMode = messengerPlatformRegistry.getPlatform(platform)?.connectionMode;+ if (connectionMode === 'websocket') return;++ const connectionId = messengerConnectionIdForUser({ connectionMode, installationKey, userId });+ userMessengerConnections.delete(connectionId);++ const client = getMessageGatewayClient(platform);+ if (!client.isConfigured) return;++ try {+ await client.disconnect(connectionId);+ log('disconnectUserMessenger: disconnected %s', connectionId);+ } catch (error) {+ log('disconnectUserMessenger: failed for %s: %O', connectionId, error);+ }+}