Skip to content

🤯 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.

🐛 fix(wecom): keep a reply that lands while the message gateway restarts (#23092)

Rdmclin21247174af229
diff --git a/apps/server/src/services/bot/platforms/wecom/client.test.ts b/apps/server/src/services/bot/platforms/wecom/client.test.ts
index 78614e07925..7648ebd0de0 100644
--- a/apps/server/src/services/bot/platforms/wecom/client.test.ts
+++ b/apps/server/src/services/bot/platforms/wecom/client.test.ts
@@ -129,7 +129,7 @@ vi.mock('@/server/services/gateway/MessageGatewayClient', () => {
const { decodeWeComThreadId, WECOM_DISPLACED_MESSAGE, WeComClientFactory, wecomExtractFiles } =
await import('./client');
-const { resetWeComGatewayConnectionIds } = await import('./outbound');
+const { createGatewayWeComOutbound, resetWeComGatewayConnectionIds } = await import('./outbound');
const { MessageGatewaySendError } = await import('@/server/services/gateway/MessageGatewayClient');
const flush = async () => {
@@ -416,6 +416,120 @@ describe('WeComClient on the Node message gateway', () => {
]);
});
+ describe('while the gateway does not hold the connection (restart / reconnect)', () => {
+ const thread = { id: 'u1', type: 'single' as const };
+ const delays = [1, 2, 3];
+
+ it('waits for the connection to come back instead of losing the reply', async () => {
+ const sleep = vi.fn(async () => {});
+ gw.sendText
+ .mockRejectedValueOnce(new MessageGatewaySendError(404, 'Connection not found'))
+ .mockRejectedValueOnce(
+ new MessageGatewaySendError(500, '{"error":"wecom: connection prov-1 is not connected"}'),
+ )
+ .mockResolvedValueOnce({ messageId: 'push-1' });
+
+ const outbound = createGatewayWeComOutbound('bot-1', { retryDelaysMs: delays, sleep });
+
+ await expect(outbound.deliver(thread, 'answer')).resolves.toEqual({ id: 'push-1' });
+ expect(gw.sendText).toHaveBeenCalledTimes(3);
+ expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([1, 2]);
+ });
+
+ it('retries when the gateway cannot be reached at all', async () => {
+ const sleep = vi.fn(async () => {});
+ gw.sendText
+ .mockRejectedValueOnce(new TypeError('fetch failed', { cause: { code: 'ECONNREFUSED' } }))
+ .mockResolvedValueOnce({ messageId: 'push-1' });
+
+ const outbound = createGatewayWeComOutbound('bot-1', { retryDelaysMs: delays, sleep });
+
+ await expect(outbound.deliver(thread, 'answer')).resolves.toEqual({ id: 'push-1' });
+ expect(sleep).toHaveBeenCalledTimes(1);
+ });
+
+ it('gives up after the last retry and surfaces the error', async () => {
+ const sleep = vi.fn(async () => {});
+ gw.sendText.mockRejectedValue(new MessageGatewaySendError(404, 'Connection not found'));
+
+ const outbound = createGatewayWeComOutbound('bot-1', { retryDelaysMs: delays, sleep });
+
+ await expect(outbound.deliver(thread, 'answer')).rejects.toThrow('Connection not found');
+ expect(gw.sendText).toHaveBeenCalledTimes(delays.length + 1);
+ expect(sleep).toHaveBeenCalledTimes(delays.length);
+ });
+
+ it.each([
+ [
+ 'a receipt lost when the socket dropped',
+ new MessageGatewaySendError(500, '{"error":"WeCom bot bot-1 connection closed"}'),
+ ],
+ [
+ 'a gateway connection reset mid-request',
+ new TypeError('fetch failed', { cause: { code: 'ECONNRESET' } }),
+ ],
+ ['a fetch failure without a known cause', new TypeError('fetch failed')],
+ ])('does not resend %s: it may already have reached WeCom', async (_label, failure) => {
+ const sleep = vi.fn(async () => {});
+ gw.sendText.mockRejectedValue(failure);
+
+ const outbound = createGatewayWeComOutbound('bot-1', { retryDelaysMs: delays, sleep });
+
+ await expect(outbound.deliver(thread, 'answer')).rejects.toBe(failure);
+ expect(gw.sendText).toHaveBeenCalledTimes(1);
+ expect(sleep).not.toHaveBeenCalled();
+ });
+
+ it("still tries a recreated bot's new connection id after the last backoff", async () => {
+ const sleep = vi.fn(async () => {});
+ const notFound = new MessageGatewaySendError(404, 'Connection not found');
+ gw.sendText.mockImplementation(async (id: string) => {
+ if (id === 'prov-2') return { messageId: 'push-1' };
+ throw notFound;
+ });
+ // The row is recreated during the last backoff window: only the final lookup sees it.
+ let lookups = 0;
+ gw.findByPlatformAndAppId.mockImplementation(async () => {
+ lookups++;
+ return { id: lookups > delays.length + 1 ? 'prov-2' : 'prov-1' };
+ });
+
+ const outbound = createGatewayWeComOutbound('bot-1', { retryDelaysMs: delays, sleep });
+
+ await expect(outbound.deliver(thread, 'answer')).resolves.toEqual({ id: 'push-1' });
+ expect(sleep).toHaveBeenCalledTimes(delays.length);
+ expect(gw.sendText.mock.calls.at(-1)?.[0]).toBe('prov-2');
+ });
+
+ it('stops after one extra try even when the connection id keeps changing', async () => {
+ const sleep = vi.fn(async () => {});
+ gw.sendText.mockRejectedValue(new MessageGatewaySendError(404, 'Connection not found'));
+ let lookups = 0;
+ gw.findByPlatformAndAppId.mockImplementation(async () => ({ id: `prov-${++lookups}` }));
+
+ const outbound = createGatewayWeComOutbound('bot-1', { retryDelaysMs: delays, sleep });
+
+ await expect(outbound.deliver(thread, 'answer')).rejects.toThrow('Connection not found');
+ expect(gw.sendText).toHaveBeenCalledTimes(delays.length + 2);
+ });
+
+ it('does not resend what WeCom itself refused', async () => {
+ const sleep = vi.fn(async () => {});
+ gw.sendText.mockRejectedValue(
+ new MessageGatewaySendError(
+ 500,
+ '{"error":"WeCom rejected aibot_send_msg (errcode 40008)"}',
+ ),
+ );
+
+ const outbound = createGatewayWeComOutbound('bot-1', { retryDelaysMs: delays, sleep });
+
+ await expect(outbound.deliver(thread, 'answer')).rejects.toThrow(/40008/);
+ expect(gw.sendText).toHaveBeenCalledTimes(1);
+ expect(sleep).not.toHaveBeenCalled();
+ });
+ });
+
it('accepts a bot the gateway holds with the same Secret, without a probe', async () => {
gw.findEnabledByPlatformAndAppId.mockResolvedValue({
credentials: { secret: 'sec' },
diff --git a/apps/server/src/services/bot/platforms/wecom/outbound.ts b/apps/server/src/services/bot/platforms/wecom/outbound.ts
index 57a896c777a..c6505836a08 100644
--- a/apps/server/src/services/bot/platforms/wecom/outbound.ts
+++ b/apps/server/src/services/bot/platforms/wecom/outbound.ts
@@ -40,11 +40,71 @@ const resolveConnectionId = async (botId: string, refresh = false): Promise<stri
/** Test hook: forget cached connection ids. */
export const resetWeComGatewayConnectionIds = (): void => connectionIds.clear();
+/**
+ * Waits between attempts while the gateway does not hold the bot's connection. A gateway restart
+ * (deploy) drops every connection and re-registers them from lobehub's desired set, which took
+ * ~30 s in production (T-14145); a reply that lands in that window must wait for it, not be lost.
+ * About a minute in total, well inside the callback's function budget.
+ */
+export const WECOM_GATEWAY_RETRY_DELAYS_MS = [2000, 4000, 8000, 15_000, 15_000, 15_000];
+
+/**
+ * Refusals raised before any frame is written: the gateway has no live socket for the bot, or the
+ * connection refuses to enqueue. Not "connection closed": a socket that drops while a frame waits
+ * for its receipt may already have delivered it.
+ */
+const NOT_SENT_DETAIL = /is not connected|socket is not open/i;
+
+/** `fetch` failed while connecting, so the request never reached the gateway. */
+const CONNECT_ERROR_CODES = new Set([
+ 'ECONNREFUSED',
+ 'ENOTFOUND',
+ 'EAI_AGAIN',
+ 'UND_ERR_CONNECT_TIMEOUT',
+]);
+
+const connectErrorCode = (error: TypeError): string | undefined => {
+ const cause = (error as { cause?: { code?: unknown } }).cause;
+ return typeof cause?.code === 'string' ? cause.code : undefined;
+};
+
+/**
+ * Whether a failed send is known to have sent nothing because the gateway does not hold a live
+ * connection right now: a 404 (no such connection), the "not connected" refusal raised before a
+ * frame is written, or a gateway that could not be reached at all. Only these are retried —
+ * `sendText` carries no idempotency key, so a failure that may have reached WeCom (a lost receipt,
+ * a reset mid-request) is surfaced instead of risking a duplicate reply. A rejection from WeCom
+ * itself is not retried either.
+ */
+export const isConnectionNotHeldError = (error: unknown): boolean => {
+ if (error instanceof MessageGatewaySendError) {
+ return error.status === 404 || (error.status >= 500 && NOT_SENT_DETAIL.test(error.message));
+ }
+ if (error instanceof TypeError) {
+ const code = connectErrorCode(error);
+ return !!code && CONNECT_ERROR_CODES.has(code);
+ }
+ return false;
+};
+
+export interface GatewayWeComOutboundOptions {
+ retryDelaysMs?: number[];
+ sleep?: (ms: number) => Promise<void>;
+}
+
+const defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+
/**
* Replies through the Node message gateway, which holds the bot's long connection and keeps its
* reply state (each conversation's latest req_id and open stream) next to the socket.
*/
-export const createGatewayWeComOutbound = (botId: string): WeComOutbound => ({
+export const createGatewayWeComOutbound = (
+ botId: string,
+ {
+ retryDelaysMs = WECOM_GATEWAY_RETRY_DELAYS_MS,
+ sleep = defaultSleep,
+ }: GatewayWeComOutboundOptions = {},
+): WeComOutbound => ({
deliver: async (thread, text) => {
const client = getMessageGatewayClient(PLATFORM);
const platformThreadId = encodeThreadId(thread);
@@ -53,15 +113,29 @@ export const createGatewayWeComOutbound = (botId: string): WeComOutbound => ({
return { id: messageId ?? '' };
};
- const connectionId = await resolveConnectionId(botId);
- try {
- return await send(connectionId);
- } catch (error) {
- // The bot was recreated under the same BotID: its connection now has a new id.
- if (!(error instanceof MessageGatewaySendError) || error.status !== 404) throw error;
- const fresh = await resolveConnectionId(botId, true);
- if (fresh === connectionId) throw error;
- return send(fresh);
+ let connectionId = await resolveConnectionId(botId);
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await send(connectionId);
+ } catch (error) {
+ if (!isConnectionNotHeldError(error)) throw error;
+ // The bot may have been recreated under the same BotID: its connection then has a new id,
+ // worth trying right away — even once the backoff budget is spent, but only once past it.
+ const fresh = await resolveConnectionId(botId, true);
+ if (fresh !== connectionId && attempt <= retryDelaysMs.length) {
+ connectionId = fresh;
+ continue;
+ }
+ if (attempt >= retryDelaysMs.length) throw error;
+ log(
+ 'deliver: the gateway does not hold %s (attempt %d), retrying in %dms: %O',
+ botId,
+ attempt + 1,
+ retryDelaysMs[attempt],
+ error,
+ );
+ await sleep(retryDelaysMs[attempt]);
+ }
}
},
openStream: async (thread) => {
diff --git a/apps/server/src/services/bot/platforms/wecom/protocol-spec.md b/apps/server/src/services/bot/platforms/wecom/protocol-spec.md
index 3c8ca993ffc..ad57c5553f7 100644
--- a/apps/server/src/services/bot/platforms/wecom/protocol-spec.md
+++ b/apps/server/src/services/bot/platforms/wecom/protocol-spec.md
@@ -119,6 +119,7 @@ LobeHub 的回复管线没有 token 级流式;平台定义 `supportsMessageEdi
- 回复上下文按**会话**保存,只记最新一条消息的 `req_id`。群里两人先后 @ 机器人、第一条还没开始回复时,第一条的回答会挂在第二条消息的 stream 上,第二条的回答改走主动推送。
- 打开「处理中」消息(`processingMessage`)时,这条确认消息会先用掉 stream,最终回复因此走主动推送,显示为一条新消息而不是对原消息的回复。
- 回复上下文和打开的 stream 跟连接放在一起。连接被替换(保存凭证、手动重连、管理后台重新注册)时它们会清空:替换前已经开跑的回答找不到 `req_id`,改走主动推送,之前打开的「正在回复」气泡由 WeCom 自行超时。
+- 网关重启(部署)或重连期间,网关上暂时没有这个 bot 的连接:`/send` 返回 404 或 `not connected`,或者连不上网关。服务端按退避重试约 1 分钟(`WECOM_GATEWAY_RETRY_DELAYS_MS`),等网关重新注册连接后以主动推送送达。只重试确定没发出去的失败:`sendText` 没有幂等键,收据丢失(`connection closed`)、请求中途断开(`ECONNRESET`)这类可能已经送达的失败直接报错,企微自己拒绝的也不重试,避免重复回复。网关停连接时先用 `drain()` 给打开的 stream 发 `finish`(内容 `…`),不再留下一直转圈的气泡(T-14145,线上 2026-11-16 网关部署时出现过一次回复丢失)。
### 4.2 限制
diff --git a/packages/chat-adapter-wecom/src/connection.test.ts b/packages/chat-adapter-wecom/src/connection.test.ts
index 802c03dc282..5c418a04bb0 100644
--- a/packages/chat-adapter-wecom/src/connection.test.ts
+++ b/packages/chat-adapter-wecom/src/connection.test.ts
@@ -273,6 +273,56 @@ describe('WeComLongConnection — replies', () => {
});
describe('WeComLongConnection — lifecycle', () => {
+ it('drain() finishes open streams before stopping, so no bubble is left spinning', async () => {
+ const { connection, socket } = setup();
+ active = connection;
+ await connection.start();
+ socket().serverSend(inbound('req-1'));
+ socket().serverSend(inbound('req-2', { from: { userid: 'lisi' } }));
+ await flush();
+ await connection.openStream({ id: 'zhangsan', type: 'single' });
+ await connection.openStream({ id: 'lisi', type: 'single' });
+ const live = socket();
+
+ await connection.drain();
+
+ const finishes = live.sentWith(WECOM_CMD.RESPOND).filter((f) => f.body.stream.finish);
+ expect(finishes.map((f) => f.headers.req_id).sort()).toEqual(['req-1', 'req-2']);
+ expect(finishes[0].body.stream.content).toBe('…');
+ expect(connection.isConnected).toBe(false);
+ expect(live.readyState).toBe(3);
+ });
+
+ it('drain() stops after maxWaitMs even when receipts never come', async () => {
+ // Receipts would only time out after a minute: if `maxWaitMs` were ignored, drain() would
+ // outlive the test's own timeout.
+ const { connection, socket } = setup({ ackTimeoutMs: 60_000 });
+ active = connection;
+ await connection.start();
+ socket().serverSend(inbound('req-1'));
+ await flush();
+ await connection.openStream({ id: 'zhangsan', type: 'single' });
+ socket().ackFor = () => undefined;
+ const live = socket();
+
+ await connection.drain(20);
+
+ expect(live.sentWith(WECOM_CMD.RESPOND).at(-1)?.body.stream).toMatchObject({ finish: true });
+ expect(connection.isConnected).toBe(false);
+ expect(live.readyState).toBe(3);
+ });
+
+ it('drain() just stops when no stream is open', async () => {
+ const { connection, socket } = setup();
+ active = connection;
+ await connection.start();
+
+ await connection.drain();
+
+ expect(socket().sentWith(WECOM_CMD.RESPOND)).toHaveLength(0);
+ expect(connection.isConnected).toBe(false);
+ });
+
it('stops without reconnecting when a newer connection displaces it', async () => {
const onDisplaced = vi.fn();
const { connection, socket, sockets } = setup({ onDisplaced });
diff --git a/packages/chat-adapter-wecom/src/connection.ts b/packages/chat-adapter-wecom/src/connection.ts
index d8adc846e73..90af8ac0e8c 100644
--- a/packages/chat-adapter-wecom/src/connection.ts
+++ b/packages/chat-adapter-wecom/src/connection.ts
@@ -202,6 +202,38 @@ export class WeComLongConnection {
this.options.log('WeCom bot %s: connection stopped', this.botId);
}
+ /**
+ * Finish every open stream, then stop. `stop()` alone drops them: the socket closes with the
+ * "replying" bubble still spinning on the user's side, and nothing can finish it later because
+ * a stream only lives on the connection that opened it. The answer itself still arrives — as a
+ * proactive push once a connection is back. The finish frames go out at once; waiting for their
+ * receipts is capped at `maxWaitMs`, so a shutdown is not held up by a slow server.
+ */
+ async drain(maxWaitMs = 3000): Promise<void> {
+ if (!this.stopped && this.isConnected && this.streams.size > 0) {
+ const open = [...this.streams.values()];
+ this.streams.clear();
+ const finishes = open.map((stream) => {
+ clearTimeout(stream.timer);
+ return this.respond(stream.reqId, {
+ msgtype: 'stream',
+ stream: { content: stream.content || '…', finish: true, id: stream.streamId },
+ }).catch((error) => {
+ this.options.log('WeCom bot %s: finishing stream on drain failed: %O', this.botId, error);
+ });
+ });
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ await Promise.race([
+ Promise.all(finishes),
+ new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, maxWaitMs);
+ }),
+ ]);
+ clearTimeout(timer);
+ }
+ this.stop();
+ }
+
// ------------------------------------------------------------------
// Outbound
// ------------------------------------------------------------------