🤯 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
✨ feat(gateway): route message gateway connections by platform (#18628)
Rdmclin26f44291bd197
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/gatewayCron.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/gatewayCron.test.tsnew file mode 100644index 00000000000..2dad5db2ff0--- /dev/null+++ b/apps/server/src/router-hono/agent/handlers/__tests__/gatewayCron.test.ts@@ -0,0 +1,52 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { gatewayCron } from '../gatewayCron';++const mockService = vi.hoisted(() => ({+ ensureRunning: vi.fn(),+ useMessageGateway: false,+}));++vi.mock('@/server/services/gateway', () => ({+ GatewayService: class {+ get useMessageGateway() {+ return mockService.useMessageGateway;+ }+ ensureRunning = mockService.ensureRunning;+ },+}));++describe('gatewayCron', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockService.ensureRunning.mockResolvedValue(undefined);+ delete process.env.MESSAGE_GATEWAY_URL;+ delete process.env.MESSAGE_GATEWAY_SERVICE_TOKEN;+ });++ const runCron = () => gatewayCron({ json: (body: unknown) => body } as never);++ it('reconciles through the gateway even with no MESSAGE_GATEWAY_URL', async () => {+ // Node-only deployment: the owning host has a URL, the default host does+ // not. Gating this entry on MESSAGE_GATEWAY_URL would drop such a+ // deployment into the legacy path, where nothing ever reconciles the+ // connections the Node gateway is holding.+ mockService.useMessageGateway = true;++ await expect(runCron()).resolves.toEqual({ ensureRunning: true });+ expect(mockService.ensureRunning).toHaveBeenCalledTimes(1);+ });++ it('does not reconcile through the gateway when no host is enabled', async () => {+ mockService.useMessageGateway = false;+ process.env.MESSAGE_GATEWAY_URL = 'https://message-gateway.test.com';+ process.env.MESSAGE_GATEWAY_SERVICE_TOKEN = 'token';++ // Falls through to the legacy in-process path, whose dependencies are not+ // stubbed here — reaching it at all is the assertion.+ await runCron().catch(() => undefined);++ expect(mockService.ensureRunning).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/router-hono/agent/handlers/gatewayCron.ts b/apps/server/src/router-hono/agent/handlers/gatewayCron.tsindex 8d5a272a237..2c0ec7fc9d6 100644--- a/apps/server/src/router-hono/agent/handlers/gatewayCron.ts+++ b/apps/server/src/router-hono/agent/handlers/gatewayCron.ts@@ -187,14 +187,15 @@ async function processConnectQueue(remainingMs: number): Promise<number> {* Auth: `bearerSecretAuth(CRON_SECRET)` on the route.*/export async function gatewayCron(c: Context): Promise<Response> {- // When the external message gateway is enabled, sync connections via gateway.- if (process.env.MESSAGE_GATEWAY_URL && process.env.MESSAGE_GATEWAY_SERVICE_TOKEN) {- const service = new GatewayService();-- if (service.useMessageGateway) {- await service.ensureRunning();- return c.json({ ensureRunning: true });- }+ // When any external message gateway is enabled, sync connections via gateway.+ // `useMessageGateway` is the whole guard: it already requires the kill switch+ // plus a configured owning host. Re-checking MESSAGE_GATEWAY_URL here would+ // narrow that to the default host and drop a node-only deployment into the+ // legacy path, where its connections are never reconciled.+ const service = new GatewayService();+ if (service.useMessageGateway) {+ await service.ensureRunning();+ return c.json({ ensureRunning: true });}const platforms = platformRegistry.listPlatforms();diff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.tsindex 3d40845eab0..072317f6bd0 100644--- a/apps/server/src/services/bot/AgentBridgeService.ts+++ b/apps/server/src/services/bot/AgentBridgeService.ts@@ -23,6 +23,7 @@ import type { BotReplyLocale, PlatformClient } from './platforms';import {getBotReplyLocale,getStepReactionEmoji,+ platformFromThreadId,platformRegistry,RECEIVED_REACTION_EMOJI,THINKING_REACTION_EMOJI,@@ -836,7 +837,8 @@ export class AgentBridgeService {// gateway typing makes ack redundant as user feedback.// For platforms without typing support (no triggerTyping on messenger), the// gateway typing is invisible, so we still send an ack message as user feedback.- const gwClient = getMessageGatewayClient();+ const botPlatform = platformFromThreadId(botContext?.platformThreadId);+ const gwClient = getMessageGatewayClient(botPlatform);const platformSupportsTyping =client && botContext?.platformThreadId? !!client.getMessenger(botContext.platformThreadId).triggerTyping@@ -854,7 +856,7 @@ export class AgentBridgeService {// Start gateway typing immediately so the alarm keeps it alive through// the entire AI generation (platform typing expires after ~10s).if (botContext?.platformThreadId && botContext?.applicationId) {- const platform = botContext.platformThreadId.split(':')[0];+ const platform = platformFromThreadId(botContext.platformThreadId);try {if (botContext.messengerInstallationKey) {// Messenger run: shard typing by `(platform, lobeUserId)` so each@@ -1227,7 +1229,7 @@ export class AgentBridgeService {const stopGatewayTyping = () => {if (gatewayConnectionId && botContext?.platformThreadId) {- const gwClient = getMessageGatewayClient();+ const gwClient = getMessageGatewayClient(platformFromThreadId(botContext.platformThreadId));gwClient.stopTyping(gatewayConnectionId, botContext.platformThreadId).catch((err) => {log('executeWithCallback[local]: gateway stopTyping failed: %O', err);});diff --git a/apps/server/src/services/bot/BotCallbackService.ts b/apps/server/src/services/bot/BotCallbackService.tsindex c7701136666..cad8b6eeb9c 100644--- a/apps/server/src/services/bot/BotCallbackService.ts+++ b/apps/server/src/services/bot/BotCallbackService.ts@@ -25,6 +25,7 @@ import type {import {getBotReplyLocale,getStepReactionEmoji,+ platformFromThreadId,platformRegistry,resolveBotProviderConfig,} from './platforms';@@ -153,7 +154,7 @@ export class BotCallbackService {messengerInstallationKey,userId,} = body;- const platform = platformThreadId.split(':')[0];+ const platform = platformFromThreadId(platformThreadId);const { client, connectionId, messenger, charLimit, settings, workspaceId } =await this.createMessenger({@@ -679,7 +680,7 @@ export class BotCallbackService {*/private renewGatewayTyping(connectionId: string, platformThreadId: string): void {if (!connectionId) return;- const client = getMessageGatewayClient();+ const client = getMessageGatewayClient(platformFromThreadId(platformThreadId));if (!client.isEnabled) return;client.startTyping(connectionId, platformThreadId).catch((err) => {@@ -689,7 +690,7 @@ export class BotCallbackService {private stopGatewayTyping(connectionId: string, platformThreadId: string): void {if (!connectionId) return;- const client = getMessageGatewayClient();+ const client = getMessageGatewayClient(platformFromThreadId(platformThreadId));if (!client.isEnabled) return;client.stopTyping(connectionId, platformThreadId).catch((err) => {diff --git a/apps/server/src/services/bot/platforms/index.ts b/apps/server/src/services/bot/platforms/index.tsindex d2203a37f38..36cf3993d4d 100644--- a/apps/server/src/services/bot/platforms/index.ts+++ b/apps/server/src/services/bot/platforms/index.ts@@ -75,6 +75,7 @@ export {getEffectiveConnectionMode,mergeWithDefaults,parseRuntimeKey,+ platformFromThreadId,resolveBotProviderConfig,resolveConnectionMode,} from './utils';diff --git a/apps/server/src/services/bot/platforms/utils.ts b/apps/server/src/services/bot/platforms/utils.tsindex 996f8ff62f5..3bae5935244 100644--- a/apps/server/src/services/bot/platforms/utils.ts+++ b/apps/server/src/services/bot/platforms/utils.ts@@ -200,3 +200,18 @@ export function formatUsageStats(stats: UsageStats): string {: '';return `${formatTokens(totalTokens)} tokens · $${totalCost.toFixed(4)}${time}${calls}`;}++/**+ * The platform a `platformThreadId` belongs to.+ *+ * Thread ids are platform-prefixed (`wechat:…`, `discord:…`), which is the+ * only thing tying a live conversation back to its platform once it is in+ * flight — and therefore what routes gateway calls to the host that owns the+ * connection. Passes `undefined` through so optional bot contexts can hand+ * their thread id over without a guard at every call site.+ */+export function platformFromThreadId(platformThreadId: string): string;+export function platformFromThreadId(platformThreadId: string | undefined): string | undefined;+export function platformFromThreadId(platformThreadId?: string): string | undefined {+ return platformThreadId?.split(':')[0];+}diff --git a/apps/server/src/services/gateway/MessageGatewayClient.ts b/apps/server/src/services/gateway/MessageGatewayClient.tsindex d5662951e91..cf4c0725a40 100644--- a/apps/server/src/services/gateway/MessageGatewayClient.ts+++ b/apps/server/src/services/gateway/MessageGatewayClient.ts@@ -62,25 +62,29 @@ export interface MessageGatewayStats {// ─── Client ───/**- * HTTP client for the message-gateway Cloudflare Worker.+ * HTTP client for one message-gateway deployment.*- * The gateway is a pure connection proxy — it only manages persistent+ * A gateway is a pure connection proxy — it only manages persistent* connections (WebSocket/long-polling) and forwards inbound events to* LobeHub's webhook. Outbound messaging is NOT routed through the gateway;* LobeHub calls platform REST APIs directly.+ *+ * Deliberately one class for every host: the deployments speak the same HTTP+ * protocol, and the reconcile sync diffs them uniformly. Per-host behaviour+ * differences belong in the routing layer below, not in a subclass — see+ * `resolveMessageGatewayHost`. If a method ever becomes host-specific, split+ * this into a shared-protocol base plus a per-host subclass at that point.+ *+ * The endpoint is always passed in; `getMessageGatewayClientForHost` is the+ * single place that reads it out of the environment.*/export class MessageGatewayClient {private baseUrl: string;private serviceToken: string;- constructor(baseUrl?: string, serviceToken?: string) {- if (baseUrl !== undefined) {- this.baseUrl = baseUrl;- this.serviceToken = serviceToken || '';- } else {- this.baseUrl = gatewayEnv.MESSAGE_GATEWAY_URL || '';- this.serviceToken = gatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN || '';- }+ constructor(baseUrl: string, serviceToken: string) {+ this.baseUrl = baseUrl;+ this.serviceToken = serviceToken;}get isConfigured(): boolean {@@ -235,13 +239,107 @@ export class MessageGatewayClient {}}-// ─── Singleton ───+// ─── Host routing ───-let _client: MessageGatewayClient | undefined;+/**+ * A "host" is one deployed message-gateway a platform's connections live on:+ *+ * - `default` — the original gateway (`MESSAGE_GATEWAY_URL`), Cloudflare+ * Workers + Durable Objects. Right for webhook and hibernation-friendly+ * platforms.+ * - `node` — the Node gateway (`MESSAGE_GATEWAY_NODE_URL`), a long-lived+ * container speaking the same HTTP protocol. Right for platforms a DO+ * can't host economically (permanent long-polling loops such as WeChat)+ * or at all (native deps such as Baileys).+ *+ * `MESSAGE_GATEWAY_NODE_PLATFORMS` decides which platforms route to `node`;+ * everything else stays on `default`. The reconcile sync uses the same+ * resolution to move existing connections between hosts, so editing the env+ * var is the entire migration/rollback procedure.+ */+export type MessageGatewayHost = 'default' | 'node';++const parseNodePlatforms = (): Set<string> =>+ new Set(+ (gatewayEnv.MESSAGE_GATEWAY_NODE_PLATFORMS ?? '')+ .split(',')+ .map((entry) => entry.trim())+ .filter(Boolean),+ );++/** The host that should own connections for `platform` (default host when omitted). */+export function resolveMessageGatewayHost(platform?: string): MessageGatewayHost {+ if (!platform || !gatewayEnv.MESSAGE_GATEWAY_NODE_URL) return 'default';+ return parseNodePlatforms().has(platform) ? 'node' : 'default';+}-export function getMessageGatewayClient(): MessageGatewayClient {- if (!_client) {- _client = new MessageGatewayClient();+/**+ * Hosts the reconcile sync must visit. The default host is always included —+ * even with every platform routed away it still needs stale cleanup.+ */+export function getConfiguredMessageGatewayHosts(): MessageGatewayHost[] {+ return gatewayEnv.MESSAGE_GATEWAY_NODE_URL ? ['default', 'node'] : ['default'];+}++// ─── Singleton per host ───++const clients = new Map<MessageGatewayHost, MessageGatewayClient>();++export function getMessageGatewayClientForHost(host: MessageGatewayHost): MessageGatewayClient {+ let client = clients.get(host);+ if (!client) {+ client = new MessageGatewayClient(+ messageGatewayHostUrl(host) || '',+ // Both gateways share one service token — inbound webhook/callback+ // validation only accepts this value anyway.+ gatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN || '',+ );+ clients.set(host, client);}- return _client;+ return client;+}++/**+ * Client for the gateway that owns `platform`'s connections. Callers that+ * operate on a concrete connection must pass the platform; omitting it+ * returns the default-host client (kill switch checks, legacy cleanup).+ */+export function getMessageGatewayClient(platform?: string): MessageGatewayClient {+ return getMessageGatewayClientForHost(resolveMessageGatewayHost(platform));+}++/** Base URL configured for `host`, if any. The only env→host URL mapping. */+function messageGatewayHostUrl(host: MessageGatewayHost): string | undefined {+ return host === 'node' ? gatewayEnv.MESSAGE_GATEWAY_NODE_URL : gatewayEnv.MESSAGE_GATEWAY_URL;+}++/**+ * Whether `host` has both a URL and a token. Reads env directly rather than+ * asking a client: clients are cached per host and hold the endpoint they were+ * built with, so they answer for the environment as it was the first time+ * anyone asked.+ */+export function isMessageGatewayHostConfigured(host: MessageGatewayHost): boolean {+ return !!messageGatewayHostUrl(host) && !!gatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN;+}++/**+ * Whether this deployment is gateway-managed at all — as opposed to "which+ * host owns this platform?".+ *+ * Deliberately anchored on the DEFAULT host. Gateway mode is a whole-process+ * switch (taking it means the in-process runtime never starts), and every+ * platform absent from `MESSAGE_GATEWAY_NODE_PLATFORMS` resolves to the+ * default host — so without one configured, some platform always ends up with+ * a client that cannot connect and no fallback.+ *+ * A deployment with ONLY a Node gateway is therefore not supported here, and+ * that is a capability statement rather than an omission: the Node gateway+ * hosts long-polling and native-dep platforms only, so it can never serve the+ * webhook and websocket platforms the default host carries. Serving those+ * from a Node-only deployment would need a per-platform runtime decision+ * instead of one process-wide flag.+ */+export function isAnyMessageGatewayEnabled(): boolean {+ return gatewayEnv.MESSAGE_GATEWAY_ENABLED === '1' && isMessageGatewayHostConfigured('default');}diff --git a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts b/apps/server/src/services/gateway/__tests__/GatewayService.test.tsindex 96e53e57a62..f0e6b9d66e7 100644--- a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts+++ b/apps/server/src/services/gateway/__tests__/GatewayService.test.ts@@ -22,6 +22,21 @@ const mockGatewayEnv = vi.hoisted(() => ({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(),+ 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(),@@ -49,8 +64,40 @@ vi.mock('@/envs/gateway', () => ({gatewayEnv: mockGatewayEnv,}));-vi.mock('../MessageGatewayClient', () => ({- getMessageGatewayClient: () => mockGatewayClient,+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', () => ({@@ -119,6 +166,11 @@ vi.mock('@/server/services/messenger/platforms', () => ({connectionMode:platform === 'wechat' ? 'polling' : platform === 'discord' ? 'websocket' : 'webhook',}),+ listPlatforms: () => [+ { connectionMode: 'websocket', id: 'discord' },+ { connectionMode: 'webhook', id: 'slack' },+ { connectionMode: 'polling', id: 'wechat' },+ ],},}));@@ -153,6 +205,13 @@ describe('GatewayService', () => {// 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.');@@ -1127,4 +1186,358 @@ describe('GatewayService', () => {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();+ });+ });});diff --git a/apps/server/src/services/gateway/__tests__/MessageGatewayClient.test.ts b/apps/server/src/services/gateway/__tests__/MessageGatewayClient.test.tsindex 9c6d93e0ccd..09ae338f9d8 100644--- a/apps/server/src/services/gateway/__tests__/MessageGatewayClient.test.ts+++ b/apps/server/src/services/gateway/__tests__/MessageGatewayClient.test.ts@@ -1,9 +1,20 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';-import { MessageGatewayClient } from '../MessageGatewayClient';+import {+ getConfiguredMessageGatewayHosts,+ getMessageGatewayClient,+ getMessageGatewayClientForHost,+ isAnyMessageGatewayEnabled,+ MessageGatewayClient,+ resolveMessageGatewayHost,+} from '../MessageGatewayClient';const mockGatewayEnv = vi.hoisted(() => ({MESSAGE_GATEWAY_ENABLED: undefined as string | undefined,+ MESSAGE_GATEWAY_NODE_PLATFORMS: undefined as string | undefined,+ MESSAGE_GATEWAY_NODE_URL: undefined as string | undefined,+ MESSAGE_GATEWAY_SERVICE_TOKEN: undefined as string | undefined,+ MESSAGE_GATEWAY_URL: undefined as string | undefined,}));vi.mock('@/envs/gateway', () => ({@@ -168,4 +179,84 @@ describe('MessageGatewayClient', () => {).rejects.toThrow('not configured');});});++ describe('host routing', () => {+ // Set once before the per-host singletons are first constructed — the+ // client cache captures env at construction, while host RESOLUTION reads+ // env live and can be toggled per test.+ beforeAll(() => {+ mockGatewayEnv.MESSAGE_GATEWAY_NODE_PLATFORMS = ' wechat , whatsapp-baileys ';+ mockGatewayEnv.MESSAGE_GATEWAY_NODE_URL = 'https://node-gateway.test.com';+ mockGatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN = 'shared-token';+ mockGatewayEnv.MESSAGE_GATEWAY_URL = 'https://message-gateway.test.com';+ });++ it('routes listed platforms to node only while the node gateway is configured', () => {+ expect(resolveMessageGatewayHost('wechat')).toBe('node');+ expect(resolveMessageGatewayHost('whatsapp-baileys')).toBe('node');+ expect(resolveMessageGatewayHost('discord')).toBe('default');+ expect(resolveMessageGatewayHost()).toBe('default');++ mockGatewayEnv.MESSAGE_GATEWAY_NODE_URL = undefined;+ // Rollback path: dropping the node URL sends everything back to default.+ expect(resolveMessageGatewayHost('wechat')).toBe('default');+ mockGatewayEnv.MESSAGE_GATEWAY_NODE_URL = 'https://node-gateway.test.com';+ });++ it('always reconciles the default host, and node only when configured', () => {+ expect(getConfiguredMessageGatewayHosts()).toEqual(['default', 'node']);++ mockGatewayEnv.MESSAGE_GATEWAY_NODE_URL = undefined;+ expect(getConfiguredMessageGatewayHosts()).toEqual(['default']);+ mockGatewayEnv.MESSAGE_GATEWAY_NODE_URL = 'https://node-gateway.test.com';+ });++ it('returns distinct per-host singletons; node uses the shared service token', () => {+ const nodeClient = getMessageGatewayClient('wechat');+ const defaultClient = getMessageGatewayClient('discord');++ expect(nodeClient).toBe(getMessageGatewayClientForHost('node'));+ expect(defaultClient).toBe(getMessageGatewayClientForHost('default'));+ expect(nodeClient).not.toBe(defaultClient);+ // Node URL + the shared MESSAGE_GATEWAY_SERVICE_TOKEN are all it needs.+ expect(nodeClient.isConfigured).toBe(true);+ });++ describe('isAnyMessageGatewayEnabled', () => {+ beforeEach(() => {+ mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = '1';+ mockGatewayEnv.MESSAGE_GATEWAY_NODE_PLATFORMS = 'wechat';+ mockGatewayEnv.MESSAGE_GATEWAY_NODE_URL = 'https://node-gateway.test.com';+ mockGatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN = 'shared-token';+ mockGatewayEnv.MESSAGE_GATEWAY_URL = 'https://message-gateway.test.com';+ });++ it('is false while the kill switch is off, whatever is configured', () => {+ mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = undefined;+ expect(isAnyMessageGatewayEnabled()).toBe(false);+ });++ it('is false without a default host, however much the node host is configured', () => {+ // Node-only is out of scope by capability, not by oversight: the Node+ // gateway hosts long-polling/native-dep platforms only, so it can+ // never serve the webhook and websocket platforms that fall back to+ // the default host. Entering gateway mode here would hand those+ // platforms a client that cannot connect, with the in-process runtime+ // already skipped.+ mockGatewayEnv.MESSAGE_GATEWAY_URL = undefined;+ expect(isAnyMessageGatewayEnabled()).toBe(false);+ });++ it('stays true on an empty platform list while the default host is configured', () => {+ // The step-2 rollout shape: node URL deployed, nothing routed to it yet.+ mockGatewayEnv.MESSAGE_GATEWAY_NODE_PLATFORMS = '';+ expect(isAnyMessageGatewayEnabled()).toBe(true);+ });++ it('is true for the cutover shape: default host live, wechat routed to node', () => {+ mockGatewayEnv.MESSAGE_GATEWAY_NODE_PLATFORMS = 'wechat';+ expect(isAnyMessageGatewayEnabled()).toBe(true);+ });+ });+ });});diff --git a/apps/server/src/services/gateway/index.ts b/apps/server/src/services/gateway/index.tsindex d3dd8b1557d..d1c307050e4 100644--- a/apps/server/src/services/gateway/index.ts+++ b/apps/server/src/services/gateway/index.ts@@ -12,6 +12,10 @@ import {AgentBotProviderModel,type DecryptedBotProvider,} from '@/database/models/agentBotProvider';+import {+ type DecryptedMessengerAccountLink,+ MessengerAccountLinkModel,+} from '@/database/models/messengerAccountLink';import { gatewayEnv } from '@/envs/gateway';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import {@@ -31,9 +35,14 @@ import {import { BOT_CONNECT_QUEUE_EXPIRE_MS, BotConnectQueue } from './botConnectQueue';import { createGatewayManager, getGatewayManager } from './GatewayManager';import {+ getConfiguredMessageGatewayHosts,getMessageGatewayClient,+ getMessageGatewayClientForHost,+ isAnyMessageGatewayEnabled,type MessageGatewayCapabilities,type MessageGatewayConnectionStatus,+ type MessageGatewayHost,+ resolveMessageGatewayHost,} from './MessageGatewayClient';import { BOT_RUNTIME_STATUSES, getBotRuntimeStatus, updateBotRuntimeStatus } from './runtimeStatus';@@ -116,6 +125,13 @@ interface ActualConnectionsSnapshot {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 {@@ -163,7 +179,7 @@ export class GatewayService {* the client reachable for cleanup.*/get useMessageGateway(): boolean {- return getMessageGatewayClient().isEnabled;+ return isAnyMessageGatewayEnabled();}async ensureRunning(): Promise<void> {@@ -185,15 +201,16 @@ export class GatewayService {log('GatewayManager started');// Clean up leftover gateway connections to prevent duplicates.- const client = getMessageGatewayClient();- if (client.isConfigured) {+ for (const host of getConfiguredMessageGatewayHosts()) {+ const client = getMessageGatewayClientForHost(host);+ if (!client.isConfigured) continue;try {const result = await client.disconnectAll();if (result.total > 0) {- log('Cleaned up %d gateway connections', result.total);+ log('Cleaned up %d gateway connections on %s host', result.total, host);}} catch (err) {- log('Gateway cleanup skipped (non-critical): %O', err);+ log('Gateway cleanup skipped on %s host (non-critical): %O', host, err);}}}@@ -215,7 +232,6 @@ export class GatewayService {*/private async syncGatewayConnections(): Promise<void> {const startedAt = Date.now();- const client = getMessageGatewayClient();const serverDB = await getServerDB();const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();@@ -224,7 +240,141 @@ export class GatewayService {gateKeeper,);- const actual = await this.fetchActualConnections(client);+ // 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();+ 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({+ 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,+ desired,+ drainedThisRound,+ host,+ snapshot: snapshots.get(host) ?? null,+ });+ }++ await this.syncMessengerPollingConnections(+ serverDB,+ gateKeeper,+ snapshots,+ hostsReadyToReceive,+ );++ 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),+ );+ }++ /** 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),+ );+ }++ /**+ * 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: {+ 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 {+ 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@@ -238,12 +388,32 @@ export class GatewayService {actual.connections,desired,gated,+ host,+ hostsReadyToReceive,+ drainedThisRound,);} else if (actual) {log('Gateway sync: desired set incomplete, skipping stale-connection cleanup this round');}- // ── desired − actual → connect ──+ 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>;+ desired: Map<string, DesiredGatewayConnection>;+ drainedThisRound: Set<string>;+ host: MessageGatewayHost;+ snapshot: ActualConnectionsSnapshot | null;+ }): Promise<void> {+ const { counts, currentlyElsewhere, drainedThisRound, host, snapshot: actual } = params;+ const client = getMessageGatewayClientForHost(host);+ const desired = this.hostDesiredSlice(params.desired, host);let connected = 0;let deferred = 0;@@ -281,6 +451,21 @@ export class GatewayService {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@@ -362,23 +547,292 @@ export class GatewayService {);log(- 'Gateway sync complete in %dms: desired=%d actual=%s snapshotComplete=%s connected=%d skipped=%d deferred=%d gated=%d gatedDisconnected=%d stale=%d failed=%d registeredOnlyWakes=%d registeredOnlyDeferred=%d',- Date.now() - startedAt,+ '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,- gated.size,- gatedDisconnected,- stale,+ 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>,+ ): 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;++ 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 {+ const credentials = link.credentials as {+ baseUrl?: string;+ botId?: string;+ botToken?: string;+ };+ await client.connect(+ {+ applicationId: link.applicationId!,+ 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}`,+ },+ { 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.@@ -394,11 +848,12 @@ export class GatewayService {): Promise<{desired: Map<string, DesiredGatewayConnection>;desiredComplete: boolean;- gated: Set<string>;+ /** 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 Set<string>();+ const gated = new Map<string, string>();for (const definition of platformRegistry.listPlatforms()) {const platform = definition.id;@@ -439,7 +894,7 @@ export class GatewayService {}if (!allowed) {- gated.add(provider.id);+ gated.set(provider.id, platform);await updateBotRuntimeStatus({applicationId: provider.applicationId,errorMessage: getBotFeatureBlockedMessage(@@ -555,6 +1010,9 @@ export class GatewayService {actual: Map<string, string | null>,desired: Map<string, DesiredGatewayConnection>,gated: Set<string>,+ host: MessageGatewayHost,+ hostsReadyToReceive: Set<MessageGatewayHost>,+ drainedThisRound: Set<string>,): Promise<number> {const allStaleIds = [...actual.keys()].filter((id) => !desired.has(id) && !gated.has(id) && !isMessengerConnectionId(id),@@ -589,22 +1047,44 @@ export class GatewayService {try {const row = rowById.get(id);- // TOCTOU guard: a provider enabled (and connected) between the- // desired snapshot and the actual fetch shows up in `actual` but not- // in `desired`. These rows were queried after both snapshots, so- // trust them: an enabled persistent-mode row is not stale — leave it- // for the next round to classify with a fresh desired set.- if (+ // 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'- ) {- log('Gateway sync: %s enabled during sync, skipping stale disconnect', id);- return;+ '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;+ }}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@@ -727,7 +1207,6 @@ export class GatewayService {const serverDB = await getServerDB();const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();const providers = await AgentBotProviderModel.findByAgentId(serverDB, agentId, gateKeeper);- const client = getMessageGatewayClient();await Promise.all(providers.map(async (provider) => {@@ -738,6 +1217,7 @@ export class GatewayService {if (connectionMode === 'webhook') return;try {+ const client = getMessageGatewayClient(provider.platform);const { state } = await client.getStatus(provider.id);await updateBotRuntimeStatus({applicationId: provider.applicationId,@@ -790,7 +1270,7 @@ export class GatewayService {// is already the source of truth.if (connectionMode === 'webhook') return cached;- const client = getMessageGatewayClient();+ const client = getMessageGatewayClient(platform);try {const { state } = await client.getStatus(provider.id);return await updateBotRuntimeStatus({@@ -921,7 +1401,7 @@ export class GatewayService {}try {- const client = getMessageGatewayClient();+ const client = getMessageGatewayClient(platform);const isPolling = connectionMode === 'polling';await client.connect({applicationId: creds.applicationId,@@ -980,7 +1460,7 @@ export class GatewayService {const connectionId = messengerConnectionIdForUser({ connectionMode, installationKey, userId });userMessengerConnections.delete(connectionId);- const client = getMessageGatewayClient();+ const client = getMessageGatewayClient(platform);if (!client.isConfigured) return;try {@@ -998,7 +1478,7 @@ export class GatewayService {applicationId: string,userId: string,): Promise<'started'> {- const client = getMessageGatewayClient();+ const client = getMessageGatewayClient(platform);const serverDB = await getServerDB();const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();@@ -1065,7 +1545,7 @@ export class GatewayService {await manager.stopClient(platform, applicationId);}- const client = getMessageGatewayClient();+ const client = getMessageGatewayClient(platform);const serverDB = await getServerDB();const provider = await AgentBotProviderModel.findByPlatformAndAppId(diff --git a/locales/ar/chat.json b/locales/ar/chat.jsonindex 85c937e169b..e2eabedd2c6 100644--- a/locales/ar/chat.json+++ b/locales/ar/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "عرض المهام الفرعية","taskList.form.subGrouping": "التجميع الفرعي","taskList.groupBy.assignee": "المكلّف",+ "taskList.groupBy.heartbeat": "نبض القلب","taskList.groupBy.none": "دون تجميع","taskList.groupBy.priority": "الأولوية",+ "taskList.groupBy.schedule": "الجدول","taskList.groupBy.status": "الحالة","taskList.hiddenCompleted.count_one": "{{count}} مهمة","taskList.hiddenCompleted.count_other": "{{count}} مهام",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "الحالة","taskList.orderBy.title": "العنوان","taskList.orderBy.updatedAt": "تاريخ التحديث",+ "taskList.scheduled.empty": "لا توجد مهام مجدولة حتى الآن",+ "taskList.scheduled.title": "المهام المجدولة","taskList.title": "المهام","taskList.unassigned": "غير مكلّف","taskList.unassignedHint": "سيقوم Lobe AI بتشغيل هذه المهمة عند عدم تعيين منفذ",diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.jsonindex ec0bb517a05..cb848cd8d1f 100644--- a/locales/bg-BG/chat.json+++ b/locales/bg-BG/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "Показване на подзадачи","taskList.form.subGrouping": "Подгрупиране","taskList.groupBy.assignee": "Отговорник",+ "taskList.groupBy.heartbeat": "Сърдечен ритъм","taskList.groupBy.none": "Без групиране","taskList.groupBy.priority": "Приоритет",+ "taskList.groupBy.schedule": "График","taskList.groupBy.status": "Статус","taskList.hiddenCompleted.count_one": "{{count}} задача","taskList.hiddenCompleted.count_other": "{{count}} задачи",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "Статус","taskList.orderBy.title": "Заглавие","taskList.orderBy.updatedAt": "Дата на обновяване",+ "taskList.scheduled.empty": "Все още няма планирани задачи",+ "taskList.scheduled.title": "Планирани задачи","taskList.title": "Задачи","taskList.unassigned": "Без отговорник","taskList.unassignedHint": "Lobe AI ще изпълнява тази задача, когато няма зададен изпълнител",diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.jsonindex 01f9467bb68..7a4db160f5a 100644--- a/locales/de-DE/chat.json+++ b/locales/de-DE/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "Unteraufgaben anzeigen","taskList.form.subGrouping": "Untergruppierung","taskList.groupBy.assignee": "Zuständige Person",+ "taskList.groupBy.heartbeat": "Herzschlag","taskList.groupBy.none": "Keine Gruppierung","taskList.groupBy.priority": "Priorität",+ "taskList.groupBy.schedule": "Zeitplan","taskList.groupBy.status": "Status","taskList.hiddenCompleted.count_one": "{{count}} Aufgabe","taskList.hiddenCompleted.count_other": "{{count}} Aufgaben",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "Status","taskList.orderBy.title": "Titel","taskList.orderBy.updatedAt": "Aktualisiert am",+ "taskList.scheduled.empty": "Noch keine geplanten Aufgaben",+ "taskList.scheduled.title": "Geplante Aufgaben","taskList.title": "Aufgaben","taskList.unassigned": "Nicht zugewiesen","taskList.unassignedHint": "Lobe AI führt diese Aufgabe aus, wenn kein Bearbeiter zugewiesen ist",diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.jsonindex 74ec631c102..d12f49e62cf 100644--- a/locales/es-ES/chat.json+++ b/locales/es-ES/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "Mostrar subtareas","taskList.form.subGrouping": "Subagrupación","taskList.groupBy.assignee": "Asignado a",+ "taskList.groupBy.heartbeat": "Latido","taskList.groupBy.none": "Sin agrupación","taskList.groupBy.priority": "Prioridad",+ "taskList.groupBy.schedule": "Horario","taskList.groupBy.status": "Estado","taskList.hiddenCompleted.count_one": "{{count}} tarea","taskList.hiddenCompleted.count_other": "{{count}} tareas",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "Estado","taskList.orderBy.title": "Título","taskList.orderBy.updatedAt": "Actualizada el",+ "taskList.scheduled.empty": "Aún no hay tareas programadas",+ "taskList.scheduled.title": "Tareas programadas","taskList.title": "Tareas","taskList.unassigned": "Sin asignar","taskList.unassignedHint": "Lobe AI ejecutará esta tarea cuando no haya ningún asignado",diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.jsonindex 27c9118ce53..8514fc2a5bf 100644--- a/locales/fa-IR/chat.json+++ b/locales/fa-IR/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "نمایش زیرکارها","taskList.form.subGrouping": "زیرگروهبندی","taskList.groupBy.assignee": "واگذارشده",+ "taskList.groupBy.heartbeat": "ضربان قلب","taskList.groupBy.none": "بدون گروهبندی","taskList.groupBy.priority": "اولویت",+ "taskList.groupBy.schedule": "برنامهریزی","taskList.groupBy.status": "وضعیت","taskList.hiddenCompleted.count_one": "{{count}} وظیفه","taskList.hiddenCompleted.count_other": "{{count}} وظیفه",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "وضعیت","taskList.orderBy.title": "عنوان","taskList.orderBy.updatedAt": "تاریخ بروزرسانی",+ "taskList.scheduled.empty": "هنوز هیچ وظیفهای برنامهریزی نشده است",+ "taskList.scheduled.title": "وظایف برنامهریزی شده","taskList.title": "وظایف","taskList.unassigned": "واگذار نشده","taskList.unassignedHint": "Lobe AI این وظیفه را زمانی اجرا میکند که مسئولی تعیین نشده باشد",diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.jsonindex 814b725b2d8..418b4e20fc2 100644--- a/locales/fr-FR/chat.json+++ b/locales/fr-FR/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "Afficher les sous-tâches","taskList.form.subGrouping": "Sous-regroupement","taskList.groupBy.assignee": "Attribué à",+ "taskList.groupBy.heartbeat": "Fréquence cardiaque","taskList.groupBy.none": "Aucun regroupement","taskList.groupBy.priority": "Priorité",+ "taskList.groupBy.schedule": "Programme","taskList.groupBy.status": "Statut","taskList.hiddenCompleted.count_one": "{{count}} tâche","taskList.hiddenCompleted.count_other": "{{count}} tâches",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "Statut","taskList.orderBy.title": "Titre","taskList.orderBy.updatedAt": "Date de mise à jour",+ "taskList.scheduled.empty": "Aucune tâche programmée pour le moment",+ "taskList.scheduled.title": "Tâches programmées","taskList.title": "Tâches","taskList.unassigned": "Non attribuée","taskList.unassignedHint": "Lobe AI exécutera cette tâche lorsqu’aucun responsable n’est défini",diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.jsonindex 080856f95aa..f73ceda4106 100644--- a/locales/it-IT/chat.json+++ b/locales/it-IT/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "Mostra sotto-attività","taskList.form.subGrouping": "Sotto-raggruppamento","taskList.groupBy.assignee": "Assegnatario",+ "taskList.groupBy.heartbeat": "Battito cardiaco","taskList.groupBy.none": "Nessun raggruppamento","taskList.groupBy.priority": "Priorità",+ "taskList.groupBy.schedule": "Programma","taskList.groupBy.status": "Stato","taskList.hiddenCompleted.count_one": "{{count}} task","taskList.hiddenCompleted.count_other": "{{count}} task",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "Stato","taskList.orderBy.title": "Titolo","taskList.orderBy.updatedAt": "Data di aggiornamento",+ "taskList.scheduled.empty": "Nessun compito programmato al momento",+ "taskList.scheduled.title": "Compiti programmati","taskList.title": "Attività","taskList.unassigned": "Non assegnata","taskList.unassignedHint": "Lobe AI eseguirà questo task quando non è assegnato a nessuno",diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.jsonindex d1288ffe87f..3ad62707363 100644--- a/locales/ja-JP/chat.json+++ b/locales/ja-JP/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "サブタスクを表示","taskList.form.subGrouping": "サブグループ化","taskList.groupBy.assignee": "担当者",+ "taskList.groupBy.heartbeat": "ハートビート","taskList.groupBy.none": "グループ化なし","taskList.groupBy.priority": "優先度",+ "taskList.groupBy.schedule": "スケジュール","taskList.groupBy.status": "ステータス","taskList.hiddenCompleted.count_one": "{{count}} 件のタスク","taskList.hiddenCompleted.count_other": "{{count}} 件のタスク",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "ステータス","taskList.orderBy.title": "タイトル","taskList.orderBy.updatedAt": "更新日時",+ "taskList.scheduled.empty": "まだスケジュールされたタスクはありません",+ "taskList.scheduled.title": "スケジュールされたタスク","taskList.title": "タスク","taskList.unassigned": "未割り当て","taskList.unassignedHint": "担当者が設定されていない場合、Lobe AI がこのタスクを実行します",diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.jsonindex 813154a2534..3eb2ba4907a 100644--- a/locales/ko-KR/chat.json+++ b/locales/ko-KR/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "하위 작업 보기","taskList.form.subGrouping": "하위 그룹화","taskList.groupBy.assignee": "담당자",+ "taskList.groupBy.heartbeat": "하트비트","taskList.groupBy.none": "그룹 없음","taskList.groupBy.priority": "우선순위",+ "taskList.groupBy.schedule": "일정","taskList.groupBy.status": "상태","taskList.hiddenCompleted.count_one": "{{count}}개의 작업","taskList.hiddenCompleted.count_other": "{{count}}개의 작업",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "상태","taskList.orderBy.title": "제목","taskList.orderBy.updatedAt": "수정일",+ "taskList.scheduled.empty": "아직 예정된 작업이 없습니다",+ "taskList.scheduled.title": "예정된 작업","taskList.title": "작업","taskList.unassigned": "미할당","taskList.unassignedHint": "담당자가 배정되지 않은 경우 Lobe AI가 이 작업을 실행합니다",diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.jsonindex 2497cdee62a..05eb7920297 100644--- a/locales/nl-NL/chat.json+++ b/locales/nl-NL/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "Toon sub-taken","taskList.form.subGrouping": "Subgroepering","taskList.groupBy.assignee": "Toegewezen aan",+ "taskList.groupBy.heartbeat": "Hartslag","taskList.groupBy.none": "Geen groepering","taskList.groupBy.priority": "Prioriteit",+ "taskList.groupBy.schedule": "Schema","taskList.groupBy.status": "Status","taskList.hiddenCompleted.count_one": "{{count}} taak","taskList.hiddenCompleted.count_other": "{{count}} taken",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "Status","taskList.orderBy.title": "Titel","taskList.orderBy.updatedAt": "Bijgewerkt op",+ "taskList.scheduled.empty": "Nog geen geplande taken",+ "taskList.scheduled.title": "Geplande taken","taskList.title": "Taken","taskList.unassigned": "Niet toegewezen","taskList.unassignedHint": "Lobe AI voert deze taak uit wanneer er geen verantwoordelijke is ingesteld",diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.jsonindex 7a0cba4672a..eb9e97905d9 100644--- a/locales/pl-PL/chat.json+++ b/locales/pl-PL/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "Pokaż podzadania","taskList.form.subGrouping": "Podgrupowanie","taskList.groupBy.assignee": "Przypisany",+ "taskList.groupBy.heartbeat": "Puls serca","taskList.groupBy.none": "Bez grupowania","taskList.groupBy.priority": "Priorytet",+ "taskList.groupBy.schedule": "Harmonogram","taskList.groupBy.status": "Status","taskList.hiddenCompleted.count_one": "{{count}} zadanie","taskList.hiddenCompleted.count_other": "{{count}} zadań",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "Status","taskList.orderBy.title": "Tytuł","taskList.orderBy.updatedAt": "Data aktualizacji",+ "taskList.scheduled.empty": "Brak zaplanowanych zadań",+ "taskList.scheduled.title": "Zaplanowane zadania","taskList.title": "Zadania","taskList.unassigned": "Nieprzypisane","taskList.unassignedHint": "Lobe AI uruchomi to zadanie, gdy nie ma przypisanego wykonawcy",diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.jsonindex d9bcc252f46..105a9a3331a 100644--- a/locales/pt-BR/chat.json+++ b/locales/pt-BR/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "Mostrar subtarefas","taskList.form.subGrouping": "Subagrupamento","taskList.groupBy.assignee": "Responsável",+ "taskList.groupBy.heartbeat": "Batimento cardíaco","taskList.groupBy.none": "Sem agrupamento","taskList.groupBy.priority": "Prioridade",+ "taskList.groupBy.schedule": "Cronograma","taskList.groupBy.status": "Status","taskList.hiddenCompleted.count_one": "{{count}} tarefa","taskList.hiddenCompleted.count_other": "{{count}} tarefas",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "Status","taskList.orderBy.title": "Título","taskList.orderBy.updatedAt": "Atualizadas em",+ "taskList.scheduled.empty": "Nenhuma tarefa agendada ainda",+ "taskList.scheduled.title": "Tarefas agendadas","taskList.title": "Tarefas","taskList.unassigned": "Sem responsável","taskList.unassignedHint": "O Lobe AI executará esta tarefa quando nenhum responsável estiver definido",diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.jsonindex 2216f571484..0b7562f0a01 100644--- a/locales/ru-RU/chat.json+++ b/locales/ru-RU/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "Показать подзадачи","taskList.form.subGrouping": "Доп. группировка","taskList.groupBy.assignee": "Исполнитель",+ "taskList.groupBy.heartbeat": "Сердцебиение","taskList.groupBy.none": "Без группировки","taskList.groupBy.priority": "По приоритету",+ "taskList.groupBy.schedule": "Расписание","taskList.groupBy.status": "По статусу","taskList.hiddenCompleted.count_one": "{{count}} задача","taskList.hiddenCompleted.count_other": "{{count}} задач",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "Статус","taskList.orderBy.title": "Название","taskList.orderBy.updatedAt": "Дата обновления",+ "taskList.scheduled.empty": "Запланированных задач пока нет",+ "taskList.scheduled.title": "Запланированные задачи","taskList.title": "Задачи","taskList.unassigned": "Не назначено","taskList.unassignedHint": "Lobe AI выполнит эту задачу, если исполнитель не назначен",diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.jsonindex 6514212a000..91ee98ae6a5 100644--- a/locales/tr-TR/chat.json+++ b/locales/tr-TR/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "Alt görevleri göster","taskList.form.subGrouping": "Alt gruplama","taskList.groupBy.assignee": "Atanan",+ "taskList.groupBy.heartbeat": "Kalp Atışı","taskList.groupBy.none": "Gruplama yok","taskList.groupBy.priority": "Öncelik",+ "taskList.groupBy.schedule": "Program","taskList.groupBy.status": "Durum","taskList.hiddenCompleted.count_one": "{{count}} görev","taskList.hiddenCompleted.count_other": "{{count}} görev",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "Durum","taskList.orderBy.title": "Başlık","taskList.orderBy.updatedAt": "Güncellenme zamanı",+ "taskList.scheduled.empty": "Henüz planlanmış görev yok",+ "taskList.scheduled.title": "Planlanmış Görevler","taskList.title": "Görevler","taskList.unassigned": "Atanmamış","taskList.unassignedHint": "Atanan olmadığında Lobe AI bu görevi çalıştırır",diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.jsonindex 671bf746734..008407f1876 100644--- a/locales/vi-VN/chat.json+++ b/locales/vi-VN/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "Hiển thị nhiệm vụ con","taskList.form.subGrouping": "Nhóm phụ","taskList.groupBy.assignee": "Người được giao",+ "taskList.groupBy.heartbeat": "Nhịp tim","taskList.groupBy.none": "Không nhóm","taskList.groupBy.priority": "Ưu tiên",+ "taskList.groupBy.schedule": "Lịch trình","taskList.groupBy.status": "Trạng thái","taskList.hiddenCompleted.count_one": "{{count}} tác vụ","taskList.hiddenCompleted.count_other": "{{count}} tác vụ",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "Trạng thái","taskList.orderBy.title": "Tiêu đề","taskList.orderBy.updatedAt": "Ngày cập nhật",+ "taskList.scheduled.empty": "Chưa có nhiệm vụ được lên lịch",+ "taskList.scheduled.title": "Nhiệm vụ đã lên lịch","taskList.title": "Công Việc","taskList.unassigned": "Chưa giao","taskList.unassignedHint": "Lobe AI sẽ chạy tác vụ này khi không có người được giao",diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.jsonindex e210ecc749d..557f3763e67 100644--- a/locales/zh-TW/chat.json+++ b/locales/zh-TW/chat.json@@ -1513,8 +1513,10 @@"taskList.form.showSubTasks": "顯示子任務","taskList.form.subGrouping": "次分組","taskList.groupBy.assignee": "負責人",+ "taskList.groupBy.heartbeat": "心跳","taskList.groupBy.none": "不分組","taskList.groupBy.priority": "依優先順序",+ "taskList.groupBy.schedule": "排程","taskList.groupBy.status": "依狀態","taskList.hiddenCompleted.count_one": "{{count}} 個任務","taskList.hiddenCompleted.count_other": "{{count}} 個任務",@@ -1536,6 +1538,8 @@"taskList.orderBy.status": "狀態","taskList.orderBy.title": "標題","taskList.orderBy.updatedAt": "更新時間",+ "taskList.scheduled.empty": "尚無排程任務",+ "taskList.scheduled.title": "排程任務","taskList.title": "任務","taskList.unassigned": "未指派","taskList.unassignedHint": "未指派時,Lobe AI 將自動執行此任務",diff --git a/packages/app-config/src/messenger.test.ts b/packages/app-config/src/messenger.test.tsindex 213f354fda9..0bef032dbed 100644--- a/packages/app-config/src/messenger.test.ts+++ b/packages/app-config/src/messenger.test.ts@@ -11,6 +11,8 @@ const {} = vi.hoisted(() => ({gatewayEnvState: {MESSAGE_GATEWAY_ENABLED: '1' as string | undefined,+ MESSAGE_GATEWAY_NODE_PLATFORMS: undefined as string | undefined,+ MESSAGE_GATEWAY_NODE_URL: undefined as string | undefined,MESSAGE_GATEWAY_SERVICE_TOKEN: 'gateway-token' as string | undefined,MESSAGE_GATEWAY_URL: 'https://gateway.example.com' as string | undefined,},@@ -38,6 +40,8 @@ describe('getMessengerWechatConfig', () => {gatewayEnvState.MESSAGE_GATEWAY_ENABLED = '1';gatewayEnvState.MESSAGE_GATEWAY_URL = 'https://gateway.example.com';gatewayEnvState.MESSAGE_GATEWAY_SERVICE_TOKEN = 'gateway-token';+ gatewayEnvState.MESSAGE_GATEWAY_NODE_URL = undefined;+ gatewayEnvState.MESSAGE_GATEWAY_NODE_PLATFORMS = undefined;redisEnvState.REDIS_URL = 'redis://localhost:6379';mockGetServerDB.mockResolvedValue({});mockInitWithEnvKey.mockResolvedValue({});@@ -65,4 +69,25 @@ describe('getMessengerWechatConfig', () => {await expect(getMessengerWechatConfig()).resolves.toBeNull();expect(mockFindEnabledByPlatform).not.toHaveBeenCalled();});++ it('advertises WeChat when it is routed to the node host and the default host is live', async () => {+ // The cutover shape. WeChat's connection lives on the Node gateway while+ // the default host still carries every other platform.+ gatewayEnvState.MESSAGE_GATEWAY_NODE_URL = 'https://node-gateway.example.com';+ gatewayEnvState.MESSAGE_GATEWAY_NODE_PLATFORMS = 'wechat';++ await expect(getMessengerWechatConfig()).resolves.toEqual({ enabled: true });+ });++ it('does not advertise WeChat on a node-only deployment', async () => {+ // The runtime only enters gateway mode with a configured default host, so+ // here nothing would ever serve these links — advertising WeChat would+ // offer users a channel that silently never connects.+ gatewayEnvState.MESSAGE_GATEWAY_URL = undefined;+ gatewayEnvState.MESSAGE_GATEWAY_NODE_URL = 'https://node-gateway.example.com';+ gatewayEnvState.MESSAGE_GATEWAY_NODE_PLATFORMS = 'wechat';++ await expect(getMessengerWechatConfig()).resolves.toBeNull();+ expect(mockFindEnabledByPlatform).not.toHaveBeenCalled();+ });});diff --git a/packages/app-config/src/messenger.ts b/packages/app-config/src/messenger.tsindex 57bf30e38ca..08ff303c8c9 100644--- a/packages/app-config/src/messenger.ts+++ b/packages/app-config/src/messenger.ts@@ -10,6 +10,11 @@ import {import { gatewayEnv } from '@/envs/gateway';import { redisEnv } from '@/envs/redis';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import {+ isAnyMessageGatewayEnabled,+ isMessageGatewayHostConfigured,+ resolveMessageGatewayHost,+} from '@/server/services/gateway/MessageGatewayClient';const log = debug('lobe-server:messenger:config');@@ -171,13 +176,22 @@ export const getMessengerDiscordConfig = async (): Promise<MessengerDiscordConfi};export const getMessengerWechatConfig = async (): Promise<MessengerWechatConfig | null> => {- // WeChat owns a long-polling connection in the Message Gateway, with Redis+ // WeChat owns a long-polling connection in a message gateway, with Redis// backing its QR session and per-user connection state. Do not advertise an// enabled provider until the runtime can actually complete that lifecycle.+ //+ // Two conditions, and both are load-bearing: the runtime only enters gateway+ // mode when the default host is configured (`isAnyMessageGatewayEnabled`),+ // and WeChat's connection is only reachable if the host that OWNS WeChat is+ // configured — which is the Node host once it is routed there. Checking only+ // the second would advertise WeChat in a Node-only deployment, where the+ // runtime stays in-process and nothing ever serves those links.+ const gatewayReady =+ isAnyMessageGatewayEnabled() &&+ isMessageGatewayHostConfigured(resolveMessageGatewayHost('wechat'));if (gatewayEnv.MESSAGE_GATEWAY_ENABLED !== '1' ||- !gatewayEnv.MESSAGE_GATEWAY_URL ||- !gatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN ||+ !gatewayReady ||!redisEnv.REDIS_URL ||process.env.DISABLE_REDIS) {diff --git a/packages/database/src/models/messengerAccountLink.ts b/packages/database/src/models/messengerAccountLink.tsindex d5d5803128e..6824b20119d 100644--- a/packages/database/src/models/messengerAccountLink.ts+++ b/packages/database/src/models/messengerAccountLink.ts@@ -450,6 +450,24 @@ export class MessengerAccountLinkModel {return result ? decryptRow(result, gateKeeper) : undefined;};+ /**+ * All account links for a platform, credentials decrypted. Powers the+ * gateway reconcile for polling platforms (WeChat), whose per-user+ * connections must be re-pushed to the owning gateway host after restarts+ * or host migrations — server-only, never expose through TRPC.+ */+ static findAllByPlatformWithCredentials = async (+ db: LobeChatDatabase,+ platform: string,+ gateKeeper?: GateKeeper,+ ): Promise<DecryptedMessengerAccountLink[]> => {+ const rows = await db+ .select()+ .from(messengerAccountLinks)+ .where(eq(messengerAccountLinks.platform, platform));+ return Promise.all(rows.map((row) => decryptRow(row, gateKeeper)));+ };+/** Static setter used by IM `/switch` (no user-scope context, but trusted by sender match). */static setActiveAgentById = async (db: LobeChatDatabase,diff --git a/packages/env/src/gateway.ts b/packages/env/src/gateway.tsindex 48e6d9bba13..521058fe41e 100644--- a/packages/env/src/gateway.ts+++ b/packages/env/src/gateway.ts@@ -7,6 +7,8 @@ export const getGatewayConfig = () => {DEVICE_GATEWAY_SERVICE_TOKEN: process.env.DEVICE_GATEWAY_SERVICE_TOKEN,DEVICE_GATEWAY_URL: process.env.DEVICE_GATEWAY_URL,MESSAGE_GATEWAY_ENABLED: process.env.MESSAGE_GATEWAY_ENABLED,+ MESSAGE_GATEWAY_NODE_PLATFORMS: process.env.MESSAGE_GATEWAY_NODE_PLATFORMS,+ MESSAGE_GATEWAY_NODE_URL: process.env.MESSAGE_GATEWAY_NODE_URL,MESSAGE_GATEWAY_SERVICE_TOKEN: process.env.MESSAGE_GATEWAY_SERVICE_TOKEN,MESSAGE_GATEWAY_URL: process.env.MESSAGE_GATEWAY_URL,},@@ -15,6 +17,20 @@ export const getGatewayConfig = () => {DEVICE_GATEWAY_SERVICE_TOKEN: z.string().optional(),DEVICE_GATEWAY_URL: z.string().url().optional(),MESSAGE_GATEWAY_ENABLED: z.string().optional(),+ /**+ * Comma-separated platform ids whose gateway connections live on the+ * Node message gateway instead of the default one (e.g. `wechat`).+ * Doubles as the migration/rollback switch: remove a platform from the+ * list and the next reconcile moves its connections back.+ */+ MESSAGE_GATEWAY_NODE_PLATFORMS: z.string().optional(),+ /**+ * Base URL of the Node message gateway (long-polling / native-dep+ * platforms). Both gateways share MESSAGE_GATEWAY_SERVICE_TOKEN — the+ * inbound webhook/callback validation only accepts that one value, so a+ * per-gateway token would not actually isolate anything.+ */+ MESSAGE_GATEWAY_NODE_URL: z.string().url().optional(),MESSAGE_GATEWAY_SERVICE_TOKEN: z.string().optional(),MESSAGE_GATEWAY_URL: z.string().url().optional(),},