Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(feishu): 群主流 @ 自动开话题 — 每话题独立 session, 回复不再刷屏群主流 (#2621)

Lizi1774bdb921e7
diff --git a/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts b/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
index e7e42cde10..a8f811aa0f 100644
--- a/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
@@ -181,6 +181,91 @@ describe('IM slash commands', () => {
expect(mocks.sendMarkdownText).toHaveBeenCalledWith('ou_user', ui.agent.apiKeyMissing);
});
+ it('首条 slash 带 consumePendingOpener: 首个文本回复 patch 开场白卡, 不另发', async () => {
+ const { handlers } = makeHarness();
+ const withMarkdown = vi.fn(async () => true);
+ const withCard = vi.fn(async () => true);
+
+ const handled = await handlers.handleSlashCommand('/help', {
+ botContextId: 'bot',
+ userId: 'ou_user',
+ consumePendingOpener: { withMarkdown, withCard },
+ });
+
+ expect(handled).toBe(true);
+ expect(withMarkdown).toHaveBeenCalledWith('ou_user', ui.slash.help);
+ expect(mocks.sendMarkdownText).not.toHaveBeenCalled();
+ });
+
+ it('首条 slash 消费失败时回落正常发送', async () => {
+ const { handlers } = makeHarness();
+ const withMarkdown = vi.fn(async () => false);
+
+ const handled = await handlers.handleSlashCommand('/help', {
+ botContextId: 'bot',
+ userId: 'ou_user',
+ consumePendingOpener: { withMarkdown, withCard: vi.fn(async () => false) },
+ });
+
+ expect(handled).toBe(true);
+ expect(withMarkdown).toHaveBeenCalledTimes(1);
+ expect(mocks.sendMarkdownText).toHaveBeenCalledWith('ou_user', ui.slash.help);
+ });
+
+ it('opener patch 失败时回落正常发送(用户仍收到回复)', async () => {
+ const { handlers } = makeHarness();
+ const withMarkdown = vi.fn(async () => {
+ throw new Error('patch failed');
+ });
+
+ const handled = await handlers.handleSlashCommand('/help', {
+ botContextId: 'bot',
+ userId: 'ou_user',
+ consumePendingOpener: { withMarkdown, withCard: vi.fn(async () => false) },
+ });
+
+ expect(handled).toBe(true);
+ expect(withMarkdown).toHaveBeenCalledTimes(1);
+ // patch 抛错不吞回复 — 回落正常发送。
+ expect(mocks.sendMarkdownText).toHaveBeenCalledWith('ou_user', ui.slash.help);
+ });
+
+ it('opener 卡片替换失败时回落正常发卡', async () => {
+ const { handlers } = makeHarness();
+ const withCard = vi.fn(async () => {
+ throw new Error('patch failed');
+ });
+
+ const handled = await handlers.handleSlashCommand('/ctr', {
+ botContextId: 'bot',
+ userId: 'ou_user',
+ consumePendingOpener: { withMarkdown: vi.fn(async () => false), withCard },
+ });
+
+ expect(handled).toBe(true);
+ expect(withCard).toHaveBeenCalledTimes(1);
+ expect(mocks.sendInteractiveCard).toHaveBeenCalled();
+ });
+
+ it('/ctr 发卡失败时不 enterControl(用户不会被锁死)', async () => {
+ const { enterControl } = await import('../controlState');
+ mocks.sendInteractiveCard.mockRejectedValueOnce(new Error('send failed'));
+ const { handlers } = makeHarness();
+
+ await handlers.handleSlashCommand('/ctr', SLASH_CTX);
+
+ expect(enterControl).not.toHaveBeenCalled();
+ });
+
+ it('/ctr 发卡成功才 enterControl', async () => {
+ const { enterControl } = await import('../controlState');
+ const { handlers } = makeHarness();
+
+ await handlers.handleSlashCommand('/ctr', SLASH_CTX);
+
+ expect(enterControl).toHaveBeenCalledWith('bot', 'ou_user');
+ });
+
it('explains the persisted provider when /new defaults are unauthenticated', async () => {
const prepared = { ...defaultRow, agentKind: 'codex' as const, model: 'gpt-5.5' };
const repo = makeRepo({ prepareNewSession: vi.fn(async () => prepared) });
diff --git a/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts
index 9b3d342da9..031d2e12ed 100644
--- a/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts
@@ -92,6 +92,8 @@ describe('messageHandler !stop routing', () => {
let handleSlashCommand: ReturnType<typeof vi.fn>;
let sendMarkdownText: ReturnType<typeof vi.fn>;
let sendText: ReturnType<typeof vi.fn>;
+ let consumePendingOpenerCard: ReturnType<typeof vi.fn>;
+ let consumePendingOpenerAsCard: ReturnType<typeof vi.fn>;
let deliver: (event: IMMessageEvent) => void;
function wire(threadScoped: boolean): void {
@@ -100,6 +102,9 @@ describe('messageHandler !stop routing', () => {
handleSlashCommand = vi.fn(async () => true);
sendMarkdownText = vi.fn(async () => undefined);
sendText = vi.fn(async () => undefined);
+ // 群主流 @ 开话题的开场白卡收口能力(仅 feishu 实现; 这里模拟富卡渠道)。
+ consumePendingOpenerCard = vi.fn(async () => false);
+ consumePendingOpenerAsCard = vi.fn(async () => false);
const im = {
onMessage(handler: (event: IMMessageEvent) => void) {
@@ -108,11 +113,14 @@ describe('messageHandler !stop routing', () => {
},
sendMarkdownText,
sendText,
+ consumePendingOpenerCard,
+ consumePendingOpenerAsCard,
} as unknown as ChannelIM;
const adapter = {
channel: 'slack',
im,
+ output: { kind: 'rich-card', im },
ui: slackUi,
threadScoped,
} as unknown as ImChannelAdapter;
@@ -405,4 +413,210 @@ describe('messageHandler !stop routing', () => {
);
expect(runAgentTurn).not.toHaveBeenCalled();
});
+
+ // ── 群主流 @ 开话题的开场白卡收口(仅富卡渠道) ────────────────────────────
+ // 非流式终态分支若让「思考中」开场白卡留在话题里: 卡卡住, 且同话题下一条
+ // 真消息会把答案 patch 到这张旧卡上。终态分支要么消费卡 patch 回复, 要么
+ // 撤回卡让自备回复成为第一条实质内容。
+
+ it('!stop 首条消费开场白卡: patch 回复, 不再另发', async () => {
+ consumePendingOpenerCard.mockResolvedValue(true);
+ deliver(makeEvent({ groupContextLane: { chatId: 'C1', threadId: '' } }));
+ await flushMicrotasks();
+
+ expect(consumePendingOpenerCard).toHaveBeenCalledWith(
+ 'U123456789',
+ slackUi.agent.stopDone(0),
+ );
+ expect(sendMarkdownText).not.toHaveBeenCalled();
+ expect(stopActiveTurn).toHaveBeenCalledTimes(1);
+ });
+
+ it('consume 返回 false 时回落正常发送(有 pending opener 但消费失败)', async () => {
+ deliver(makeEvent({ groupContextLane: { chatId: 'C1', threadId: '' } }));
+ await flushMicrotasks();
+
+ expect(consumePendingOpenerCard).toHaveBeenCalledTimes(1);
+ expect(sendMarkdownText).toHaveBeenCalledWith('U123456789', slackUi.agent.stopDone(0), {
+ threadTs: '1234.5678',
+ });
+ });
+
+ it('slash 抛错时用内部错误收口开场白卡(sink 未被调用过)', async () => {
+ handleSlashCommand.mockRejectedValueOnce(new Error('list projects failed'));
+ consumePendingOpenerCard.mockResolvedValue(true);
+ deliver(makeEvent({ text: '/ctr', groupContextLane: { chatId: 'C1', threadId: '' } }));
+ await flushMicrotasks();
+
+ expect(consumePendingOpenerCard).toHaveBeenCalledWith(
+ 'U123456789',
+ slackUi.agent.sendInternalError('list projects failed'),
+ );
+ expect(sendMarkdownText).not.toHaveBeenCalled();
+ expect(runAgentTurn).not.toHaveBeenCalled();
+ });
+
+ it('slash 抛错且 opener 收口返回 false 时补发内部错误', async () => {
+ handleSlashCommand.mockRejectedValueOnce(new Error('list projects failed'));
+ consumePendingOpenerCard.mockResolvedValue(false);
+ deliver(makeEvent({ text: '/ctr', groupContextLane: { chatId: 'C1', threadId: '' } }));
+ await flushMicrotasks();
+
+ expect(consumePendingOpenerCard).toHaveBeenCalledWith(
+ 'U123456789',
+ slackUi.agent.sendInternalError('list projects failed'),
+ );
+ expect(sendMarkdownText).toHaveBeenCalledWith(
+ 'U123456789',
+ slackUi.agent.sendInternalError('list projects failed'),
+ { threadTs: '1234.5678' },
+ );
+ expect(runAgentTurn).not.toHaveBeenCalled();
+ });
+
+ it('runAgentTurn 抛错且本条开了话题: 用内部错误收口开场白卡', async () => {
+ runAgentTurn.mockRejectedValueOnce(new Error('provider exploded'));
+ consumePendingOpenerCard.mockResolvedValue(true);
+ deliver(makeEvent({ text: '帮我看看', groupContextLane: { chatId: 'C1', threadId: '' } }));
+ await flushMicrotasks();
+
+ expect(consumePendingOpenerCard).toHaveBeenCalledWith(
+ 'U123456789',
+ slackUi.agent.sendInternalError('provider exploded'),
+ );
+ expect(sendText).not.toHaveBeenCalled();
+ });
+
+ it('早期拒绝终态(missing_auth)经 onEarlyReject 收口开场白卡', async () => {
+ let capturedArgs: Parameters<ImTurnRunner['runAgentTurn']>[0] | undefined;
+ runAgentTurn.mockImplementationOnce(async (args: Parameters<ImTurnRunner['runAgentTurn']>[0]) => {
+ capturedArgs = args;
+ const consumed = (await args.onEarlyReject?.('missing_auth', 'AUTH_MISSING_TEXT')) ?? false;
+ expect(consumed).toBe(true);
+ });
+ consumePendingOpenerCard.mockResolvedValue(true);
+ deliver(makeEvent({ text: '帮我看看', groupContextLane: { chatId: 'C1', threadId: '' } }));
+ await flushMicrotasks();
+
+ expect(capturedArgs).toBeDefined();
+ expect(consumePendingOpenerCard).toHaveBeenCalledWith('U123456789', 'AUTH_MISSING_TEXT');
+ });
+
+ it('同话题后续 !stop 不消费上一轮的 pending opener(归属不抢占)', async () => {
+ // 消息 A 已开话题且其 pending opener 尚未被流式认领; 本条 B 是同一话题的
+ // 后续消息(groupContextLane 缺省)— B 不得 patch A 的思考卡。
+ consumePendingOpenerCard.mockResolvedValue(true);
+ deliver(makeEvent({ text: '!stop' }));
+ await flushMicrotasks();
+
+ expect(consumePendingOpenerCard).not.toHaveBeenCalled();
+ expect(sendMarkdownText).toHaveBeenCalledWith('U123456789', slackUi.agent.stopDone(0), {
+ threadTs: '1234.5678',
+ });
+ });
+
+ it('同话题后续 slash 不注入 opener sink', async () => {
+ let capturedCtx: Parameters<typeof handleSlashCommand>[1] | undefined;
+ handleSlashCommand.mockImplementation(async (_text: string, ctx: Parameters<typeof handleSlashCommand>[1]) => {
+ capturedCtx = ctx;
+ return true;
+ });
+ deliver(makeEvent({ text: '/project' }));
+ await flushMicrotasks();
+
+ expect(handleSlashCommand).toHaveBeenCalledTimes(1);
+ expect(capturedCtx?.consumePendingOpener).toBeUndefined();
+ });
+
+ it('consume patch 抛错时回落正常发送(回复不丢, 认领已完成)', async () => {
+ consumePendingOpenerCard.mockRejectedValue(new Error('patch failed'));
+ deliver(makeEvent({ groupContextLane: { chatId: 'C1', threadId: '' } }));
+ await flushMicrotasks();
+
+ expect(sendMarkdownText).toHaveBeenCalledWith('U123456789', slackUi.agent.stopDone(0), {
+ threadTs: '1234.5678',
+ });
+ expect(runAgentTurn).not.toHaveBeenCalled();
+ });
+
+ it('slash 首条注入 opener sink: 首个回复就地消费开场白卡', async () => {
+ let capturedCtx: Parameters<typeof handleSlashCommand>[1] | undefined;
+ handleSlashCommand.mockImplementation(async (_text: string, ctx: Parameters<typeof handleSlashCommand>[1]) => {
+ capturedCtx = ctx;
+ return true;
+ });
+ consumePendingOpenerCard.mockResolvedValue(true);
+ deliver(makeEvent({ text: '/project', groupContextLane: { chatId: 'C1', threadId: '' } }));
+ await flushMicrotasks();
+
+ expect(handleSlashCommand).toHaveBeenCalledTimes(1);
+ expect(runAgentTurn).not.toHaveBeenCalled();
+
+ // sink 存在且首个 withMarkdown 消费开场白卡(第二次起回落)。
+ expect(capturedCtx?.consumePendingOpener).toBeDefined();
+ await expect(capturedCtx!.consumePendingOpener!.withMarkdown('U123456789', '回复')).resolves.toBe(true);
+ expect(consumePendingOpenerCard).toHaveBeenCalledWith('U123456789', '回复');
+ await expect(capturedCtx!.consumePendingOpener!.withMarkdown('U123456789', '第二条')).resolves.toBe(false);
+ expect(consumePendingOpenerCard).toHaveBeenCalledTimes(1);
+ });
+
+ it('纯 unsupported 首条消费开场白卡: patch 提示, 不再另发', async () => {
+ consumePendingOpenerCard.mockResolvedValue(true);
+ deliver(
+ makeEvent({
+ text: '',
+ unsupported: [{ type: 'audio', label: '语音(暂不支持)' }] as IMMessageEvent['unsupported'],
+ groupContextLane: { chatId: 'C1', threadId: '' },
+ }),
+ );
+ await flushMicrotasks();
+
+ expect(consumePendingOpenerCard).toHaveBeenCalledWith(
+ 'U123456789',
+ slackUi.agent.unsupportedOnly([{ type: 'audio', label: '语音(暂不支持)' }]),
+ );
+ expect(sendText).not.toHaveBeenCalled();
+ expect(runAgentTurn).not.toHaveBeenCalled();
+ });
+
+ it('同话题后续 !stop 不消费上一轮的 pending opener(归属不抢占)', async () => {
+ // 消息 A 已开话题且其 pending opener 尚未被流式认领; 本条 B 是同一话题的
+ // 后续消息(groupContextLane 缺省)— B 不得 patch A 的思考卡。
+ consumePendingOpenerCard.mockResolvedValue(true);
+ deliver(makeEvent({ text: '!stop' }));
+ await flushMicrotasks();
+
+ expect(consumePendingOpenerCard).not.toHaveBeenCalled();
+ expect(sendMarkdownText).toHaveBeenCalledWith('U123456789', slackUi.agent.stopDone(0), {
+ threadTs: '1234.5678',
+ });
+ });
+
+ it('同话题后续 slash 不注入 opener sink', async () => {
+ let capturedCtx: Parameters<typeof handleSlashCommand>[1] | undefined;
+ handleSlashCommand.mockImplementation(async (_text: string, ctx: Parameters<typeof handleSlashCommand>[1]) => {
+ capturedCtx = ctx;
+ return true;
+ });
+ deliver(makeEvent({ text: '/project' }));
+ await flushMicrotasks();
+
+ expect(handleSlashCommand).toHaveBeenCalledTimes(1);
+ expect(capturedCtx?.consumePendingOpener).toBeUndefined();
+ });
+
+ it('同话题后续纯 unsupported 不消费上一轮的 pending opener', async () => {
+ consumePendingOpenerCard.mockResolvedValue(true);
+ deliver(
+ makeEvent({
+ text: '',
+ unsupported: [{ type: 'audio', label: '语音(暂不支持)' }] as IMMessageEvent['unsupported'],
+ }),
+ );
+ await flushMicrotasks();
+
+ expect(consumePendingOpenerCard).not.toHaveBeenCalled();
+ expect(sendText).toHaveBeenCalledTimes(1);
+ expect(runAgentTurn).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index 538965ca7e..02dbf6d0fe 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -34,6 +34,9 @@ const mocks = vi.hoisted(() => ({
patchMarkdownCard: vi.fn(),
sendInteractiveCard: vi.fn(),
updateInteractiveCard: vi.fn(),
+ consumePendingOpenerCard: vi.fn(),
+ getPendingOpenerTrigger: vi.fn(),
+ takeNotedFallbackOpenerId: vi.fn(),
},
getMaker: vi.fn(),
listProviders: vi.fn(),
@@ -419,6 +422,7 @@ interface TurnOverrides {
protectedContent?: boolean;
groupHistoryAccess?: GroupHistoryAccessScope;
prePersistedUserMessage?: { sessionId: string; clientId: string };
+ onEarlyReject?: (reason: string, text: string) => Promise<boolean> | boolean;
}
async function runDefaultTurn(onTurnComplete = vi.fn(), overrides: TurnOverrides = {}) {
@@ -441,6 +445,7 @@ async function startDefaultTurn(onTurnComplete = vi.fn(), overrides: TurnOverrid
...(overrides.prePersistedUserMessage
? { prePersistedUserMessage: overrides.prePersistedUserMessage }
: {}),
+ ...(overrides.onEarlyReject ? { onEarlyReject: overrides.onEarlyReject } : {}),
});
return { onTurnComplete, turnPromise };
}
@@ -542,6 +547,9 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
mocks.feishuIm.removeMessageReaction.mockResolvedValue(undefined);
mocks.feishuIm.sendText.mockResolvedValue(undefined);
mocks.feishuIm.sendMarkdownText.mockResolvedValue(undefined);
+ mocks.feishuIm.consumePendingOpenerCard.mockResolvedValue(false);
+ mocks.feishuIm.getPendingOpenerTrigger.mockReturnValue(undefined);
+ mocks.feishuIm.takeNotedFallbackOpenerId.mockReturnValue(undefined);
mocks.feishuIm.startStreamingText.mockResolvedValue({
messageId: 'stream-1',
append: vi.fn(),
@@ -1394,6 +1402,28 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
expect(mocks.feishuIm.sendText).toHaveBeenCalledTimes(1);
});
+ it('早期拒绝兜底发送认领暂存 opener, 避免排空后再发一份', async () => {
+ setupSession(async () => ({
+ accepted: false,
+ reason: 'cancelled-before-dispatch',
+ }));
+ mocks.feishuIm.takeNotedFallbackOpenerId.mockReturnValue('om_deferred');
+ await runDefaultTurn(vi.fn(), {
+ onEarlyReject: async () => false,
+ });
+ await flushMicrotasks();
+
+ expect(mocks.feishuIm.takeNotedFallbackOpenerId).toHaveBeenCalledWith(
+ 'ou_user',
+ 'markdown',
+ );
+ expect(mocks.feishuIm.sendText).toHaveBeenCalledWith(
+ 'ou_user',
+ expect.stringContaining('启动 agent 失败'),
+ expect.objectContaining({ fallbackOpenerId: 'om_deferred' }),
+ );
+ });
+
it('group history lease: live during the turn, released at terminal', async () => {
resetGroupHistoryAccessForTests();
const h = setupSession(async () => ({ accepted: true }));
@@ -3090,5 +3120,76 @@ describe('初始流式输出面创建失败的收口降级(#2164)', () => {
);
});
});
+
+ it('无文本输出兜底发送认领暂存 opener', async () => {
+ mocks.feishuIm.startStreamingText.mockRejectedValue(new Error('card create denied'));
+ mocks.feishuIm.getPendingOpenerTrigger.mockReturnValue('msg-user');
+ mocks.feishuIm.consumePendingOpenerCard.mockResolvedValue(false);
+ mocks.feishuIm.takeNotedFallbackOpenerId.mockReturnValue('om_deferred');
+ const h = setupSession(async () => ({ accepted: true }));
+ const onTurnComplete = vi.fn();
+ await runDefaultTurn(onTurnComplete);
+ h.emit({
+ type: 'tool_use',
+ data: { name: 'Bash', input: { command: 'ls' } },
+ source: 'claude-code',
+ });
+ await flushMicrotasks();
+ h.emit({ type: 'done', data: {}, source: 'claude-code' });
+ await waitForAssertion(() => {
+ expect(mocks.feishuIm.sendText).toHaveBeenCalledWith(
+ 'ou_user',
+ expect.stringContaining('本轮无文本输出'),
+ expect.objectContaining({ fallbackOpenerId: 'om_deferred' }),
+ );
+ });
+ });
+
+ it('错误收口兜底发送认领暂存 opener', async () => {
+ mocks.feishuIm.getPendingOpenerTrigger.mockReturnValue('msg-user');
+ mocks.feishuIm.consumePendingOpenerCard.mockResolvedValue(false);
+ mocks.feishuIm.takeNotedFallbackOpenerId.mockReturnValue('om_deferred');
+ const h = setupSession(async () => ({ accepted: true }));
+ await runDefaultTurn();
+ h.emit({ type: 'error', data: { message: 'boom', isTerminal: true } });
+ await waitForAssertion(() => {
+ expect(mocks.feishuIm.sendText).toHaveBeenCalledWith(
+ 'ou_user',
+ expect.stringMatching(/❌ 错误:.*boom/),
+ expect.objectContaining({ fallbackOpenerId: 'om_deferred' }),
+ );
+ });
+ });
+
+ it('首个文本前 error 就地消费 pending opener, 同话题下一轮无文本不会误认领', async () => {
+ mocks.feishuIm.getPendingOpenerTrigger.mockReturnValue('msg-user');
+ mocks.feishuIm.consumePendingOpenerCard.mockResolvedValueOnce(true);
+ const h = setupSession(async () => ({ accepted: true }));
+ const onTurnA = vi.fn();
+ await runDefaultTurn(onTurnA);
+ h.emit({ type: 'error', data: { message: 'boom', isTerminal: true } });
+ await waitForAssertion(() => {
+ expect(onTurnA).toHaveBeenCalledTimes(1);
+ expect(mocks.feishuIm.consumePendingOpenerCard).toHaveBeenCalledWith(
+ 'ou_user',
+ expect.stringMatching(/❌ 错误:.*boom/),
+ );
+ });
+ expect(mocks.feishuIm.sendText).not.toHaveBeenCalled();
+
+ mocks.feishuIm.getPendingOpenerTrigger.mockReturnValue(undefined);
+ const onTurnB = vi.fn();
+ await runDefaultTurn(onTurnB, { userMessageId: 'msg-user-2', text: 'followup' });
+ h.emit({ type: 'done', data: {}, source: 'claude-code' });
+ await waitForAssertion(() => {
+ expect(onTurnB).toHaveBeenCalledTimes(1);
+ expect(mocks.feishuIm.consumePendingOpenerCard).toHaveBeenCalledTimes(1);
+ expect(mocks.feishuIm.sendText).toHaveBeenCalledWith(
+ 'ou_user',
+ expect.stringContaining('本轮无文本输出'),
+ expect.anything(),
+ );
+ });
+ });
});
});
diff --git a/apps/desktop/src/main/im/shared/messageHandler.ts b/apps/desktop/src/main/im/shared/messageHandler.ts
index 0cef6ffcff..7f86dbc065 100644
--- a/apps/desktop/src/main/im/shared/messageHandler.ts
+++ b/apps/desktop/src/main/im/shared/messageHandler.ts
@@ -16,7 +16,7 @@
* 跨渠道互不影响。
*/
-import type { IMAttachment, IMMessageEvent, TextChannelIM } from '@cindy/im';
+import type { IMAttachment, IMMessageEvent, InteractiveCardSpec, TextChannelIM } from '@cindy/im';
import { createLogger } from '../../logger';
import {
@@ -46,6 +46,25 @@ export function createMessageHandler(
turnRunner: ImTurnRunner,
): (im: TextChannelIM) => () => void {
const { ui, channel, threadScoped } = adapter;
+ // 富卡渠道(仅 feishu 实现这两个能力): 群主流 @ 开话题的「思考中」开场白卡
+ // 在非流式终态分支的收口 — 见各分支内 consume/discard 调用点。
+ const richIm = adapter.output?.kind === 'rich-card' ? adapter.output.im : null;
+
+ /**
+ * 尝试消费 pending 开场白卡并把终态回复 patch 上去。消费成功返回 true
+ * (调用方跳过另发); 无 pending opener 或 patch 失败返回 false(回落正常
+ * 发送 — 失败场景下发送兜底, 且认领已完成, 同话题下一条不会再 patch 错卡)。
+ */
+ async function consumeOpenerWithText(userId: string, text: string): Promise<boolean> {
+ if (!richIm?.consumePendingOpenerCard) return false;
+ try {
+ return await richIm.consumePendingOpenerCard(userId, text);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`consumePendingOpenerCard failed (fallback to normal send): ${msg}`);
+ return false;
+ }
+ }
const log = createLogger(`im:${channel}:msg`);
/** Per-user serial lock — same shape as legacy messageRouter.turnLocks. */
@@ -154,25 +173,93 @@ export function createMessageHandler(
log.error(`stopActiveTurn threw: ${msg}`);
reply = ui.agent.sendInternalError(msg);
}
- try {
- await im.sendMarkdownText(event.senderId, reply, { threadTs: event.scopeKey });
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log.warn(`!stop reply failed (non-fatal): ${msg}`);
+ // 群主流 @ 开话题的首条若是 !stop: 「思考中」开场白卡就地 patch 成
+ // stop 回复(消费 pending opener), 不再另发一条; 消费不了再走正常发送。
+ // 仅当本条消息**自己**开了话题(groupContextLane 存在)才消费 — 同话题
+ // 后续消息 B 不得认领上一轮 A 的 pending opener, 否则 B 的终态回复会
+ // 覆盖 A 的思考卡, A 的回答另发新卡造成归属错乱。
+ const openerConsumed = event.groupContextLane
+ ? await consumeOpenerWithText(event.senderId, reply)
+ : false;
+ if (!openerConsumed) {
+ try {
+ await im.sendMarkdownText(event.senderId, reply, {
+ threadTs: event.scopeKey,
+ fallbackOpenerId: richIm?.takeNotedFallbackOpenerId?.(event.senderId, 'markdown'),
+ });
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`!stop reply failed (non-fatal): ${msg}`);
+ }
}
return;
}
// ── slash command (only on plain text: no attachments, no unsupported) ──
if (pureTextCommandInput && looksLikeSlashCommand(event.text)) {
+ // 群主流 @ 开话题的首条若是 slash: slash 自备回复(文本/卡片), 把它的
+ // **首个**回复就地消费开场白卡(patch 文本 / 替换卡片)— 卡不卡住, 也
+ // 不用撤回后拿已删消息当回复锚点。消费过一次后后续回复正常发送。
+ // 仅当本条消息**自己**开了话题(groupContextLane 存在)才注入 sink —
+ // 同话题后续 slash 不得认领上一轮的 pending opener(归属错乱, 同
+ // !stop 分支的说明)。
+ // bind 接收者: FeishuIM 方法内部访问 this.log, 裸函数引用会导致 catch
+ // 路径(撤回开场白卡)在 this=undefined 下抛错、卡残留。
+ const consumeCard = event.groupContextLane
+ ? richIm?.consumePendingOpenerCard?.bind(richIm)
+ : undefined;
+ const consumeAsCard = event.groupContextLane
+ ? richIm?.consumePendingOpenerAsCard?.bind(richIm)
+ : undefined;
+ const sink = consumeCard
+ ? {
+ used: false,
+ async withMarkdown(userId: string, markdown: string): Promise<boolean> {
+ if (this.used) return false;
+ const ok = await consumeCard(userId, markdown);
+ if (ok) this.used = true;
+ return ok;
+ },
+ async withCard(userId: string, spec: InteractiveCardSpec): Promise<boolean> {
+ if (this.used) return false;
+ const ok = (await consumeAsCard?.(userId, spec)) ?? false;
+ if (ok) this.used = true;
+ return ok;
+ },
+ }
+ : undefined;
try {
await slash.handleSlashCommand(event.text, {
botContextId: event.contextId,
userId: event.senderId,
+ consumePendingOpener: sink,
});
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`slash command threw: ${msg}`);
+ // slash 在首个回复发出前抛错(如 /ctr 枚举失败): sink 未被调用,
+ // 开场白卡用内部错误内容收口 — 否则「思考中」卡永久保留。
+ // withMarkdown 返回 false(撤回/空窗暂存)或抛错时走正常发送兜底,
+ // 与 !stop / runAgentTurn 失败分支同一口径。
+ const errorText = ui.agent.sendInternalError(msg);
+ let openerConsumed = false;
+ if (sink) {
+ try {
+ openerConsumed = await sink.withMarkdown(event.senderId, errorText);
+ } catch {
+ openerConsumed = false;
+ }
+ }
+ if (!openerConsumed) {
+ try {
+ await im.sendMarkdownText(event.senderId, errorText, {
+ threadTs: event.scopeKey,
+ fallbackOpenerId: richIm?.takeNotedFallbackOpenerId?.(event.senderId, 'markdown'),
+ });
+ } catch {
+ /* 发送失败与卡残留同一最终边界 */
+ }
+ }
}
return;
}
@@ -181,13 +268,22 @@ export function createMessageHandler(
// ── pure-unsupported: reply directly, do NOT invoke agent ───────────────
if (!hasContent && event.unsupported.length > 0) {
- try {
- await im.sendText(event.senderId, ui.agent.unsupportedOnly(event.unsupported), {
- threadTs: event.scopeKey,
- });
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log.warn(`unsupportedOnly send failed (non-fatal): ${msg}`);
+ const notice = ui.agent.unsupportedOnly(event.unsupported);
+ // 同 !stop: 开场白卡就地 patch 成 unsupported 提示, 消费不了再另发;
+ // 仅本条消息自己开了话题(groupContextLane)才消费。
+ const openerConsumed = event.groupContextLane
+ ? await consumeOpenerWithText(event.senderId, notice)
+ : false;
+ if (!openerConsumed) {
+ try {
+ await im.sendText(event.senderId, notice, {
+ threadTs: event.scopeKey,
+ fallbackOpenerId: richIm?.takeNotedFallbackOpenerId?.(event.senderId, 'markdown'),
+ });
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`unsupportedOnly send failed (non-fatal): ${msg}`);
+ }
}
return;
}
@@ -265,6 +361,16 @@ export function createMessageHandler(
...(turnPermissionPolicy ? { turnPermissionPolicy } : {}),
...(groupHistoryAccess ? { groupHistoryAccess } : {}),
...(handedOverAck !== undefined ? { ackReactionIdPromise: handedOverAck } : {}),
+ // 早期拒绝终态(missing_auth / credential busy): 本条消息自己开了话题
+ // 时, 用终态文案收口开场白卡 — 否则「思考中」卡残留且下一条误认领。
+ ...(event.groupContextLane
+ ? {
+ onEarlyReject: async (reason: string, text: string) => {
+ void reason;
+ return consumeOpenerWithText(event.senderId, text);
+ },
+ }
+ : {}),
...(prePersisted ? { prePersistedUserMessage: prePersisted } : {}),
...(prepared ? { agentText: prepared.agentText } : {}),
// 群历史附件只进模型消息、不落库(见 ImRunAgentTurnArgs.contextAttachments)。
@@ -299,12 +405,20 @@ export function createMessageHandler(
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`runAgentTurn threw: ${msg}`);
- try {
- await im.sendText(event.senderId, ui.agent.sendInternalError(msg), {
- threadTs: event.scopeKey,
- });
- } catch {
- /* swallow */
+ // 本条消息自己开了话题(groupContextLane)时, 开场白卡还没被流式认领 —
+ // 用内部错误内容收口它, 否则卡永久残留且同话题下一条会 patch 错卡。
+ const openerConsumed = event.groupContextLane
+ ? await consumeOpenerWithText(event.senderId, ui.agent.sendInternalError(msg))
+ : false;
+ if (!openerConsumed) {
+ try {
+ await im.sendText(event.senderId, ui.agent.sendInternalError(msg), {
+ threadTs: event.scopeKey,
+ fallbackOpenerId: richIm?.takeNotedFallbackOpenerId?.(event.senderId, 'markdown'),
+ });
+ } catch {
+ /* swallow */
+ }
}
}
}
diff --git a/apps/desktop/src/main/im/shared/slashCommands.ts b/apps/desktop/src/main/im/shared/slashCommands.ts
index 24b6317f82..d2e41bb4d5 100644
--- a/apps/desktop/src/main/im/shared/slashCommands.ts
+++ b/apps/desktop/src/main/im/shared/slashCommands.ts
@@ -34,7 +34,7 @@ import {
import { startThreadControlFlow } from './controlFlow';
import { enterControl } from './controlState';
import { bindingStore, executeDetach } from '../binding';
-import type { IdentityKey } from '@cindy/im';
+import type { IdentityKey, InteractiveCardSpec } from '@cindy/im';
import type { ImChannelAdapter } from './types';
import {
permissionModeCommandContext,
@@ -52,6 +52,16 @@ export function looksLikeSlashCommand(text: string): boolean {
export interface SlashCtx {
botContextId: string;
userId: string;
+ /**
+ * 群主流 @ 开话题的首条 slash 时由 messageHandler 注入: slash 的**首个**
+ * 回复(文本或卡片)就地消费开场白卡(patch 文本 / 替换卡片)而不是另发 —
+ * 「思考中」卡不会卡住, 也不会撤回后拿已删消息当回复锚点。消费过一次
+ * 后返回 false, 后续回复正常发送。
+ */
+ consumePendingOpener?: {
+ withMarkdown(userId: string, markdown: string): Promise<boolean>;
+ withCard(userId: string, spec: InteractiveCardSpec): Promise<boolean>;
+ };
}
export interface ImSlashHandlers {
@@ -80,16 +90,68 @@ export function createSlashHandlers(
* 所有 slash 反馈都走 markdown (body-only interactive card), 因为很多文案带
* **粗体** / `code` / emoji, 渠道原生 text 不渲染 markdown 标记会显示成原文。
* markdown 同样兼容纯文本: 没标记的字符串显示效果跟 text 一致。
+ *
+ * 群主流 @ 开话题的首条 slash: 首个回复经 ctx.consumePendingOpener 就地
+ * patch 开场白卡(消费过一次后回落正常发送)。
*/
- async function safeSendText(userId: string, text: string): Promise<void> {
+ async function safeSendText(ctx: SlashCtx, text: string): Promise<void> {
try {
- await im.sendMarkdownText(userId, text);
+ if (ctx.consumePendingOpener) {
+ try {
+ if (await ctx.consumePendingOpener.withMarkdown(ctx.userId, text)) return;
+ } catch (err) {
+ // patch 失败不吞回复: 认领已完成(卡不会再被误 patch), 回落正常
+ // 发送 — 用户至少收到结果。
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`consumePendingOpener withMarkdown failed (fallback to normal send): ${msg}`);
+ }
+ }
+ const fallbackOpenerId = richIm?.takeNotedFallbackOpenerId?.(ctx.userId, 'markdown');
+ if (fallbackOpenerId) {
+ await im.sendMarkdownText(ctx.userId, text, { fallbackOpenerId });
+ } else {
+ await im.sendMarkdownText(ctx.userId, text);
+ }
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.warn(`safeSendText failed (non-fatal): ${msg}`);
}
}
+ /**
+ * 卡片反馈: 首条经 consumePendingOpener 替换开场白卡, 替换失败回落正常发卡。
+ * 返回是否送达(替换成功或发卡成功)— /ctr 等依赖「卡片确实可见」的调用方
+ * 据此决定是否进入控制态。
+ */
+ async function safeSendCard(ctx: SlashCtx, spec: InteractiveCardSpec): Promise<boolean> {
+ try {
+ if (ctx.consumePendingOpener) {
+ try {
+ if (await ctx.consumePendingOpener.withCard(ctx.userId, spec)) return true;
+ } catch (err) {
+ // 替换失败回落正常发卡: 认领已完成, 用户至少拿到一张可用卡片。
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`consumePendingOpener withCard failed (fallback to normal send): ${msg}`);
+ }
+ }
+ if (!richIm) {
+ log.warn('safeSendCard failed: channel has no rich-card output');
+ return false;
+ }
+ const fallbackOpenerId = richIm.takeNotedFallbackOpenerId?.(ctx.userId, 'spec');
+ if (fallbackOpenerId) {
+ await richIm.sendInteractiveCard(ctx.userId, spec, { fallbackOpenerId });
+ } else {
+ await richIm.sendInteractiveCard(ctx.userId, spec);
+ }
+ return true;
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`safeSendCard failed (non-fatal): ${msg}`);
+ return false;
+ }
+ }
+
/**
* 工作区显示名。
*
@@ -141,7 +203,7 @@ export function createSlashHandlers(
)
) {
await safeSendText(
- ctx.userId,
+ ctx,
ui.slash.interactiveCommandUnsupported?.(cmd) ?? ui.slash.unknownCommand(cmd),
);
return true;
@@ -149,17 +211,17 @@ export function createSlashHandlers(
switch (cmd) {
case '/help':
- await safeSendText(ctx.userId, ui.slash.help);
+ await safeSendText(ctx, ui.slash.help);
return true;
case '/start': {
// Telegram 私聊首次交互必发 /start(START 按钮) — 有欢迎语的渠道回
// 欢迎语, 其它渠道走未知命令提示。
if (ui.slash.start) {
- await safeSendText(ctx.userId, ui.slash.start);
+ await safeSendText(ctx, ui.slash.start);
return true;
}
- await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
+ await safeSendText(ctx, ui.slash.unknownCommand(cmd));
return true;
}
@@ -178,21 +240,21 @@ export function createSlashHandlers(
log.error(`/stop stopActiveTurn threw: ${msg}`);
reply = ui.agent.sendInternalError(msg);
}
- await safeSendText(ctx.userId, reply);
+ await safeSendText(ctx, reply);
return true;
}
case '/new': {
// thread = session 模型: 发新顶层消息即新会话, /new 无意义 → 废弃提示。
if (threadScoped && threadUi) {
- await safeSendText(ctx.userId, threadUi.newDeprecated);
+ await safeSendText(ctx, threadUi.newDeprecated);
return true;
}
const prepared = await repo.prepareNewSession(ctx.botContextId, ctx.userId);
const auth = await turnRunner.getAuthStatusForRoute?.(prepared);
if (auth ? !auth.ok : !(await turnRunner.hasAuthForRoute(prepared))) {
await safeSendText(
- ctx.userId,
+ ctx,
auth && ui.agent.authMissing
? ui.agent.authMissing({
...auth,
@@ -211,24 +273,24 @@ export function createSlashHandlers(
await resetSessionToDefaults(row.id, adapter.config, prepared, adapter.channel);
}
await turnRunner.disposeOneSession(row.id);
- await safeSendText(ctx.userId, ui.slash.new);
+ await safeSendText(ctx, ui.slash.new);
return true;
}
case '/model': {
if (!richIm) {
- await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
+ await safeSendText(ctx, ui.slash.unknownCommand(cmd));
return true;
}
// thread 模型: slash 命令不携带 thread 上下文(Slack 平台限制), 无法定位
// 目标 thread/session;不拦的话 resolveRouteTarget 会误建空 scope session。
if (threadScoped && threadUi) {
- await safeSendText(ctx.userId, threadUi.perThreadConfigUnsupported);
+ await safeSendText(ctx, threadUi.perThreadConfigUnsupported);
return true;
}
const target = await turnRunner.resolveRouteTarget(ctx.botContextId, ctx.userId);
if (!target) {
- await safeSendText(ctx.userId, ui.agent.apiKeyMissing);
+ await safeSendText(ctx, ui.agent.apiKeyMissing);
return true;
}
const { row } = target;
@@ -268,7 +330,7 @@ export function createSlashHandlers(
: undefined,
});
try {
- await richIm.sendInteractiveCard(ctx.userId, spec);
+ await safeSendCard(ctx, spec);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`/model card send failed: ${msg}`);
@@ -282,7 +344,7 @@ export function createSlashHandlers(
if (threadScoped && threadUi) {
const all = bindingStore.listByIdentity(channel, ctx.botContextId, ctx.userId);
if (all.length === 0) {
- await safeSendText(ctx.userId, threadUi.exctrNothing);
+ await safeSendText(ctx, threadUi.exctrNothing);
return true;
}
let detached = 0;
@@ -295,7 +357,7 @@ export function createSlashHandlers(
log.error(`${invocation} executeDetach(scope) threw: ${msg}`);
}
}
- await safeSendText(ctx.userId, threadUi.exctrAllDone(detached));
+ await safeSendText(ctx, threadUi.exctrAllDone(detached));
return true;
}
// 结束当前 (bot, owner) 的接管, 让后续消息回到渠道默认 session。
@@ -309,21 +371,21 @@ export function createSlashHandlers(
try {
const result = await executeDetach(identity, `${channel}-slash`);
if (!result.wasAttached) {
- await safeSendText(ctx.userId, ui.slash.notAttached);
+ await safeSendText(ctx, ui.slash.notAttached);
} else {
- await safeSendText(ctx.userId, ui.slash.detachedBySlash);
+ await safeSendText(ctx, ui.slash.detachedBySlash);
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`${invocation} executeDetach threw: ${msg}`);
- await safeSendText(ctx.userId, `❌ 结束接管失败:${msg}`);
+ await safeSendText(ctx, `❌ 结束接管失败:${msg}`);
}
return true;
}
case '/ctr': {
if (!richIm) {
- await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
+ await safeSendText(ctx, ui.slash.unknownCommand(cmd));
return true;
}
// ── thread 模型: 整个选择流程在"接管锚点卡"的 thread 里进行 ────────
@@ -364,12 +426,11 @@ export function createSlashHandlers(
projects,
currentAttachedTitle,
});
- try {
- await richIm.sendInteractiveCard(ctx.userId, spec);
+ const sent = await safeSendCard(ctx, spec);
+ if (sent) {
enterControl(ctx.botContextId, ctx.userId);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log.error(`/ctr card send failed: ${msg}`);
+ } else {
+ log.error('/ctr picker card send failed — control NOT entered (avoid locking the user)');
}
return true;
}
@@ -379,7 +440,7 @@ export function createSlashHandlers(
// 才放行; 选中走 control:session-pick 接管路径。
const recentUi = ui.cards.control.recentSessions;
if (!richIm || !recentUi) {
- await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
+ await safeSendText(ctx, ui.slash.unknownCommand(cmd));
return true;
}
const recent = await listRecentSessionsForPicker();
@@ -388,7 +449,7 @@ export function createSlashHandlers(
sessions: recent,
});
try {
- await richIm.sendInteractiveCard(ctx.userId, spec);
+ await safeSendCard(ctx, spec);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`/session card send failed: ${msg}`);
@@ -401,7 +462,7 @@ export function createSlashHandlers(
// 未知命令处理, 不暴露半成品入口。
const projectUi = ui.cards.project;
if (!richIm || !adapter.projectSwitching || !projectUi) {
- await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
+ await safeSendText(ctx, ui.slash.unknownCommand(cmd));
return true;
}
// /ctr 接管期间语义冲突(消息在被接管的 desktop 会话里跑): 先 /exctr。
@@ -411,7 +472,7 @@ export function createSlashHandlers(
userId: ctx.userId,
};
if (bindingStore.get(identity)) {
- await safeSendText(ctx.userId, projectUi.attachedUnsupported);
+ await safeSendText(ctx, projectUi.attachedUnsupported);
return true;
}
const [projects, current] = await Promise.all([
@@ -429,7 +490,7 @@ export function createSlashHandlers(
currentName,
});
try {
- await richIm.sendInteractiveCard(ctx.userId, spec);
+ await safeSendCard(ctx, spec);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`/project card send failed: ${msg}`);
@@ -441,11 +502,11 @@ export function createSlashHandlers(
// 只读总览 —— 不改任何配置, 所以不需要富卡, 纯文本渠道也照常可用。
const render = ui.slash.settings;
if (!render) {
- await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
+ await safeSendText(ctx, ui.slash.unknownCommand(cmd));
return true;
}
if (threadScoped && threadUi) {
- await safeSendText(ctx.userId, threadUi.perThreadConfigUnsupported);
+ await safeSendText(ctx, threadUi.perThreadConfigUnsupported);
return true;
}
// /ctr 接管期间, 下一条消息跑在**被接管的 desktop 会话**里 —— /model、
@@ -478,7 +539,7 @@ export function createSlashHandlers(
effective.workspaceKind,
);
await safeSendText(
- ctx.userId,
+ ctx,
render({
workspace,
agent: effective.agentKind,
@@ -492,12 +553,12 @@ export function createSlashHandlers(
case '/permission': {
if (threadScoped && threadUi) {
- await safeSendText(ctx.userId, threadUi.perThreadConfigUnsupported);
+ await safeSendText(ctx, threadUi.perThreadConfigUnsupported);
return true;
}
const target = await turnRunner.resolveRouteTarget(ctx.botContextId, ctx.userId);
if (!target) {
- await safeSendText(ctx.userId, ui.agent.apiKeyMissing);
+ await safeSendText(ctx, ui.agent.apiKeyMissing);
return true;
}
const { row } = target;
@@ -509,12 +570,12 @@ export function createSlashHandlers(
if (!richIm) {
const requested = commandArgs[0];
if (!requested) {
- await safeSendText(ctx.userId, renderTextPermissionModePicker(ui, context));
+ await safeSendText(ctx, renderTextPermissionModePicker(ui, context));
return true;
}
const mode = resolvePermissionMode(context.modes, requested);
if (!mode) {
- await safeSendText(ctx.userId, renderTextPermissionModePicker(ui, context));
+ await safeSendText(ctx, renderTextPermissionModePicker(ui, context));
return true;
}
const confirmedFullAccess = ['confirm', '确认'].includes(commandArgs[1]?.toLowerCase());
@@ -524,7 +585,7 @@ export function createSlashHandlers(
modes: context.modes,
confirmedFullAccess,
});
- await safeSendText(ctx.userId, renderTextPermissionModeResult(ui, result));
+ await safeSendText(ctx, renderTextPermissionModeResult(ui, result));
return true;
}
const spec = cards.buildPermissionModePickerCard({
@@ -534,7 +595,7 @@ export function createSlashHandlers(
currentMode: row.permissionMode,
});
try {
- await richIm.sendInteractiveCard(ctx.userId, spec);
+ await safeSendCard(ctx, spec);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`/permission card send failed: ${msg}`);
@@ -543,7 +604,7 @@ export function createSlashHandlers(
}
default:
- await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
+ await safeSendText(ctx, ui.slash.unknownCommand(cmd));
return true;
}
}
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 9c90c5a8d8..8006d68c56 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -263,6 +263,8 @@ interface QueuedSend {
/** 触发消息来自受保护群 —— 正文与附件不进会话存档(见 ImRunAgentTurnArgs)。 */
protectedContent?: boolean;
groupHistoryAccess?: GroupHistoryAccessScope;
+ /** 早期拒绝终态回调(见 ImRunAgentTurnArgs.onEarlyReject)。 */
+ onEarlyReject?: (reason: string, text: string) => Promise<boolean> | boolean;
/** 调用方在拼群上下文之前已落库的 user 行(见 ImRunAgentTurnArgs 同名字段)。 */
prePersistedUserMessage?: { sessionId: string; clientId: string };
}
@@ -403,6 +405,13 @@ export interface ImRunAgentTurnArgs {
* 重置), 那时这份预落库对不上号, dispatch 必须照常自己落一条。
*/
prePersistedUserMessage?: { sessionId: string; clientId: string };
+ /**
+ * 早期拒绝终态(missing_auth / credential_mode_switch 等正常 resolve 的
+ * reject/busy)回调 — turnRunner 把本要另发的终态文案交给调用方: 返回
+ * true 表示已消费(如群主流 @ 开话题时 patch 开场白卡), turnRunner 跳过
+ * 自己的发送; false/缺省则照常发送。
+ */
+ onEarlyReject?(reason: string, text: string): Promise<boolean> | boolean;
}
export interface ImTurnTerminal {
@@ -511,6 +520,19 @@ export function createTurnRunner(
): ImTurnRunner {
const { im, output, ui, channel } = adapter;
const richIm = output.kind === 'rich-card' ? output.im : null;
+
+ function sendTextClaimingOpener(
+ userId: string,
+ text: string,
+ threadTs: string | undefined,
+ ): Promise<{ messageId: string }> {
+ const fallbackOpenerId = richIm?.takeNotedFallbackOpenerId?.(userId, 'markdown');
+ return im.sendText(userId, text, {
+ threadTs,
+ ...(fallbackOpenerId ? { fallbackOpenerId } : {}),
+ });
+ }
+
/** 过程区耗时显示的低频刷新(5s)— 单个长工具调用期间状态行不冻结。 */
const ACTIVITY_TICK_MS = 5_000;
@@ -669,7 +691,11 @@ export function createTurnRunner(
const created = await createAuthenticatedDefaultRouteTarget(botContextId, userId, scopeKey);
if (!created.target) {
if (args.queueMode === 'internal') {
- await replyMissingAuth(userId, created.missingAuth, scopeKey);
+ const text =
+ ui.agent.authMissing?.({ ...created.missingAuth, attached: false }) ??
+ ui.agent.apiKeyMissing;
+ const consumed = (await args.onEarlyReject?.('missing_auth', text)) ?? false;
+ if (!consumed) await replyMissingAuth(userId, created.missingAuth, scopeKey);
}
await discardHandedOverAck(userMessageId, args.ackReactionIdPromise);
return { kind: 'rejected', reason: 'missing_auth' };
@@ -681,12 +707,14 @@ export function createTurnRunner(
const auth = await checkImRouteAuthDetailed(row, undefined, authCheckDeps());
if (!auth.ok) {
if (args.queueMode === 'internal') {
- await replyMissingAuth(
- userId,
- { ...auth, agentKind: row.agentKind, model: row.model },
- scopeKey,
- target.attached,
- );
+ const authStatus = { ...auth, agentKind: row.agentKind, model: row.model };
+ const text =
+ ui.agent.authMissing?.({ ...authStatus, attached: target.attached }) ??
+ ui.agent.apiKeyMissing;
+ const consumed = (await args.onEarlyReject?.('missing_auth', text)) ?? false;
+ if (!consumed) {
+ await replyMissingAuth(userId, authStatus, scopeKey, target.attached);
+ }
}
await discardHandedOverAck(userMessageId, args.ackReactionIdPromise);
return { kind: 'rejected', reason: 'missing_auth' };
@@ -775,7 +803,12 @@ export function createTurnRunner(
} catch (err) {
if (isCredentialModeSwitchBusyError(err)) {
if (args.queueMode === 'internal') {
- await handleSessionWiringBusy(userId, turn);
+ const consumed = (await args.onEarlyReject?.('credential_mode_switch', ui.agent.credentialBusy)) ?? false;
+ if (!consumed) {
+ await handleSessionWiringBusy(userId, turn);
+ } else {
+ await completeTurnCallbackAfterAck(turn);
+ }
} else {
await completeTurnCallbackAfterAck(turn);
}
@@ -853,6 +886,7 @@ export function createTurnRunner(
...(args.beforeProviderStart ? { beforeProviderStart: args.beforeProviderStart } : {}),
...(args.onRouteResolved ? { onRouteResolved: args.onRouteResolved } : {}),
...(args.turnPermissionPolicy ? { turnPermissionPolicy: args.turnPermissionPolicy } : {}),
+ ...(args.onEarlyReject ? { onEarlyReject: args.onEarlyReject } : {}),
...(args.protectedContent === true ? { protectedContent: true } : {}),
...(args.groupHistoryAccess ? { groupHistoryAccess: args.groupHistoryAccess } : {}),
...(args.prePersistedUserMessage
@@ -1143,6 +1177,7 @@ export function createTurnRunner(
source: outcome.source,
reason: outcome.reason,
context: outcome.context,
+ onEarlyReject: item.onEarlyReject,
});
return { kind: 'rejected', reason: outcome.reason };
}
@@ -1168,6 +1203,7 @@ export function createTurnRunner(
source: `${channel}-runner`,
reason: turnPolicyFailureReason,
context: buildSendContext(rowId),
+ onEarlyReject: item.onEarlyReject,
});
return { kind: 'rejected', reason: turnPolicyFailureReason };
}
@@ -1216,6 +1252,7 @@ export function createTurnRunner(
reason: normalized.reason,
context: buildSendContext(rowId),
error: normalized.error,
+ onEarlyReject: item.onEarlyReject,
});
return { kind: 'rejected', reason: normalized.reason };
} finally {
@@ -2474,6 +2511,7 @@ export function createTurnRunner(
reason: string;
context: string;
error?: SanitizedSendOutcomeError;
+ onEarlyReject?: (reason: string, text: string) => Promise<boolean> | boolean;
},
): Promise<void> {
log.error(`${channel} session send failed before dispatch`, {
@@ -2511,21 +2549,25 @@ export function createTurnRunner(
? unsupportedCopy(rejectedMode)
: unsupportedCopy
: `❌ 启动 agent 失败:${failure.reason}`;
- if (
- output.kind === 'chunked-text' &&
- failure.turn.chunkedReplyBegun
- ) {
- await output.commitFinal({
- userId,
- text: message,
- terminal: 'error',
- threadTs: state.scopeKey,
- errorCode: failure.reason,
- });
- } else {
- await im.sendText(userId, message, {
- threadTs: state.scopeKey,
- });
+ // 早期拒绝终态交调用方消费(群主流 @ 开话题时 patch 开场白卡),
+ // 消费了就不再另发。
+ const consumed =
+ (await failure.onEarlyReject?.(failure.reason, message)) ?? false;
+ if (!consumed) {
+ if (
+ output.kind === 'chunked-text' &&
+ failure.turn.chunkedReplyBegun
+ ) {
+ await output.commitFinal({
+ userId,
+ text: message,
+ terminal: 'error',
+ threadTs: state.scopeKey,
+ errorCode: failure.reason,
+ });
+ } else {
+ await sendTextClaimingOpener(userId, message, state.scopeKey);
+ }
}
// 群会话「完全访问」档被强确认策略拒绝: 报错文案之外, 再给 owner
// 私聊发一张一键修复卡(切回 auto)。只对提供 permissionModeFix 文案
@@ -2823,9 +2865,19 @@ export function createTurnRunner(
...(turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : {}),
});
} else {
- await output.im.sendText(userId, '✅ (本轮无文本输出)', {
- threadTs: state.scopeKey,
- });
+ // 群主流 @ 开话题但本轮无流式输出: pending opener 尚未被认领 —
+ // 仅当 opener 是本轮消息创建的(trigger 匹配)才消费, 否则另发
+ // (避免消费上一轮遗留的 opener 造成归属错乱)。
+ const triggerId = output.im.getPendingOpenerTrigger?.(userId);
+ const isMyOpener = triggerId === turn.userMessageId;
+ const consumed =
+ isMyOpener
+ ? ((await output.im.consumePendingOpenerCard?.(userId, '✅ (本轮无文本输出)')) ??
+ false)
+ : false;
+ if (!consumed) {
+ await sendTextClaimingOpener(userId, '✅ (本轮无文本输出)', state.scopeKey);
+ }
}
} catch {
/* swallow */
@@ -2929,9 +2981,16 @@ export function createTurnRunner(
...(turn && turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : {}),
});
} else {
- await output.im.sendText(userId, `❌ 错误:${msg}`, {
- threadTs: state.scopeKey,
- });
+ const errorText = `❌ 错误:${msg}`;
+ const triggerId = output.im.getPendingOpenerTrigger?.(userId);
+ const isMyOpener = triggerId === turn?.userMessageId;
+ const consumed =
+ isMyOpener
+ ? ((await output.im.consumePendingOpenerCard?.(userId, errorText)) ?? false)
+ : false;
+ if (!consumed) {
+ await sendTextClaimingOpener(userId, errorText, state.scopeKey);
+ }
}
} catch {
/* swallow */
diff --git a/packages/lizi-im/src/channelIM.ts b/packages/lizi-im/src/channelIM.ts
index c05620d020..b8ef7783b4 100644
--- a/packages/lizi-im/src/channelIM.ts
+++ b/packages/lizi-im/src/channelIM.ts
@@ -43,14 +43,14 @@ export interface TextChannelIM {
sendText(
userId: string,
text: string,
- opts?: { threadTs?: string },
+ opts?: { threadTs?: string; fallbackOpenerId?: string },
): Promise<{ messageId: string }>;
/** 渲染 markdown 的文本消息(粗体 / 行内 code / 链接等)。 */
sendMarkdownText(
userId: string,
markdown: string,
- opts?: { threadTs?: string },
+ opts?: { threadTs?: string; fallbackOpenerId?: string },
): Promise<{ messageId: string }>;
/** 发送本地文件;失败原因见 SendFileResult.reason。 */
@@ -87,6 +87,8 @@ export interface RichChannelIM extends TextChannelIM {
spec: InteractiveCardSpec,
opts?: {
threadTs?: string;
+ /** 原兜底发送认领本轮暂存 opener, 后续发送不要传。 */
+ fallbackOpenerId?: string;
/**
* **只有授权类(permission)卡片**可以传 true: 群 lane 里把卡片改投宿主私聊 ——
* 群里的授权卡消不掉, 而且只有宿主本人能回答它。
@@ -133,6 +135,35 @@ export interface RichChannelIM extends TextChannelIM {
* 变成 thread root 的 scopeKey, 而不泄漏渠道 messageId 编码格式。
*/
threadKeyForMessage?(messageId: string): string;
+
+ /**
+ * 群主流 @ 开话题的「思考中」开场白卡被非流式终态(!stop / 纯 unsupported
+ * 等)截流时, 编排层用本方法消费: 认领该 lane 的 pending opener 并把 markdown
+ * patch 上去(开场白卡就地变成回复, 替代另发一条), 返回 true; 无 pending
+ * opener 返回 false, 调用方走正常发送。仅 feishu 实现。
+ */
+ consumePendingOpenerCard?(userId: string, markdown: string): Promise<boolean>;
+
+ /**
+ * 同上场景但终态内容是一张卡片(slash 的 /ctr picker、/model 选择卡等):
+ * 认领 pending opener 并把卡片 spec 原地替换上去(开场白卡就地变成该卡),
+ * 返回 true; 无 pending opener 返回 false, 调用方走正常发卡。仅 feishu
+ * 实现。
+ */
+ consumePendingOpenerAsCard?(userId: string, spec: InteractiveCardSpec): Promise<boolean>;
+
+ /**
+ * 返回该 lane 上 pending opener 的触发消息 id(没有则返回 undefined)。
+ * 调用方用它判断「这张思考卡是不是本轮消息创建的」— 空文本终态等场景下
+ * 不应消费上一轮遗留的 opener。
+ */
+ getPendingOpenerTrigger?(userId: string): string | undefined;
+
+ /**
+ * consume 在空窗暂存后, 原兜底发送领取本轮 openerId, 再经 send* 的
+ * fallbackOpenerId 认领排空结果。后续发送不要调用, 否则会领走别人的轮次。
+ */
+ takeNotedFallbackOpenerId?(userId: string, kind: 'markdown' | 'spec'): string | undefined;
}
/** Backward-compatible name for the existing rich-card channel contract. */
diff --git a/packages/lizi-im/src/feishu/__tests__/feishuOpenerConsume.test.ts b/packages/lizi-im/src/feishu/__tests__/feishuOpenerConsume.test.ts
new file mode 100644
index 0000000000..7ab1eda29b
--- /dev/null
+++ b/packages/lizi-im/src/feishu/__tests__/feishuOpenerConsume.test.ts
@@ -0,0 +1,653 @@
+/**
+ * FeishuIM 开场白卡消费(consumePendingOpenerCard / consumePendingOpenerAsCard)
+ * 的失败语义: patch/替换失败时认领已完成 — 撤回开场白卡(不让「思考中」卡
+ * 永久残留)并返回 false 让编排层回落正常发送。
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { IMHost } from '../../types.js';
+
+const fakeClient = { fake: 'client' };
+
+const outboundMocks = vi.hoisted(() => ({
+ claimPatchableOpener: vi.fn<() => string | null>(() => null),
+ getBoundClient: vi.fn<() => { fake: string } | null>(() => ({ fake: 'client' })),
+ recallOwnMessageWith: vi.fn(async () => true),
+ updateInteractive: vi.fn(async () => undefined),
+ registerCardLane: vi.fn(),
+ rearmAnchorToTrigger: vi.fn(() => true),
+ deferOpenerConsume: vi.fn(),
+ sendInteractive: vi.fn(async () => ({ messageId: 'om_sent' })),
+ drainDeferredOpenerConsumes: vi.fn<
+ () => Array<{
+ userId: string;
+ openerId: string;
+ markdown?: string;
+ spec?: { body: string; buttons: unknown[] };
+ }>
+ >(() => []),
+ takeMatchingDeferredOpenerConsume: vi.fn<
+ () =>
+ | ({
+ userId: string;
+ openerId: string;
+ markdown?: string;
+ spec?: { body: string; buttons: unknown[] };
+ } & { epoch: number })
+ | undefined
+ >(() => undefined),
+ takeDeferredOpenerConsumeById: vi.fn<
+ (openerId: string) =>
+ | ({
+ userId: string;
+ openerId: string;
+ markdown?: string;
+ spec?: { body: string; buttons: unknown[] };
+ } & { epoch: number })
+ | undefined
+ >(() => undefined),
+ drainEvictedOpeners: vi.fn(() => []),
+ getAccountEpoch: vi.fn(() => 0),
+ recallOwnMessage: vi.fn(async () => true),
+ sendText: vi.fn(async () => ({ messageId: 'om_sent' })),
+ getOpenerTrigger: vi.fn(() => undefined),
+}));
+
+vi.mock('../outbound.js', () => ({
+ claimPatchableOpener: outboundMocks.claimPatchableOpener,
+ getBoundClient: outboundMocks.getBoundClient,
+ recallOwnMessageWith: outboundMocks.recallOwnMessageWith,
+ recallOwnMessage: outboundMocks.recallOwnMessage,
+ updateInteractive: outboundMocks.updateInteractive,
+ registerCardLane: outboundMocks.registerCardLane,
+ rearmAnchorToTrigger: outboundMocks.rearmAnchorToTrigger,
+ deferOpenerConsume: outboundMocks.deferOpenerConsume,
+ drainDeferredOpenerConsumes: outboundMocks.drainDeferredOpenerConsumes,
+ takeMatchingDeferredOpenerConsume: outboundMocks.takeMatchingDeferredOpenerConsume,
+ takeDeferredOpenerConsumeById: outboundMocks.takeDeferredOpenerConsumeById,
+ drainEvictedOpeners: outboundMocks.drainEvictedOpeners,
+ getAccountEpoch: outboundMocks.getAccountEpoch,
+ sendInteractive: outboundMocks.sendInteractive,
+ sendText: outboundMocks.sendText,
+ getOpenerTrigger: outboundMocks.getOpenerTrigger,
+}));
+
+vi.mock('../streamingText.js', () => ({
+ patchMarkdown: vi.fn(async () => undefined),
+}));
+
+vi.mock('../wsClient.js', () => ({
+ QUIT_OFFLINE_ANNOUNCE_TIMEOUT_MS: 4500,
+ getCurrentStatus: () => 'idle',
+ getCurrentBotAppId: () => null,
+ setLifecycleAnnouncement: vi.fn(),
+ stop: vi.fn(async () => undefined),
+ start: vi.fn(async () => 'connected' as const),
+}));
+
+vi.mock('../storage.js', () => ({
+ readCredentials: () => null,
+ readOwnerOpenId: () => null,
+ readLifecycleAnnouncement: () => true,
+ writeLifecycleAnnouncement: vi.fn(),
+ writeCredentials: vi.fn(),
+ writeOwnerOpenId: vi.fn(),
+ clearAll: vi.fn(),
+}));
+
+vi.mock('../ownerGuard.js', () => ({
+ loadFromDisk: vi.fn(),
+ firstAllowed: () => null,
+ clear: vi.fn(),
+}));
+
+vi.mock('../appRegistration.js', () => ({
+ requestAppRegistration: vi.fn(),
+ pollAppRegistration: vi.fn(),
+}));
+
+vi.mock('../moduleScope.js', () => ({
+ getLog: () => ({
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ fatal: vi.fn(),
+ }),
+ setHost: vi.fn(),
+}));
+
+import { FeishuIM } from '../index.js';
+import { feishuEvents } from '../events.js';
+import * as streamingText from '../streamingText.js';
+
+let im: FeishuIM;
+
+const SPEC = { body: 'picker', buttons: [] };
+
+describe('FeishuIM opener consumption failure semantics', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ im = new FeishuIM({} as unknown as IMHost);
+ outboundMocks.drainDeferredOpenerConsumes.mockReset();
+ outboundMocks.drainDeferredOpenerConsumes.mockReturnValue([]);
+ outboundMocks.takeMatchingDeferredOpenerConsume.mockReset();
+ outboundMocks.takeMatchingDeferredOpenerConsume.mockReturnValue(undefined);
+ outboundMocks.takeDeferredOpenerConsumeById.mockReset();
+ outboundMocks.takeDeferredOpenerConsumeById.mockReturnValue(undefined);
+ outboundMocks.drainEvictedOpeners.mockReset();
+ outboundMocks.drainEvictedOpeners.mockReturnValue([]);
+ outboundMocks.getAccountEpoch.mockReset();
+ outboundMocks.getAccountEpoch.mockReturnValue(0);
+ outboundMocks.sendInteractive.mockReset();
+ outboundMocks.sendInteractive.mockResolvedValue({ messageId: 'om_sent' });
+ outboundMocks.sendText.mockReset();
+ outboundMocks.sendText.mockResolvedValue({ messageId: 'om_sent' });
+ outboundMocks.deferOpenerConsume.mockReset();
+ outboundMocks.recallOwnMessageWith.mockReset();
+ outboundMocks.recallOwnMessageWith.mockResolvedValue(true);
+ outboundMocks.updateInteractive.mockReset();
+ outboundMocks.updateInteractive.mockResolvedValue(undefined);
+ outboundMocks.registerCardLane.mockReset();
+ outboundMocks.rearmAnchorToTrigger.mockReset();
+ outboundMocks.rearmAnchorToTrigger.mockReturnValue(true);
+ outboundMocks.claimPatchableOpener.mockReset();
+ outboundMocks.claimPatchableOpener.mockReturnValue(null);
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockReset();
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
+ // 默认有绑定 client — 个别用例覆盖为 null, 不能泄漏到后续用例。
+ outboundMocks.getBoundClient.mockReturnValue({ fake: 'client' });
+ });
+
+ afterEach(async () => {
+ await im.dispose();
+ vi.useRealTimers();
+ });
+
+ async function queueOriginalFallback(openerId: string, markdown: string): Promise<void> {
+ outboundMocks.getBoundClient.mockReturnValue(null);
+ outboundMocks.claimPatchableOpener.mockReturnValue(openerId);
+ await im.consumePendingOpenerCard('g/oc_c/omt_t', markdown);
+ outboundMocks.getBoundClient.mockReturnValue({ fake: 'client' });
+ }
+
+ async function sendOriginalFallback(
+ userId: string,
+ text: string,
+ ): Promise<{ messageId: string }> {
+ const fallbackOpenerId = im.takeNotedFallbackOpenerId(userId, 'markdown');
+ return im.sendText(userId, text, { fallbackOpenerId });
+ }
+
+ it('兜底发送就地收口撤回失败不另发, 重新暂存', async () => {
+ await queueOriginalFallback('om_reserved', '终态');
+ outboundMocks.takeDeferredOpenerConsumeById.mockReturnValueOnce({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_reserved',
+ markdown: '终态',
+ epoch: 0,
+ });
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error('patch failed'),
+ );
+ outboundMocks.recallOwnMessageWith.mockResolvedValueOnce(false);
+
+ await expect(sendOriginalFallback('g/oc_c/omt_t', '兜底')).rejects.toThrow('patch failed');
+ expect(outboundMocks.recallOwnMessageWith).toHaveBeenCalled();
+ expect(outboundMocks.rearmAnchorToTrigger).not.toHaveBeenCalled();
+ expect(outboundMocks.sendText).not.toHaveBeenCalled();
+ expect(outboundMocks.deferOpenerConsume).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_reserved',
+ markdown: '终态',
+ }),
+ );
+ });
+
+ it('同账号未换代时最终发送失败也重新暂存, 进入退避排空', async () => {
+ await queueOriginalFallback('om_reserved', '终态');
+ outboundMocks.takeDeferredOpenerConsumeById.mockReturnValueOnce({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_reserved',
+ markdown: '终态',
+ epoch: 0,
+ });
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error('rate limited'),
+ );
+ outboundMocks.sendText.mockRejectedValueOnce(new Error('rate limited'));
+
+ await expect(sendOriginalFallback('g/oc_c/omt_t', '兜底')).rejects.toThrow('rate limited');
+ expect(outboundMocks.recallOwnMessageWith).toHaveBeenCalled();
+ expect(outboundMocks.deferOpenerConsume).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_reserved',
+ markdown: '终态',
+ }),
+ );
+ });
+
+ it('排空时撤回失败不补发终态, 重新入队', async () => {
+ const pinned = { fake: 'pinned-client' };
+ outboundMocks.getBoundClient.mockReturnValue(pinned);
+ outboundMocks.drainDeferredOpenerConsumes.mockReturnValueOnce([
+ { userId: 'g/oc_c/omt_t', openerId: 'om_opener', markdown: '兜底回复' },
+ ]);
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error('patch failed'),
+ );
+ outboundMocks.recallOwnMessageWith.mockResolvedValueOnce(false);
+
+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(outboundMocks.recallOwnMessageWith).toHaveBeenCalledWith(pinned, 'om_opener');
+ expect(outboundMocks.rearmAnchorToTrigger).not.toHaveBeenCalled();
+ expect(outboundMocks.sendInteractive).not.toHaveBeenCalled();
+ expect(outboundMocks.deferOpenerConsume).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_opener',
+ markdown: '兜底回复',
+ }),
+ );
+ });
+
+ it('排空时 patch 失败: 撤回 pin 到排空开始的 client 并补发终态兜底', async () => {
+ const pinned = { fake: 'pinned-client' };
+ outboundMocks.getBoundClient.mockReturnValue(pinned);
+ outboundMocks.drainDeferredOpenerConsumes.mockReturnValueOnce([
+ { userId: 'g/oc_c/omt_t', openerId: 'om_opener', markdown: '兜底回复' },
+ ]);
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error('patch failed'),
+ );
+
+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(outboundMocks.recallOwnMessageWith).toHaveBeenCalledWith(pinned, 'om_opener');
+ expect(outboundMocks.rearmAnchorToTrigger).toHaveBeenCalledWith('g/oc_c/omt_t');
+ // 补发兜底: 文本经 sendMarkdownText(sendInteractive) 正常发送。
+ expect(outboundMocks.sendInteractive).toHaveBeenCalledWith('g/oc_c/omt_t', {
+ body: '兜底回复',
+ buttons: [],
+ });
+ });
+
+ it('兜底发送就地收口预留 opener(不另发、不留思考卡)', async () => {
+ // 空窗暂存后连接恢复: 兜底发送应优先 patch 预留卡, 而不是另发。
+ await queueOriginalFallback('om_reserved', '回复');
+ outboundMocks.takeDeferredOpenerConsumeById.mockReturnValueOnce({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_reserved',
+ markdown: '回复',
+ epoch: 0,
+ });
+
+ const result = await sendOriginalFallback('g/oc_c/omt_t', '兜底');
+ expect(outboundMocks.takeDeferredOpenerConsumeById).toHaveBeenCalledWith('om_reserved');
+ expect(streamingText.patchMarkdown).toHaveBeenCalledWith('om_reserved', '回复');
+ expect(result).toEqual({ messageId: 'om_reserved' });
+ expect(outboundMocks.sendText).not.toHaveBeenCalled();
+ });
+
+ it('排空兜底发送也失败(再次重连)时重新入队, 下一次 connected 重试', async () => {
+ outboundMocks.drainDeferredOpenerConsumes.mockReturnValueOnce([
+ { userId: 'g/oc_c/omt_t', openerId: 'om_opener', markdown: '终态' },
+ ]);
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error('patch failed'),
+ );
+ outboundMocks.sendInteractive.mockRejectedValueOnce(new Error('client unbound again'));
+
+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });
+ for (let i = 0; i < 12; i += 1) await Promise.resolve();
+
+ // 兜底发送失败 → 条目重新入队(终态不因一次失败永久丢失)。
+ expect(outboundMocks.deferOpenerConsume).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_opener',
+ markdown: '终态',
+ }),
+ );
+ });
+
+ it('等待排空期间换代后丢弃旧轮次, 不回落用新账号发送', async () => {
+ let rejectPatch!: (err: Error) => void;
+ const patchGate = new Promise<void>((_resolve, reject) => {
+ rejectPatch = reject;
+ });
+ await queueOriginalFallback('om_flushing', '终态回复');
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockImplementationOnce(
+ () => patchGate,
+ );
+ outboundMocks.drainDeferredOpenerConsumes.mockReturnValueOnce([
+ { userId: 'g/oc_c/omt_t', openerId: 'om_flushing', markdown: '终态回复' },
+ ]);
+
+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });
+ for (let i = 0; i < 6; i += 1) await Promise.resolve();
+ const sendP = sendOriginalFallback('g/oc_c/omt_t', '兜底');
+ outboundMocks.getAccountEpoch.mockReturnValue(1);
+ outboundMocks.getBoundClient.mockReturnValue({ fake: 'account-b' });
+ rejectPatch(new Error('patch failed after rebind'));
+
+ await expect(sendP).rejects.toThrow(/account changed while waiting for opener flush/);
+ expect(outboundMocks.sendText).not.toHaveBeenCalled();
+ });
+
+ it('connected 排空与兜底发送重叠时复用在途暂存项, 不另发一份', async () => {
+ let resolvePatch!: () => void;
+ const patchGate = new Promise<void>((resolve) => {
+ resolvePatch = resolve;
+ });
+ await queueOriginalFallback('om_flushing', '终态回复');
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockImplementationOnce(
+ () => patchGate,
+ );
+ outboundMocks.drainDeferredOpenerConsumes.mockReturnValueOnce([
+ { userId: 'g/oc_c/omt_t', openerId: 'om_flushing', markdown: '终态回复' },
+ ]);
+ outboundMocks.takeMatchingDeferredOpenerConsume.mockReturnValue(undefined);
+
+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });
+ const sendP = sendOriginalFallback('g/oc_c/omt_t', '兜底');
+ resolvePatch();
+ await expect(sendP).resolves.toEqual({ messageId: 'om_flushing' });
+ expect(outboundMocks.sendText).not.toHaveBeenCalled();
+ });
+
+ it('排空已成功后原兜底发送仍复用同一 opener, 不另发', async () => {
+ await queueOriginalFallback('om_done', '终态回复');
+ outboundMocks.drainDeferredOpenerConsumes.mockReturnValueOnce([
+ { userId: 'g/oc_c/omt_t', openerId: 'om_done', markdown: '终态回复' },
+ ]);
+ outboundMocks.takeMatchingDeferredOpenerConsume.mockReturnValue(undefined);
+
+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });
+ for (let i = 0; i < 12; i += 1) await Promise.resolve();
+
+ await expect(sendOriginalFallback('g/oc_c/omt_t', '兜底')).resolves.toEqual({
+ messageId: 'om_done',
+ });
+ expect(outboundMocks.sendText).not.toHaveBeenCalled();
+ });
+
+ it('排空完成后同 lane 后续发送不得认领旧 opener 终态', async () => {
+ await queueOriginalFallback('om_done', '终态回复');
+ outboundMocks.drainDeferredOpenerConsumes.mockReturnValueOnce([
+ { userId: 'g/oc_c/omt_t', openerId: 'om_done', markdown: '终态回复' },
+ ]);
+ outboundMocks.takeMatchingDeferredOpenerConsume.mockReturnValue(undefined);
+
+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });
+ for (let i = 0; i < 12; i += 1) await Promise.resolve();
+
+ outboundMocks.sendText.mockResolvedValue({ messageId: 'om_help' });
+ await expect(im.sendText('g/oc_c/omt_t', '/help')).resolves.toEqual({
+ messageId: 'om_help',
+ });
+ expect(outboundMocks.sendText).toHaveBeenCalledWith('g/oc_c/omt_t', '/help');
+
+ await expect(sendOriginalFallback('g/oc_c/omt_t', '兜底')).resolves.toEqual({
+ messageId: 'om_done',
+ });
+ });
+
+ it('排空进行中时同 lane 的新发送不认领旧终态', async () => {
+ let resolvePatch!: () => void;
+ const patchGate = new Promise<void>((resolve) => {
+ resolvePatch = resolve;
+ });
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockImplementationOnce(
+ () => patchGate,
+ );
+ outboundMocks.drainDeferredOpenerConsumes.mockReturnValueOnce([
+ { userId: 'g/oc_c/omt_t', openerId: 'om_flushing', markdown: '/new 回复' },
+ ]);
+ outboundMocks.sendText.mockResolvedValue({ messageId: 'om_help' });
+
+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });
+ const helpP = im.sendText('g/oc_c/omt_t', '/help');
+ resolvePatch();
+ await expect(helpP).resolves.toEqual({ messageId: 'om_help' });
+ expect(outboundMocks.sendText).toHaveBeenCalledWith('g/oc_c/omt_t', '/help');
+ });
+
+ it('保持连接时重新入队后按退避再排空, 不依赖下一次 connected', async () => {
+ vi.useFakeTimers();
+ outboundMocks.drainDeferredOpenerConsumes
+ .mockReturnValueOnce([
+ { userId: 'g/oc_c/omt_t', openerId: 'om_opener', markdown: '终态' },
+ ])
+ .mockReturnValueOnce([
+ { userId: 'g/oc_c/omt_t', openerId: 'om_opener', markdown: '终态' },
+ ]);
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>)
+ .mockRejectedValueOnce(new Error('patch failed'))
+ .mockResolvedValueOnce(undefined);
+ outboundMocks.sendInteractive.mockRejectedValueOnce(new Error('rate limited'));
+
+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(outboundMocks.deferOpenerConsume).toHaveBeenCalledTimes(1);
+ expect(streamingText.patchMarkdown).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(99);
+ expect(streamingText.patchMarkdown).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(streamingText.patchMarkdown).toHaveBeenCalledTimes(2);
+ expect(streamingText.patchMarkdown).toHaveBeenNthCalledWith(2, 'om_opener', '终态');
+ vi.useRealTimers();
+ });
+
+ it('排空持续失败时按退避上限停止, 不零延迟风暴', async () => {
+ vi.useFakeTimers();
+ outboundMocks.drainDeferredOpenerConsumes.mockImplementation(() => [
+ { userId: 'g/oc_c/omt_t', openerId: 'om_opener', markdown: '终态' },
+ ]);
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockRejectedValue(
+ new Error('patch failed'),
+ );
+ outboundMocks.sendInteractive.mockRejectedValue(new Error('rate limited'));
+
+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(streamingText.patchMarkdown).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(100);
+ expect(streamingText.patchMarkdown).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(300);
+ expect(streamingText.patchMarkdown).toHaveBeenCalledTimes(3);
+ await vi.advanceTimersByTimeAsync(900);
+ expect(streamingText.patchMarkdown).toHaveBeenCalledTimes(4);
+ await vi.advanceTimersByTimeAsync(2700);
+ expect(streamingText.patchMarkdown).toHaveBeenCalledTimes(5);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(streamingText.patchMarkdown).toHaveBeenCalledTimes(5);
+ vi.useRealTimers();
+ });
+
+ it('consumePendingOpenerCard: 无 pending opener 返回 false(不撤回)', async () => {
+ outboundMocks.claimPatchableOpener.mockReturnValue(null);
+ await expect(im.consumePendingOpenerCard('g/oc_c/omt_t', '回复')).resolves.toBe(false);
+ expect(outboundMocks.recallOwnMessageWith).not.toHaveBeenCalled();
+ });
+
+ it('重连空窗(无绑定 client)暂存消费: 原子预留 opener 并携带 id, 返回 false', async () => {
+ outboundMocks.getBoundClient.mockReturnValue(null);
+ outboundMocks.claimPatchableOpener.mockReturnValue('om_reserved');
+ await expect(im.consumePendingOpenerCard('g/oc_c/omt_t', '回复')).resolves.toBe(false);
+ await expect(im.consumePendingOpenerAsCard('g/oc_c/omt_t', SPEC)).resolves.toBe(false);
+ expect(outboundMocks.deferOpenerConsume).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_reserved',
+ markdown: '回复',
+ }),
+ );
+ expect(outboundMocks.deferOpenerConsume).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_reserved',
+ spec: SPEC,
+ }),
+ );
+ });
+
+ it('连接就绪后排空暂存消费: 用预留的 openerId patch 文本 / 替换卡片', async () => {
+ outboundMocks.drainDeferredOpenerConsumes.mockReturnValueOnce([
+ { userId: 'g/oc_c/omt_t1', openerId: 'om_opener', markdown: '回复' },
+ { userId: 'g/oc_c/omt_t2', openerId: 'om_opener', spec: SPEC },
+ ]);
+
+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });
+ for (let i = 0; i < 8; i += 1) await Promise.resolve();
+
+ // 排空不再 claim(暂存时已原子预留) — 不会被后续轮次认领。
+ expect(outboundMocks.claimPatchableOpener).not.toHaveBeenCalled();
+ expect(streamingText.patchMarkdown).toHaveBeenCalledWith('om_opener', '回复');
+ expect(outboundMocks.updateInteractive).toHaveBeenCalledWith('om_opener', SPEC);
+ expect(outboundMocks.registerCardLane).toHaveBeenCalledWith('g/oc_c/omt_t2', 'om_opener');
+ });
+
+ it('consumePendingOpenerCard: patch 失败时撤回开场白卡并返回 false(回落发送)', async () => {
+ outboundMocks.claimPatchableOpener.mockReturnValue('om_opener');
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error('patch failed'),
+ );
+ await expect(im.consumePendingOpenerCard('g/oc_c/omt_t', '回复')).resolves.toBe(false);
+ expect(outboundMocks.recallOwnMessageWith).toHaveBeenCalledWith(fakeClient, 'om_opener');
+ expect(outboundMocks.rearmAnchorToTrigger).toHaveBeenCalledWith('g/oc_c/omt_t');
+ });
+
+ it('consumePendingOpenerCard: 撤回失败不回拨不另发, 重新暂存等重试', async () => {
+ outboundMocks.claimPatchableOpener.mockReturnValue('om_opener');
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error('patch failed'),
+ );
+ outboundMocks.recallOwnMessageWith.mockResolvedValueOnce(false);
+
+ await expect(im.consumePendingOpenerCard('g/oc_c/omt_t', '回复')).resolves.toBe(false);
+ expect(outboundMocks.recallOwnMessageWith).toHaveBeenCalledWith(fakeClient, 'om_opener');
+ expect(outboundMocks.rearmAnchorToTrigger).not.toHaveBeenCalled();
+ expect(outboundMocks.deferOpenerConsume).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_opener',
+ markdown: '回复',
+ }),
+ );
+ expect(im.takeNotedFallbackOpenerId('g/oc_c/omt_t', 'markdown')).toBe('om_opener');
+ });
+
+ it('consumePendingOpenerAsCard: 撤回失败不回拨不另发, 重新暂存', async () => {
+ outboundMocks.claimPatchableOpener.mockReturnValue('om_opener');
+ outboundMocks.updateInteractive.mockRejectedValueOnce(new Error('replace failed'));
+ outboundMocks.recallOwnMessageWith.mockResolvedValueOnce(false);
+
+ await expect(im.consumePendingOpenerAsCard('g/oc_c/omt_t', SPEC)).resolves.toBe(false);
+ expect(outboundMocks.rearmAnchorToTrigger).not.toHaveBeenCalled();
+ expect(outboundMocks.registerCardLane).not.toHaveBeenCalled();
+ expect(outboundMocks.deferOpenerConsume).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_opener',
+ spec: SPEC,
+ }),
+ );
+ expect(im.takeNotedFallbackOpenerId('g/oc_c/omt_t', 'spec')).toBe('om_opener');
+ });
+
+ it('consumePendingOpenerAsCard: 替换失败时撤回并返回 false', async () => {
+ outboundMocks.claimPatchableOpener.mockReturnValue('om_opener');
+ outboundMocks.updateInteractive.mockRejectedValueOnce(new Error('replace failed'));
+ await expect(im.consumePendingOpenerAsCard('g/oc_c/omt_t', SPEC)).resolves.toBe(false);
+ expect(outboundMocks.recallOwnMessageWith).toHaveBeenCalledWith(fakeClient, 'om_opener');
+ expect(outboundMocks.rearmAnchorToTrigger).toHaveBeenCalledWith('g/oc_c/omt_t');
+ expect(outboundMocks.registerCardLane).not.toHaveBeenCalled();
+ });
+
+ it('consumePendingOpenerAsCard: 替换成功登记 lane 并返回 true(不撤回)', async () => {
+ outboundMocks.claimPatchableOpener.mockReturnValue('om_opener');
+ await expect(im.consumePendingOpenerAsCard('g/oc_c/omt_t', SPEC)).resolves.toBe(true);
+ expect(outboundMocks.registerCardLane).toHaveBeenCalledWith('g/oc_c/omt_t', 'om_opener');
+ expect(outboundMocks.recallOwnMessageWith).not.toHaveBeenCalled();
+ });
+
+ it('consumePendingOpenerCard: patch 等待中换账号则丢弃旧轮次, 不指示调用方发送', async () => {
+ outboundMocks.claimPatchableOpener.mockReturnValue('om_opener');
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockImplementationOnce(async () => {
+ outboundMocks.getAccountEpoch.mockReturnValue(1);
+ outboundMocks.getBoundClient.mockReturnValue({ fake: 'account-b' });
+ throw new Error('patch failed after rebind');
+ });
+
+ await expect(im.consumePendingOpenerCard('g/oc_c/omt_t', '回复')).resolves.toBe(true);
+ expect(outboundMocks.recallOwnMessageWith).toHaveBeenCalledWith(fakeClient, 'om_opener');
+ expect(outboundMocks.rearmAnchorToTrigger).not.toHaveBeenCalled();
+ expect(outboundMocks.deferOpenerConsume).not.toHaveBeenCalled();
+ });
+
+ it('consumePendingOpenerCard: patch 失败仍同账号但空窗时重新暂存, 不撤回', async () => {
+ outboundMocks.claimPatchableOpener.mockReturnValue('om_opener');
+ (streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockImplementationOnce(async () => {
+ outboundMocks.getBoundClient.mockReturnValue(null);
+ throw new Error('client unbound mid-patch');
+ });
+
+ await expect(im.consumePendingOpenerCard('g/oc_c/omt_t', '回复')).resolves.toBe(false);
+ expect(outboundMocks.deferOpenerConsume).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_opener',
+ markdown: '回复',
+ }),
+ );
+ expect(outboundMocks.recallOwnMessageWith).not.toHaveBeenCalled();
+ expect(outboundMocks.rearmAnchorToTrigger).not.toHaveBeenCalled();
+ });
+
+ it('consumePendingOpenerAsCard: 替换等待中换账号则丢弃旧轮次, 不指示调用方发送', async () => {
+ outboundMocks.claimPatchableOpener.mockReturnValue('om_opener');
+ outboundMocks.updateInteractive.mockImplementationOnce(async () => {
+ outboundMocks.getAccountEpoch.mockReturnValue(1);
+ outboundMocks.getBoundClient.mockReturnValue({ fake: 'account-b' });
+ throw new Error('replace failed after rebind');
+ });
+
+ await expect(im.consumePendingOpenerAsCard('g/oc_c/omt_t', SPEC)).resolves.toBe(true);
+ expect(outboundMocks.recallOwnMessageWith).toHaveBeenCalledWith(fakeClient, 'om_opener');
+ expect(outboundMocks.rearmAnchorToTrigger).not.toHaveBeenCalled();
+ expect(outboundMocks.deferOpenerConsume).not.toHaveBeenCalled();
+ expect(outboundMocks.registerCardLane).not.toHaveBeenCalled();
+ });
+
+ it('consumePendingOpenerAsCard: 替换失败仍同账号但空窗时重新暂存, 不撤回', async () => {
+ outboundMocks.claimPatchableOpener.mockReturnValue('om_opener');
+ outboundMocks.updateInteractive.mockImplementationOnce(async () => {
+ outboundMocks.getBoundClient.mockReturnValue(null);
+ throw new Error('client unbound mid-replace');
+ });
+
+ await expect(im.consumePendingOpenerAsCard('g/oc_c/omt_t', SPEC)).resolves.toBe(false);
+ expect(outboundMocks.deferOpenerConsume).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'g/oc_c/omt_t',
+ openerId: 'om_opener',
+ spec: SPEC,
+ }),
+ );
+ expect(outboundMocks.recallOwnMessageWith).not.toHaveBeenCalled();
+ expect(outboundMocks.rearmAnchorToTrigger).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts
index bd607a5547..24e13e68d2 100644
--- a/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts
@@ -29,6 +29,7 @@ vi.mock('../wsClient.js', () => ({
QUIT_OFFLINE_ANNOUNCE_TIMEOUT_MS: 4500,
getCurrentStatus: mocks.getCurrentStatus,
setLifecycleAnnouncement: vi.fn(),
+ clearOrphanRetriesForCredentialClear: vi.fn(),
stop: mocks.stop,
start: mocks.start,
}));
diff --git a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts
index 3e0b49f27b..97396e9484 100644
--- a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts
@@ -8,22 +8,44 @@ const larkMocks = vi.hoisted(() => {
void payload;
return { data: { message_id: 'om_created' } };
});
+ // 记录每次调用的 this(各自的 message 命名空间对象, 每个 Client 实例一个)—
+ // 用于断言 openThread 的 reply/get/delete 是否 pin 在同一个 client 上。
+ const replyOwners: unknown[] = [];
+ const getOwners: unknown[] = [];
+ const deleteOwners: unknown[] = [];
const reply = vi.fn(
- async (payload: {
- path: unknown;
- data: unknown;
- }): Promise<{ data: { message_id: string; thread_id?: string } }> => {
+ function (
+ this: unknown,
+ payload: {
+ path: unknown;
+ data: unknown;
+ },
+ ): Promise<{ data: { message_id: string; thread_id?: string } }> {
+ replyOwners.push(this);
void payload;
- return { data: { message_id: 'om_replied', thread_id: 'omt_r1' } };
+ return Promise.resolve({ data: { message_id: 'om_replied', thread_id: 'omt_r1' } });
+ },
+ );
+ const deleteMessage = vi.fn(
+ function (this: unknown): Promise<{ code?: number; msg?: string; data?: {} }> {
+ deleteOwners.push(this);
+ return Promise.resolve({ data: {} });
},
);
- const deleteMessage = vi.fn(async () => ({ data: {} }));
+ const patch = vi.fn(
+ async (): Promise<{ code?: number; msg?: string; data?: {} }> => ({ data: {} }),
+ );
const getMessage = vi.fn(
- async (): Promise<{ data: { items: Array<{ thread_id?: string }> } }> => ({
- data: { items: [] },
- }),
+ function (
+ this: unknown,
+ payload: { path: unknown },
+ ): Promise<{ data: { items: Array<{ thread_id?: string }> } }> {
+ getOwners.push(this);
+ void payload;
+ return Promise.resolve({ data: { items: [] } });
+ },
);
- return { create, reply, deleteMessage, getMessage };
+ return { create, reply, deleteMessage, getMessage, patch, replyOwners, getOwners, deleteOwners };
});
vi.mock('@larksuiteoapi/node-sdk', () => ({
@@ -35,6 +57,7 @@ vi.mock('@larksuiteoapi/node-sdk', () => ({
reply: larkMocks.reply,
delete: larkMocks.deleteMessage,
get: larkMocks.getMessage,
+ patch: larkMocks.patch,
},
messageReaction: { create: vi.fn(), delete: vi.fn() },
image: { create: vi.fn() },
@@ -62,12 +85,20 @@ vi.mock('../moduleScope.js', () => ({
import * as outbound from '../outbound.js';
const creds = { appId: 'cli_test', appSecret: 'secret', service: 'feishu' as const };
+const otherCreds = { appId: 'cli_other_account', appSecret: 'secret', service: 'feishu' as const };
+
+/** 强制清掉同账号重连会保留的 opener/锚点, 避免用例互相泄漏。 */
+function rebindFresh(next = creds): void {
+ outbound.unbindClient();
+ outbound.bindClient({ appId: 'cli_test_reset', appSecret: '', service: 'feishu' });
+ outbound.unbindClient();
+ outbound.bindClient(next);
+}
describe('feishu outbound lane routing', () => {
beforeEach(() => {
vi.clearAllMocks();
- outbound.unbindClient(); // clears lane anchors
- outbound.bindClient(creds);
+ rebindFresh();
});
it('sends p2p messages via open_id unchanged', async () => {
@@ -160,7 +191,7 @@ describe('feishu outbound lane routing', () => {
);
});
- it('openThread replies with a patchable card + reply_in_thread + uuid, returns the new thread id', async () => {
+ it('openThread replies with a patchable card + reply_in_thread + uuid, returns opened', async () => {
const res = await outbound.openThread('om_root1');
expect(larkMocks.reply).toHaveBeenCalledWith(
expect.objectContaining({
@@ -172,14 +203,14 @@ describe('feishu outbound lane routing', () => {
}),
}),
);
- expect(res).toEqual({ messageId: 'om_replied', threadId: 'omt_r1' });
+ expect(res).toEqual({ kind: 'opened', messageId: 'om_replied', threadId: 'omt_r1' });
});
it('openThread is idempotent per trigger message (duplicate delivery opens no second topic)', async () => {
const first = outbound.openThread('om_root2');
const second = outbound.openThread('om_root2');
- expect(await first).toEqual({ messageId: 'om_replied', threadId: 'omt_r1' });
- expect(await second).toEqual({ messageId: 'om_replied', threadId: 'omt_r1' });
+ expect(await first).toEqual({ kind: 'opened', messageId: 'om_replied', threadId: 'omt_r1' });
+ expect(await second).toEqual({ kind: 'opened', messageId: 'om_replied', threadId: 'omt_r1' });
// 并发/重复调用只打一次 API — 飞书重投同一条 @ 事件不会开出多个话题。
expect(larkMocks.reply).toHaveBeenCalledTimes(1);
});
@@ -190,55 +221,269 @@ describe('feishu outbound lane routing', () => {
data: { items: [{ thread_id: 'omt_recovered' }] },
});
const res = await outbound.openThread('om_root3');
- expect(res).toEqual({ messageId: 'om_replied', threadId: 'omt_recovered' });
+ expect(res).toEqual({ kind: 'opened', messageId: 'om_replied', threadId: 'omt_recovered' });
expect(larkMocks.getMessage).toHaveBeenCalledWith({
path: { message_id: 'om_replied' },
});
expect(larkMocks.deleteMessage).not.toHaveBeenCalled();
});
- it('openThread recalls the opener and returns null when thread_id is unrecoverable', async () => {
+ it('openThread recalls the opener and returns degraded when thread_id is unrecoverable', async () => {
larkMocks.reply.mockResolvedValueOnce({ data: { message_id: 'om_replied' } });
larkMocks.getMessage.mockResolvedValueOnce({ data: { items: [] } });
- await expect(outbound.openThread('om_root4')).resolves.toBeNull();
+ await expect(outbound.openThread('om_root4')).resolves.toEqual({ kind: 'degraded' });
// 开场白已发出但拿不到话题 id: 撤回它再降级, 不让「回复都在里面」误导。
expect(larkMocks.deleteMessage).toHaveBeenCalledWith({
path: { message_id: 'om_replied' },
});
});
- it('openThread recalls the opener and returns null when message.get itself fails', async () => {
+ it('openThread recalls the opener and returns degraded when message.get itself fails', async () => {
larkMocks.reply.mockResolvedValueOnce({ data: { message_id: 'om_replied' } });
larkMocks.getMessage.mockRejectedValueOnce(new Error('get failed'));
- await expect(outbound.openThread('om_root5')).resolves.toBeNull();
+ await expect(outbound.openThread('om_root5')).resolves.toEqual({ kind: 'degraded' });
expect(larkMocks.deleteMessage).toHaveBeenCalledWith({
path: { message_id: 'om_replied' },
});
});
- it('openThread returns null instead of throwing when the API fails', async () => {
+ it('openThread returns orphaned (not degraded) when recall fails too', async () => {
+ larkMocks.reply.mockResolvedValueOnce({ data: { message_id: 'om_replied' } });
+ larkMocks.getMessage.mockRejectedValueOnce(new Error('get failed'));
+ larkMocks.deleteMessage.mockRejectedValueOnce(new Error('delete failed'));
+ await expect(outbound.openThread('om_root6')).resolves.toEqual({
+ kind: 'orphaned',
+ openerMessageId: 'om_replied',
+ });
+ });
+
+ it('openThread treats a business-error delete response as failed recall (orphaned)', async () => {
+ larkMocks.reply.mockResolvedValueOnce({ data: { message_id: 'om_replied' } });
+ larkMocks.getMessage.mockRejectedValueOnce(new Error('get failed'));
+ // SDK 对业务错误不抛异常 — 2xx 响应带非零 code 时撤回并未成功。
+ larkMocks.deleteMessage.mockResolvedValueOnce({ code: 99991672, msg: 'no permission' });
+ await expect(outbound.openThread('om_root7')).resolves.toEqual({
+ kind: 'orphaned',
+ openerMessageId: 'om_replied',
+ });
+ });
+
+ it('openThread returns degraded instead of throwing when the API fails', async () => {
larkMocks.reply.mockRejectedValueOnce(new Error('no thread permission'));
- await expect(outbound.openThread('om_root6')).resolves.toBeNull();
+ await expect(outbound.openThread('om_root8')).resolves.toEqual({ kind: 'degraded' });
+ expect(larkMocks.reply).toHaveBeenCalledTimes(1);
expect(larkMocks.deleteMessage).not.toHaveBeenCalled();
});
- it('unbindClient clears held anchors (no cross-generation mismatch)', async () => {
+ it('openThread retries an uncertain timeout with the same uuid and recovers', async () => {
+ larkMocks.reply
+ .mockRejectedValueOnce(Object.assign(new Error('timeout of 10000ms exceeded'), { code: 'ETIMEDOUT' }))
+ .mockResolvedValueOnce({ data: { message_id: 'om_recovered', thread_id: 'omt_recovered' } });
+ await expect(outbound.openThread('om_root_timeout')).resolves.toEqual({
+ kind: 'opened',
+ messageId: 'om_recovered',
+ threadId: 'omt_recovered',
+ });
+ expect(larkMocks.reply).toHaveBeenCalledTimes(2);
+ expect(larkMocks.reply.mock.calls.every((call) => {
+ const data = call[0]?.data as { uuid?: string } | undefined;
+ return data?.uuid === 'om_root_timeout';
+ })).toBe(true);
+ });
+
+ it('openThread does not degrade after bounded uncertain retries still have no receipt', async () => {
+ const reset = Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' });
+ larkMocks.reply
+ .mockRejectedValueOnce(reset)
+ .mockRejectedValueOnce(reset)
+ .mockRejectedValueOnce(reset);
+ await expect(outbound.openThread('om_root_unconfirmed')).resolves.toEqual({
+ kind: 'unconfirmed',
+ });
+ expect(larkMocks.reply).toHaveBeenCalledTimes(3);
+ expect(larkMocks.deleteMessage).not.toHaveBeenCalled();
+ // 不是稳定结论: 清缓存后下一次调用会重新打 API。
+ await expect(outbound.openThread('om_root_unconfirmed')).resolves.toEqual({
+ kind: 'opened',
+ messageId: 'om_replied',
+ threadId: 'omt_r1',
+ });
+ });
+
+ it('evictOpenThreadOutcome drops the cached result so the next call retries the API', async () => {
+ // 第一次失败(degraded)会被缓存; 放弃路径 evict 后, 重投应重新打 API。
+ larkMocks.reply.mockRejectedValueOnce(new Error('old client gone'));
+ await expect(outbound.openThread('om_root9')).resolves.toEqual({ kind: 'degraded' });
+
+ outbound.evictOpenThreadOutcome('om_root9');
+ const retried = await outbound.openThread('om_root9');
+ expect(retried).toEqual({ kind: 'opened', messageId: 'om_replied', threadId: 'omt_r1' });
+ expect(larkMocks.reply).toHaveBeenCalledTimes(2);
+ });
+
+ it('recallOwnMessage returns true on success and false on business error or throw', async () => {
+ await expect(outbound.recallOwnMessage('om_ok')).resolves.toBe(true);
+ larkMocks.deleteMessage.mockResolvedValueOnce({ code: 99991672, msg: 'rejected' });
+ await expect(outbound.recallOwnMessage('om_rejected')).resolves.toBe(false);
+ larkMocks.deleteMessage.mockRejectedValueOnce(new Error('network down'));
+ await expect(outbound.recallOwnMessage('om_throw')).resolves.toBe(false);
+ });
+
+ it('updateInteractive / patchCardRaw reject HTTP 200 with a non-zero Feishu code', async () => {
+ outbound.pushReplyAnchor('g/oc_g/omt_t', 'om_anchor');
+ larkMocks.patch.mockResolvedValueOnce({ code: 99991663, msg: 'card not editable' });
+ await expect(
+ outbound.updateInteractive('om_opener', { body: '终态', buttons: [] }),
+ ).rejects.toThrow(/99991663|card not editable/);
+
+ larkMocks.patch.mockResolvedValueOnce({ code: 230002, msg: 'permission denied' });
+ await expect(outbound.patchCardRaw('om_opener', { schema: '2.0' })).rejects.toThrow(
+ /230002|permission denied/,
+ );
+
+ larkMocks.patch.mockResolvedValueOnce({ code: 0, data: {} });
+ await expect(
+ outbound.updateInteractive('om_opener', { body: 'ok', buttons: [] }),
+ ).resolves.toBeUndefined();
+ larkMocks.patch.mockResolvedValueOnce({ data: {} });
+ await expect(outbound.patchCardRaw('om_opener', { schema: '2.0' })).resolves.toBeUndefined();
+ });
+
+ it('openThread pins recovery/recall to the client that created the opener', async () => {
+ const creds2 = { appId: 'cli_other', appSecret: 'secret2', service: 'feishu' as const };
+ const replyBase = larkMocks.replyOwners.length;
+ const getBase = larkMocks.getOwners.length;
+ const deleteBase = larkMocks.deleteOwners.length;
+ larkMocks.reply.mockImplementationOnce(function (this: unknown) {
+ larkMocks.replyOwners.push(this);
+ return Promise.resolve({ data: { message_id: 'om_replied' } });
+ });
+ // message.get 执行期间换账号: bindClient(creds2) 后返回空 items —
+ // 补查与撤回必须仍走创建开场白的那条连接, 不能打到新账号的 client。
+ larkMocks.getMessage.mockImplementationOnce(function (this: unknown, payload: { path: unknown }) {
+ larkMocks.getOwners.push(this);
+ void payload;
+ outbound.bindClient(creds2);
+ return Promise.resolve({ data: { items: [] } });
+ });
+ await expect(outbound.openThread('om_pin1')).resolves.toEqual({ kind: 'degraded' });
+
+ const replyCtx = larkMocks.replyOwners[replyBase];
+ const getCtx = larkMocks.getOwners[getBase];
+ const delCtx = larkMocks.deleteOwners[deleteBase];
+ expect(getCtx).toBe(replyCtx);
+ expect(delCtx).toBe(replyCtx);
+ });
+
+ it('账号替换后清空群 lane 锚点, 不再 reply 到旧账号的触发消息', async () => {
outbound.pushReplyAnchor('g/oc_g', 'om_old');
outbound.unbindClient();
- outbound.bindClient(creds);
+ outbound.bindClient(otherCreds);
await outbound.sendText('g/oc_g', 'later');
expect(larkMocks.reply).not.toHaveBeenCalled();
expect(larkMocks.create).toHaveBeenCalledWith(
expect.objectContaining({ params: { receive_id_type: 'chat_id' } }),
);
});
+
+ it('rearmAnchorToTrigger: 回拨到触发消息的回复带 reply_in_thread 落回话题', async () => {
+ outbound.pushReplyAnchor('g/oc_g/omt_p9', 'om_opener');
+ outbound.pushPatchableOpener('g/oc_g/omt_p9', 'om_opener', 'om_trigger');
+ expect(outbound.claimPatchableOpener('g/oc_g/omt_p9')).toBe('om_opener');
+
+ // patch 失败撤回开场白卡后: 回拨锚点到触发消息。
+ expect(outbound.rearmAnchorToTrigger('g/oc_g/omt_p9')).toBe(true);
+ await outbound.sendText('g/oc_g/omt_p9', '兜底回复');
+ expect(larkMocks.reply).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ path: { message_id: 'om_trigger' },
+ data: expect.objectContaining({ reply_in_thread: true }),
+ }),
+ );
+ // 触发记录一次性消费 — 再次回拨返回 false。
+ expect(outbound.rearmAnchorToTrigger('g/oc_g/omt_p9')).toBe(false);
+ });
+
+ it('暂存队列容量淘汰记录 opener id, 连接恢复时撤回(不留思考卡)', async () => {
+ for (let i = 0; i < 51; i++) {
+ outbound.deferOpenerConsume({ userId: `g/oc_g/omt_ev${i}`, openerId: `om_ev${i}`, markdown: 'x' });
+ }
+ const pending = outbound.drainDeferredOpenerConsumes();
+ expect(pending).toHaveLength(50);
+ const evicted = outbound.drainEvictedOpeners();
+ expect(evicted).toEqual(['om_ev0']);
+ });
+
+ it('claimPatchableOpener consumes the registered opener exactly once', async () => {
+ outbound.pushReplyAnchor('g/oc_g/omt_p1', 'om_opener');
+ outbound.pushPatchableOpener('g/oc_g/omt_p1', 'om_opener');
+
+ expect(outbound.claimPatchableOpener('g/oc_g/omt_p1')).toBe('om_opener');
+ // 第二次认领必须是 null — 同话题下一条真消息不能复用旧开场白卡 id。
+ expect(outbound.claimPatchableOpener('g/oc_g/omt_p1')).toBeNull();
+ });
+
+ it('账号替换后 pending opener 不可再被认领', async () => {
+ outbound.pushReplyAnchor('g/oc_g/omt_p2', 'om_opener');
+ outbound.pushPatchableOpener('g/oc_g/omt_p2', 'om_opener');
+
+ outbound.unbindClient();
+ outbound.bindClient(otherCreds);
+ expect(outbound.claimPatchableOpener('g/oc_g/omt_p2')).toBeNull();
+ });
+
+ it('明确清除凭证(forgetBoundAccount)后同凭证重绑不保留旧 opener', async () => {
+ outbound.pushReplyAnchor('g/oc_g/omt_p8', 'om_opener');
+ outbound.pushPatchableOpener('g/oc_g/omt_p8', 'om_opener', 'om_trigger');
+
+ // 登出(clearAndDisconnect): stop → forgetBoundAccount → 之后重新保存
+ // 相同凭证 — 不得被误判为同账号 transport 重连, 旧 opener 不保留。
+ outbound.unbindClient();
+ outbound.forgetBoundAccount();
+ outbound.bindClient(creds);
+ expect(outbound.claimPatchableOpener('g/oc_g/omt_p8')).toBeNull();
+ });
+
+ it('同账号重连(rebind 同凭证)保留 pending opener, 仍可被认领', async () => {
+ outbound.pushReplyAnchor('g/oc_g/omt_keep', 'om_opener');
+ outbound.pushPatchableOpener('g/oc_g/omt_keep', 'om_opener');
+
+ // reconnectSavedCredentials: stop → unbind → start → bind 同凭证。
+ // host 可能还在回翻群历史, turn 未认领开场白 — 重连后必须还能 patch。
+ outbound.unbindClient();
+ outbound.bindClient(creds);
+ expect(outbound.claimPatchableOpener('g/oc_g/omt_keep')).toBe('om_opener');
+ });
+
+ it('同账号重连保留话题锚点, 后续出站仍能 reply 不丢进群主流', async () => {
+ outbound.pushReplyAnchor('g/oc_g/omt_keep2', 'om_anchor');
+
+ outbound.unbindClient();
+ outbound.bindClient(creds);
+ await outbound.sendText('g/oc_g/omt_keep2', 'after-reconnect');
+ expect(larkMocks.reply).toHaveBeenCalledWith(
+ expect.objectContaining({ path: { message_id: 'om_anchor' } }),
+ );
+ expect(larkMocks.create).not.toHaveBeenCalled();
+ });
+
+ it('账号真正替换(appId 变化)时清空 pending opener 与话题锚点', async () => {
+ outbound.pushReplyAnchor('g/oc_g/omt_drop', 'om_opener');
+ outbound.pushPatchableOpener('g/oc_g/omt_drop', 'om_opener');
+
+ outbound.unbindClient();
+ outbound.bindClient(otherCreds);
+ expect(outbound.claimPatchableOpener('g/oc_g/omt_drop')).toBeNull();
+ await expect(outbound.sendText('g/oc_g/omt_drop', 'after-switch')).rejects.toThrow(
+ /no reply anchor/,
+ );
+ });
});
describe('feishu card lane registry', () => {
beforeEach(() => {
vi.clearAllMocks();
- outbound.unbindClient(); // clears lane anchors + card registry
- outbound.bindClient(creds);
+ rebindFresh();
});
it('registers topic-lane cards and resolves them back to the same lane', async () => {
diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts
index 426f6fcd20..1612e4b392 100644
--- a/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts
@@ -19,13 +19,22 @@ const mocks = {
sendText: vi.fn(async () => ({ messageId: 'om_sent' })),
replyText: vi.fn(async () => ({ messageId: 'om_reply' })),
openThread: vi.fn(
- async (): Promise<{ messageId: string; threadId: string } | null> => ({
+ async (
+ _messageId?: string,
+ ): Promise<
+ | { kind: 'opened'; messageId: string; threadId: string }
+ | { kind: 'degraded' }
+ | { kind: 'orphaned'; openerMessageId: string }
+ > => ({
+ kind: 'opened',
messageId: 'om_opener',
threadId: 'omt_new',
}),
),
pushReplyAnchor: vi.fn(),
pushPatchableOpener: vi.fn(),
+ evictOpenThreadOutcome: vi.fn(),
+ recallOwnMessage: vi.fn(async () => true),
firstAllowed: vi.fn<() => string | null>(() => null),
readOwnerOpenId: vi.fn<() => string | null>(() => null),
clearOwner: vi.fn(),
@@ -73,6 +82,8 @@ vi.doMock('../outbound.js', () => ({
openThread: mocks.openThread,
pushReplyAnchor: mocks.pushReplyAnchor,
pushPatchableOpener: mocks.pushPatchableOpener,
+ evictOpenThreadOutcome: mocks.evictOpenThreadOutcome,
+ recallOwnMessage: mocks.recallOwnMessage,
}));
vi.doMock('../ownerGuard.js', () => ({
@@ -144,12 +155,21 @@ beforeEach(async () => {
// 入站去重账本按设计跨 stop/start 保留(重推高发在重连前后), 所以用例之间
// 想复用同一个 message_id 必须显式清账。
wsClient.resetInboundDedupeForTest();
+ wsClient.resetOrphanRetriesForTest();
mocks.options.length = 0;
mocks.eventHandlers = {};
vi.clearAllMocks();
feishuEvents.removeAllListeners('message');
mocks.firstAllowed.mockReturnValue(OWNER);
mocks.checkOwner.mockImplementation((id: string) => id === OWNER);
+ // 恢复 openThread / replyText 默认实现 — 个别用例会覆盖它们
+ // (含持续的 mockRejectedValue), 不能泄漏到后续用例。
+ mocks.openThread.mockImplementation(async () => ({
+ kind: 'opened',
+ messageId: 'om_opener',
+ threadId: 'omt_new',
+ }));
+ mocks.replyText.mockImplementation(async () => ({ messageId: 'om_reply' }));
});
afterEach(async () => {
@@ -220,13 +240,13 @@ describe('feishu group inbound gate', () => {
// 锚点是开场白消息(话题内合法锚点), 不是触发消息。
expect(mocks.pushReplyAnchor).toHaveBeenCalledWith('g/oc_chat1/omt_new', 'om_opener');
// 开场白卡登记为可补丁锚点 — 本轮流式卡直接 patch 它, 不发占位消息。
- expect(mocks.pushPatchableOpener).toHaveBeenCalledWith('g/oc_chat1/omt_new', 'om_opener');
+ expect(mocks.pushPatchableOpener).toHaveBeenCalledWith('g/oc_chat1/omt_new', 'om_opener', 'om_msg1');
// 路由进新话题 lane, 但上下文取数 lane 仍是群主流(新话题是空的)。
expect(event.groupContextLane).toEqual({ chatId: 'oc_chat1', threadId: '' });
});
it('falls back to the plain group lane when thread creation fails', async () => {
- mocks.openThread.mockResolvedValueOnce(null);
+ mocks.openThread.mockResolvedValueOnce({ kind: 'degraded' });
await connect();
const events = collectEvents();
await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
@@ -237,6 +257,949 @@ describe('feishu group inbound gate', () => {
expect(mocks.pushReplyAnchor).toHaveBeenCalledWith('g/oc_chat1', 'om_msg1');
});
+ it('orphaned opener: replies an in-topic notice and drops the turn instead of degrading', async () => {
+ mocks.openThread.mockResolvedValueOnce({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+
+ expect(events).toHaveLength(0);
+ expect(mocks.pushReplyAnchor).not.toHaveBeenCalled();
+ expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();
+ // 提示挂在开场白下(自动落回话题) — 不把回答刷进群主流。
+ expect(mocks.replyText).toHaveBeenCalledWith('om_opener', expect.any(String));
+ });
+
+ it('drops the turn when the connection is replaced while openThread is awaiting', async () => {
+ let resolveOpenThread!: (outcome: {
+ kind: 'opened';
+ messageId: string;
+ threadId: string;
+ }) => void;
+ mocks.openThread.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveOpenThread = resolve;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ const handling = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ // openThread 仍在等待 API 时用户断开/换账号 — 旧连接的轮次不得漏进新连接。
+ await wsClient.stop({ announceOffline: false, reason: 'test-disconnect-mid-open' });
+ resolveOpenThread({ kind: 'opened', messageId: 'om_opener', threadId: 'omt_new' });
+ await handling;
+
+ expect(events).toHaveLength(0);
+ expect(mocks.pushReplyAnchor).not.toHaveBeenCalled();
+ expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();
+ // 放弃路径释放了入站认领并 evict 了开话题缓存 — 新连接上的重投消息应
+ // 重新走 openThread API(而不是复用旧连接上的结果), 且正常处理。
+ expect(mocks.evictOpenThreadOutcome).toHaveBeenCalledWith('om_msg1');
+ await connect();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(events).toHaveLength(1);
+ expect(events[0]!.senderId).toBe('g/oc_chat1/omt_new');
+ expect(mocks.openThread).toHaveBeenCalledTimes(2);
+ });
+
+ it('orphan notice failure schedules escalating active retries instead of relying on redelivery', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValueOnce({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ // 首发失败 + 前两次重试失败, 第三次重试成功。
+ mocks.replyText
+ .mockRejectedValueOnce(new Error('transient network error'))
+ .mockRejectedValueOnce(new Error('rate limited'))
+ .mockRejectedValueOnce(new Error('still down'));
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+
+ // 首轮: 不起 turn, 提示发送失败。
+ expect(events).toHaveLength(0);
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 飞书对 3s 内完成处理的事件直接 ACK 不再重推 — 主动重试不依赖重投,
+ // 递增间隔(10s / 30s / 90s), 用户不会永远看着「思考中」的开场白卡。
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(3);
+ await vi.advanceTimersByTimeAsync(90_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(4);
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('orphan notice retries are gated to the triggering connection', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValueOnce({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 首发失败后、重试触发前用户断开/换账号 — 旧账号的开场白不该发进
+ // 新账号的会话, 重试应被跳过。
+ await wsClient.stop({ announceOffline: false, reason: 'test-disconnect-before-retry' });
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('retry exhaustion recalls the orphaned opener card as last resort', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValueOnce({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ // 首发 + 3 次重试全部失败(持续故障)。
+ mocks.replyText.mockRejectedValue(new Error('persistent outage'));
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await vi.advanceTimersByTimeAsync(10_000);
+ await vi.advanceTimersByTimeAsync(30_000);
+ await vi.advanceTimersByTimeAsync(90_000);
+
+ expect(mocks.replyText).toHaveBeenCalledTimes(4);
+ // 重试耗尽: 撤回开场白卡, 用户看到干净群主流而不是永久「思考中」卡。
+ expect(mocks.recallOwnMessage).toHaveBeenCalledWith('om_opener');
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('stop 挂起超过 100 条孤儿收口链后同账号重连仍恢复最早一条', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockImplementation(async (messageId?: string) => ({
+ kind: 'orphaned' as const,
+ openerMessageId: `om_opener_${messageId ?? 'x'}`,
+ }));
+ mocks.replyText.mockRejectedValue(new Error('persistent outage'));
+ await connect();
+
+ for (let i = 0; i < 101; i += 1) {
+ await mocks.eventHandlers['im.message.receive_v1']!(
+ groupMessage({ messageId: `om_msg_${i}`, text: `@_user_1 孤儿${i}` }),
+ );
+ }
+
+ await wsClient.stop({ announceOffline: false, reason: 'same-account-reconnect' });
+ await connect();
+ mocks.replyText.mockClear();
+
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledWith(
+ 'om_opener_om_msg_0',
+ expect.any(String),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('redelivery while a retry is in-flight shares the same send (no concurrent duplicate)', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ // 第一次定时重试(10s)的发送挂起中 — 重投此刻到达, 必须共享这次发送
+ // 而不是并发发出第二条提示。
+ let resolveRetry!: (v: { messageId: string }) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((resolve) => {
+ resolveRetry = resolve;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+
+ // 冷却(60s)过后的重投: in-flight 共享 — 重投自己不另发(replyText 不变)。
+ // 重投 handler 会等共享发送的结果, 不能 await(否则测试自身挂起)。
+ await vi.advanceTimersByTimeAsync(51_000);
+ const redelivery = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+
+ // 执行中的发送成功 — 共享结果 'delivered': 两条路径都收尾, 无新发送。
+ resolveRetry({ messageId: 'om_ok' });
+ await redelivery;
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('redelivery shared with a failing in-flight retry continues one chain (no duplicate)', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ // 第一次定时重试(10s)的发送挂起中 — 重投共享它, 之后该发送失败。
+ let rejectRetry!: (err: Error) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((_, reject) => {
+ rejectRetry = reject;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+
+ // 冷却过后的重投共享该 in-flight 发送(不另发), 随后发送失败 —
+ // 共享结果 'failed': 两条路径各自安排重试, 入口同一(替换计时器)。
+ // 重投 handler 等共享结果, 不 await。
+ await vi.advanceTimersByTimeAsync(51_000);
+ const redelivery = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ rejectRetry(new Error('outage'));
+ await redelivery;
+ await Promise.resolve();
+ await Promise.resolve();
+
+ // 重试链继续(单链): 下一次尝试成功送达, 之后不再有发送。
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(3);
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(3);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('retry scheduled after a same-account reconnect proceeds on the new connection', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ // 首次发送挂起中 — 期间断开 + 同一 bot 重连, 挂起的发送之后才失败。
+ let rejectFirst!: (err: Error) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((_, reject) => {
+ rejectFirst = reject;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ const firstDelivery = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 断开 + 同一 bot 重连; stop 已释放 in-flight 认领 — 重投到达时不再被
+ // 认领压掉, 而是正常处理并共享在途发送(不另发第二条)。
+ await wsClient.stop({ announceOffline: false, reason: 'test-same-account-reconnect' });
+ await connect();
+ const redelivery = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 旧发送此刻失败 — 共享结果 'failed': 两条路径各自安排重试, 入口同一;
+ // 同账号重连后在新连接上继续执行(stale generation 不拦同 bot 的重试)。
+ rejectFirst(new Error('client closed'));
+ await firstDelivery;
+ await redelivery;
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('retry is skipped when the account changed (old account opener never hits the new client)', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ let rejectFirst!: (err: Error) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((_, reject) => {
+ rejectFirst = reject;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ const firstDelivery = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 断开并换成**别的** bot 账号。
+ await wsClient.stop({ announceOffline: false, reason: 'test-account-swap' });
+ const otherCreds = { appId: 'cli_other_account', appSecret: 'secret', service: 'feishu' as const };
+ const connecting = wsClient.start(otherCreds, { announceLifecycle: false });
+ mocks.options.at(-1)?.onReady?.();
+ await connecting;
+ wsClient.setBotOpenIdForTest(BOT_OPEN_ID);
+
+ // 旧发送失败 → 安排重试; 重试触发时账号已换 — 必须跳过, 旧账号的
+ // 开场白不得经新账号的 client 发出。
+ rejectFirst(new Error('client closed'));
+ await firstDelivery;
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('queued retry survives a same-bot reconnect (re-armed on start)', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+ // 10s 重试已排队。
+
+ // 定时器触发前断开 + 同一 bot 重连: stop() 挂起重试, start() 恢复入队。
+ await wsClient.stop({ announceOffline: false, reason: 'test-reconnect-before-retry' });
+ await connect();
+
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('retry that fires while disconnected is suspended and resumed on same-bot reconnect', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ // 第一次定时重试(10s)的发送挂起中 — 断开, 该发送之后才失败。
+ let rejectRetry!: (err: Error) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((_, reject) => {
+ rejectRetry = reject;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+
+ // 断开(in-flight 无法挂起); 旧发送失败 → 在停止状态安排下一次重试。
+ await wsClient.stop({ announceOffline: false, reason: 'test-disconnect-mid-retry' });
+ rejectRetry(new Error('client closed'));
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ // 该重试在重连前触发: 无连接 → 挂起(不终止)。
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+
+ // 同一 bot 重连 → 挂起重试恢复入队 → 下一次尝试成功送达。
+ await connect();
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(3);
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(3);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('failure after stop suspends immediately instead of creating a live timer', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ // 首次发送挂起中 — 断开, 该发送之后才失败(失败路径运行在停止状态)。
+ let rejectFirst!: (err: Error) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((_, reject) => {
+ rejectFirst = reject;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ const firstDelivery = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ await wsClient.stop({ announceOffline: false, reason: 'test-stop-mid-first-send' });
+ rejectFirst(new Error('client closed'));
+ await firstDelivery;
+
+ // 停止状态: 失败路径不创建定时器(直接挂起)— 推进时间无任何发送。
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 同一 bot 重连 → 挂起恢复入队 → 送达。
+ await connect();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('清凭证期间在途首发失败后,同账号再登录不会恢复登出前的 opener 重试', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ let rejectFirst!: (err: Error) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((_, reject) => {
+ rejectFirst = reject;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ const firstDelivery = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 生产顺序: stop 再清凭证。在途 REST 此时仍未落定; 只清 map 挡不住
+ // 失败续段 suspend, 同账号再登录就会把登出前的 opener 重试复活。
+ await wsClient.stop({ announceOffline: false, reason: 'credentials-cleared' });
+ wsClient.clearOrphanRetriesForCredentialClear();
+ rejectFirst(new Error('client closed'));
+ await firstDelivery;
+
+ await connect();
+ await vi.advanceTimersByTimeAsync(200_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('清凭证期间在途重试失败后,同账号再登录不会恢复登出前的 opener 重试', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ let rejectRetry!: (err: Error) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((_, reject) => {
+ rejectRetry = reject;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+
+ await wsClient.stop({ announceOffline: false, reason: 'credentials-cleared' });
+ wsClient.clearOrphanRetriesForCredentialClear();
+ rejectRetry(new Error('client closed'));
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ await connect();
+ await vi.advanceTimersByTimeAsync(200_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('in-flight dedupe survives a same-bot reconnect (redelivery shares the old send)', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ // 10s 定时重试的发送挂起中 — 断开重连后, 重投必须共享这次在途发送。
+ let resolveRetry!: (v: { messageId: string }) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((resolve) => {
+ resolveRetry = resolve;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+
+ // 断开 + 同一 bot 重连(in-flight 记账保留), 冷却(60s)过后重投。
+ await wsClient.stop({ announceOffline: false, reason: 'test-reconnect-mid-inflight' });
+ await connect();
+ await vi.advanceTimersByTimeAsync(61_000);
+ const redelivery = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+
+ // 在途发送成功 — 共享结果 'delivered', 无第三条发送。
+ resolveRetry({ messageId: 'om_ok' });
+ await redelivery;
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('suspended retries are not re-armed across service boundary (same appId, feishu → lark)', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+ // 10s 重试已排队。
+
+ // 断开, 用同一 appId 但 service=lark 的凭证重连 — 旧 feishu 的挂起
+ // 重试不得恢复(账号边界含 service)。
+ await wsClient.stop({ announceOffline: false, reason: 'test-service-swap' });
+ const larkCreds = { appId: 'cli_group_test', appSecret: 'secret', service: 'lark' as const };
+ const connecting = wsClient.start(larkCreds, { announceLifecycle: false });
+ mocks.options.at(-1)?.onReady?.();
+ await connecting;
+ wsClient.setBotOpenIdForTest(BOT_OPEN_ID);
+
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('redelivery joining a failed in-flight retry does not reset the attempt budget', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ // 首发 + attempt0(10s) + attempt1(40s) 都失败; 下一次重投的发送挂起。
+ mocks.replyText
+ .mockRejectedValueOnce(new Error('outage'))
+ .mockRejectedValueOnce(new Error('outage'))
+ .mockRejectedValueOnce(new Error('outage'));
+ let rejectShared!: (err: Error) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((_, reject) => {
+ rejectShared = reject;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await vi.advanceTimersByTimeAsync(61_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(3); // 首发 + attempt0 + attempt1
+ // attempt2 已排队(130s 触发)。
+
+ // 冷却过后的重投创建 in-flight 发送(第 4 次调用, 挂起)。
+ const redelivery = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(4);
+
+ // attempt2 定时器触发 → 加入那次 in-flight(不另发)。
+ await vi.advanceTimersByTimeAsync(69_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(4);
+
+ // 共享发送失败: attempt2 链进撤回兜底; 重投失败路径的 attempt 0 不得
+ // 重置预算(预算天花板) — 之后不应再有新发送。
+ rejectShared(new Error('outage'));
+ await redelivery;
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(mocks.recallOwnMessage).toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(4);
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('换账号启动时丢弃旧账号的挂起重试(不再等待旧账号回归)', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 断开(重试挂起)→ 换成别的 bot 启动: 挂起项被丢弃。
+ await wsClient.stop({ announceOffline: false, reason: 'test-account-swap-drop' });
+ const otherCreds = { appId: 'cli_other_account', appSecret: 'secret', service: 'feishu' as const };
+ const connecting = wsClient.start(otherCreds, { announceLifecycle: false });
+ mocks.options.at(-1)?.onReady?.();
+ await connecting;
+ wsClient.setBotOpenIdForTest(BOT_OPEN_ID);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 之后再换回旧账号: 丢弃过的重试不得复活(向早已过时的 opener 补发)。
+ await wsClient.stop({ announceOffline: false, reason: 'test-back-to-old-account' });
+ const back = wsClient.start(credentials, { announceLifecycle: false });
+ mocks.options.at(-1)?.onReady?.();
+ await back;
+ wsClient.setBotOpenIdForTest(BOT_OPEN_ID);
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('清凭证取消在途孤儿发送的续段(不再 schedule/suspend 新状态)', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ let rejectFirst!: (err: Error) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((_, reject) => {
+ rejectFirst = reject;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ const firstDelivery = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 在途发送期间清凭证: 续段按代次放弃 — 不 schedule、不 suspend。
+ wsClient.clearOrphanRetriesForCredentialClear();
+ rejectFirst(new Error('client closed'));
+ await firstDelivery;
+ await vi.advanceTimersByTimeAsync(200_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+
+ // 清凭证后同凭证重连: 也不应有任何重试复活。
+ await wsClient.stop({ announceOffline: false, reason: 'test-relogin' });
+ await connect();
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('stale in-flight 不丢本代收口链: 安排本代重试, 旧请求落定后送达', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ // 首次发送挂起(代次 N)。
+ let rejectOld!: (err: Error) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((_, reject) => {
+ rejectOld = reject;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ const firstDelivery = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 清凭证(代次 N+1)后同凭证重登录, 平台重投: 新 handler 加入 stale
+ // in-flight → 安排本代重试(不丢收口链)。
+ wsClient.clearOrphanRetriesForCredentialClear();
+ await wsClient.stop({ announceOffline: false, reason: 'test-relogin-stale' });
+ await connect();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 旧请求失败 → 旧 handler 的续段被代次拦截; 本代重试在 10s 后触发,
+ // 以当前代次重新发送并送达。
+ rejectOld(new Error('client closed'));
+ await firstDelivery;
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('queued retry is not re-armed when a different bot starts', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 定时器触发前断开, 换成别的 bot — 旧 bot 的挂起重试不得恢复。
+ await wsClient.stop({ announceOffline: false, reason: 'test-account-swap-before-retry' });
+ const otherCreds = { appId: 'cli_other_account', appSecret: 'secret', service: 'feishu' as const };
+ const connecting = wsClient.start(otherCreds, { announceLifecycle: false });
+ mocks.options.at(-1)?.onReady?.();
+ await connecting;
+ wsClient.setBotOpenIdForTest(BOT_OPEN_ID);
+
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('delivered terminal marker blocks a late send path even beyond the 60s cooldown', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+
+ // 10s 定时重试成功送达 — 终态标记写入。
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+
+ // 远超 60s 冷却窗口后的重投: 送达是终态 + 入站认领已重新认领 —
+ // 任何路径都不再发送第三条提示。
+ await vi.advanceTimersByTimeAsync(300_000);
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('successful retry reclaims the message so later redeliveries are suppressed', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText.mockRejectedValueOnce(new Error('transient network error'));
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 10s 定时重试成功 — 重新认领触发消息。
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+
+ // 冷却(60s)过后的重投: 入站去重拦下(已重新认领), 不再进入提示流程。
+ await vi.advanceTimersByTimeAsync(61_000);
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(2);
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('successful redelivery cancels the stale retry scheduled by the failed first attempt', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ // 首发 + 前两轮定时重试都失败(90s 重试挂起中) — 重投在此时成功送达。
+ mocks.replyText
+ .mockRejectedValueOnce(new Error('transient network error'))
+ .mockRejectedValueOnce(new Error('still down'))
+ .mockRejectedValueOnce(new Error('still down'));
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 冷却过后的重投成功发送提示 — 之前失败轮次安排的定时重试应被清掉,
+ // 否则它会绕过冷却在稍后重复提示, 甚至耗尽后误撤回开场白卡。
+ await vi.advanceTimersByTimeAsync(61_000);
+ // 61s 内 10s + 30s 两轮定时重试都跑过且失败(共 3 次调用)。
+ expect(mocks.replyText).toHaveBeenCalledTimes(3);
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(4);
+
+ // 再推进远超 90s 的重试窗口: 被清掉的重试链不应再有任何发送。
+ await vi.advanceTimersByTimeAsync(200_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(4);
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('exhaustion recall is gated to the triggering connection', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValueOnce({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ mocks.replyText
+ .mockRejectedValueOnce(new Error('outage'))
+ .mockRejectedValueOnce(new Error('outage'))
+ .mockRejectedValueOnce(new Error('outage'));
+ // 最后一次重试(retry2)的 replyText 挂起 — 期间用户换代, 之后才失败。
+ let rejectLast!: (err: Error) => void;
+ mocks.replyText.mockImplementationOnce(
+ () =>
+ new Promise<{ messageId: string }>((_, reject) => {
+ rejectLast = reject;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await vi.advanceTimersByTimeAsync(10_000);
+ await vi.advanceTimersByTimeAsync(30_000);
+ await vi.advanceTimersByTimeAsync(90_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(4);
+
+ // 最后一次重试挂起期间换代, 然后失败 → 耗尽分支应 gate 拦截撤回:
+ // 旧账号的开场白卡不得经新 client 发出删除请求。
+ await wsClient.stop({ announceOffline: false, reason: 'test-disconnect-mid-retry' });
+ rejectLast(new Error('outage'));
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('cooldown-hit redelivery releases its claim so a later redelivery can retry', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.openThread.mockResolvedValue({ kind: 'orphaned', openerMessageId: 'om_opener' });
+ // 首发 + 前两次定时重试都失败; 第三次重试(90s)不触发。
+ mocks.replyText
+ .mockRejectedValueOnce(new Error('transient network error'))
+ .mockRejectedValueOnce(new Error('still down'))
+ .mockRejectedValueOnce(new Error('still down'));
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 冷却期内的重投: 冷却命中不发送 — 必须释放本次认领, 否则冷却期间
+ // 的 claim 卡满 10 分钟, 之后换代会丢消息。
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(1);
+
+ // 推进 61s: 定时重试(10s/30s)跑两轮都失败; 冷却已过期。
+ await vi.advanceTimersByTimeAsync(61_000);
+ expect(mocks.replyText).toHaveBeenCalledTimes(3);
+
+ // 冷却过期后的重投: 认领未被卡住 → 正常处理 → 提示发送成功(第 4 次)。
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.replyText).toHaveBeenCalledTimes(4);
+ expect(events).toHaveLength(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('stop releases the in-flight claim so a redelivery on the reconnected bot is processed', async () => {
+ // 旧连接的 openThread 挂起中; stop(同账号重连)释放认领; 新连接的重投
+ // 到达 → 正常处理(不被仍持有的认领压掉)。
+ let resolveOldOpen!: (o: { kind: 'opened'; messageId: string; threadId: string }) => void;
+ mocks.openThread.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveOldOpen = resolve;
+ }),
+ );
+ await connect();
+ const events = collectEvents();
+ const oldHandling = mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await Promise.resolve();
+ expect(mocks.openThread).toHaveBeenCalledTimes(1);
+
+ await wsClient.stop({ announceOffline: false, reason: 'test-reconnect-while-opening' });
+ await connect();
+ // 重投(旧请求恢复前到达): stop 已释放认领 → 新连接正常处理并 emit。
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ await vi.waitFor(() => expect(mocks.openThread).toHaveBeenCalledTimes(2));
+ expect(events).toHaveLength(1);
+ expect(events[0]!.senderId).toBe('g/oc_chat1/omt_new');
+
+ // 旧 handler 此刻才恢复: gate-drop, 且不得再释放新连接的认领。
+ resolveOldOpen({ kind: 'opened', messageId: 'om_opener', threadId: 'omt_new' });
+ await oldHandling;
+ expect(events).toHaveLength(1);
+
+ // 第三次投递: 新连接的认领仍在 → 重推被压掉, 不会重复起 turn。
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(events).toHaveLength(1);
+ expect(mocks.openThread).toHaveBeenCalledTimes(2);
+ });
+
+ it('drops duplicate delivery of the same message (one turn per message)', async () => {
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ // 飞书重投同一条 @ 事件: 入站去重直接丢弃, 第二次 turn 不会启动
+ // (重复锚点 + 两份回答)。
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+
+ expect(events).toHaveLength(1);
+ expect(mocks.openThread).toHaveBeenCalledTimes(1);
+ expect(mocks.pushReplyAnchor).toHaveBeenCalledTimes(1);
+ });
+
it('routes topic messages into a topic lane without opening a new thread', async () => {
await connect();
const events = collectEvents();
diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts
index 832571210a..f39e6642bc 100644
--- a/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts
@@ -28,10 +28,16 @@ const mocks = {
getBoundClient: vi.fn(() => null),
sendText: vi.fn(async () => ({ messageId: 'om_sent' })),
replyText: vi.fn(async () => ({ messageId: 'om_reply' })),
- // 返回 null = 开话题失败(降级回群 lane), 单测按用例覆盖。
+ // 返回 degraded = 开话题失败(降级回群 lane), 单测按用例覆盖。
openThread: vi.fn<
- () => Promise<{ messageId: string; threadId: string } | null>
- >(async () => ({ messageId: 'om_opener', threadId: 'omt_new' })),
+ (messageId?: string) => Promise<
+ | { kind: 'opened'; messageId: string; threadId: string }
+ | { kind: 'degraded' }
+ | { kind: 'orphaned'; openerMessageId: string }
+ | { kind: 'unconfirmed' }
+ >
+ >(async () => ({ kind: 'opened', messageId: 'om_opener', threadId: 'omt_new' })),
+ evictOpenThreadOutcome: vi.fn(),
pushReplyAnchor: vi.fn(),
pushPatchableOpener: vi.fn(),
resolveCardLane: vi.fn<(messageId: string, chatId: string) => string | null>(
@@ -82,6 +88,7 @@ vi.doMock('../outbound.js', () => ({
sendText: mocks.sendText,
replyText: mocks.replyText,
openThread: mocks.openThread,
+ evictOpenThreadOutcome: mocks.evictOpenThreadOutcome,
pushReplyAnchor: mocks.pushReplyAnchor,
pushPatchableOpener: mocks.pushPatchableOpener,
resolveCardLane: mocks.resolveCardLane,
@@ -153,6 +160,7 @@ beforeEach(async () => {
// 去重账本按设计跨 stop/start 保留, 用例之间必须显式清掉才能复用同一个
// message_id。
wsClient.resetInboundDedupeForTest();
+ wsClient.resetOrphanRetriesForTest();
mocks.options.length = 0;
mocks.eventHandlers = {};
vi.clearAllMocks();
@@ -163,7 +171,9 @@ beforeEach(async () => {
afterEach(async () => {
await wsClient.stop({ announceOffline: false, reason: 'test-cleanup' });
+ wsClient.resetOrphanRetriesForTest();
feishuEvents.removeAllListeners('message');
+ vi.useRealTimers();
});
beforeAll(async () => {
@@ -187,7 +197,7 @@ describe('feishu group thread routing', () => {
expect(mocks.openThread).toHaveBeenCalledWith('om_msg1');
expect(mocks.pushReplyAnchor).toHaveBeenCalledWith('g/oc_chat1/omt_new', 'om_opener');
- expect(mocks.pushPatchableOpener).toHaveBeenCalledWith('g/oc_chat1/omt_new', 'om_opener');
+ expect(mocks.pushPatchableOpener).toHaveBeenCalledWith('g/oc_chat1/omt_new', 'om_opener', 'om_msg1');
expect(events).toHaveLength(1);
expect(events[0].senderId).toBe('g/oc_chat1/omt_new');
// 新话题是空的, 群历史前缀仍按触发时所在的群主流拉取。
@@ -202,8 +212,8 @@ describe('feishu group thread routing', () => {
*/
it('每次群主流 @bot 都开自己的新话题(没有任何"截流进接管话题"的通道)', async () => {
mocks.openThread
- .mockResolvedValueOnce({ messageId: 'om_opener1', threadId: 'omt_a' })
- .mockResolvedValueOnce({ messageId: 'om_opener2', threadId: 'omt_b' });
+ .mockResolvedValueOnce({ kind: 'opened', messageId: 'om_opener1', threadId: 'omt_a' })
+ .mockResolvedValueOnce({ kind: 'opened', messageId: 'om_opener2', threadId: 'omt_b' });
const events = collectMessages();
await connect();
@@ -234,7 +244,7 @@ describe('feishu group thread routing', () => {
});
it('开话题失败时降级回群 lane(锚点 = 触发消息)', async () => {
- mocks.openThread.mockResolvedValueOnce(null);
+ mocks.openThread.mockResolvedValueOnce({ kind: 'degraded' });
const events = collectMessages();
await connect();
@@ -244,4 +254,185 @@ describe('feishu group thread routing', () => {
expect(mocks.pushReplyAnchor).toHaveBeenCalledWith('g/oc_chat1', 'om_msg1');
expect(events[0].groupContextLane).toBeUndefined();
});
+
+ it('开话题回执不确定时立刻不起 turn、不降级, 也不释放认领', async () => {
+ mocks.openThread.mockResolvedValueOnce({ kind: 'unconfirmed' });
+ const events = collectMessages();
+ await connect();
+
+ await mocks.eventHandlers['im.message.receive_v1'](groupMainFlowMessage('回执不确定'));
+
+ expect(events).toHaveLength(0);
+ expect(mocks.pushReplyAnchor).not.toHaveBeenCalled();
+ expect(mocks.evictOpenThreadOutcome).not.toHaveBeenCalled();
+ });
+
+ it('回执不确定后定时用同一 uuid 取回 opened, 再发出话题 turn', async () => {
+ vi.useFakeTimers();
+ mocks.openThread
+ .mockResolvedValueOnce({ kind: 'unconfirmed' })
+ .mockResolvedValueOnce({ kind: 'opened', messageId: 'om_recovered', threadId: 'omt_rec' });
+ const events = collectMessages();
+ await connect();
+
+ await mocks.eventHandlers['im.message.receive_v1'](groupMainFlowMessage('回执不确定后恢复'));
+ expect(events).toHaveLength(0);
+
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.openThread).toHaveBeenCalledTimes(2);
+ expect(mocks.openThread).toHaveBeenLastCalledWith('om_msg1');
+ expect(events).toHaveLength(1);
+ expect(events[0].senderId).toBe('g/oc_chat1/omt_rec');
+ expect(mocks.pushPatchableOpener).toHaveBeenCalledWith(
+ 'g/oc_chat1/omt_rec',
+ 'om_recovered',
+ 'om_msg1',
+ );
+ vi.useRealTimers();
+ });
+
+ it('回执不确定耗尽后同账号重连仍能恢复, 不丢弃恢复链', async () => {
+ vi.useFakeTimers();
+ mocks.openThread.mockReset();
+ mocks.openThread.mockResolvedValue({ kind: 'unconfirmed' });
+ const events = collectMessages();
+ await connect();
+
+ await mocks.eventHandlers['im.message.receive_v1'](groupMainFlowMessage('耗尽后重连'));
+ await vi.advanceTimersByTimeAsync(10_000 + 30_000 + 90_000 + 1_000);
+ expect(events).toHaveLength(0);
+ expect(mocks.openThread).toHaveBeenCalledTimes(4);
+
+ await wsClient.stop({ announceOffline: false, reason: 'same-account-reconnect' });
+ await connect();
+ mocks.openThread.mockClear();
+ mocks.openThread.mockResolvedValueOnce({
+ kind: 'opened',
+ messageId: 'om_late',
+ threadId: 'omt_late',
+ });
+
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.openThread).toHaveBeenCalledWith('om_msg1');
+ expect(events).toHaveLength(1);
+ expect(events[0]?.senderId).toBe('g/oc_chat1/omt_late');
+ vi.useRealTimers();
+ });
+
+ it('回执不确定后恢复为 degraded 不视为确认无卡, 不降级派发', async () => {
+ vi.useFakeTimers();
+ mocks.openThread.mockReset();
+ mocks.openThread
+ .mockResolvedValueOnce({ kind: 'unconfirmed' })
+ .mockResolvedValueOnce({ kind: 'degraded' })
+ .mockResolvedValueOnce({
+ kind: 'opened',
+ messageId: 'om_late',
+ threadId: 'omt_late',
+ });
+ const events = collectMessages();
+ await connect();
+
+ await mocks.eventHandlers['im.message.receive_v1'](groupMainFlowMessage('先不确定后失败'));
+ expect(events).toHaveLength(0);
+
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.openThread).toHaveBeenCalledTimes(2);
+ expect(events).toHaveLength(0);
+ expect(mocks.pushReplyAnchor).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(events).toHaveLength(1);
+ expect(events[0]?.senderId).toBe('g/oc_chat1/omt_late');
+ expect(mocks.pushPatchableOpener).toHaveBeenCalledWith(
+ 'g/oc_chat1/omt_late',
+ 'om_late',
+ 'om_msg1',
+ );
+ vi.useRealTimers();
+ });
+
+ it('回执不确定耗尽定时重试后仍不降级群主流', async () => {
+ vi.useFakeTimers();
+ mocks.openThread.mockResolvedValue({ kind: 'unconfirmed' });
+ const events = collectMessages();
+ await connect();
+
+ await mocks.eventHandlers['im.message.receive_v1'](groupMainFlowMessage('一直不确定'));
+ await vi.advanceTimersByTimeAsync(10_000 + 30_000 + 90_000 + 1_000);
+
+ expect(events).toHaveLength(0);
+ expect(mocks.pushReplyAnchor).not.toHaveBeenCalled();
+ // 首次 + 三档延迟重试
+ expect(mocks.openThread).toHaveBeenCalledTimes(4);
+ vi.useRealTimers();
+ });
+
+ it('stop 挂起超过 100 条 unconfirmed 后同账号重连仍恢复最早一条', async () => {
+ vi.useFakeTimers();
+ mocks.openThread.mockResolvedValue({ kind: 'unconfirmed' });
+ const events = collectMessages();
+ await connect();
+
+ for (let i = 0; i < 101; i += 1) {
+ await mocks.eventHandlers['im.message.receive_v1'](
+ groupMainFlowMessage(`回执不确定${i}`, `om_unconfirmed_${i}`),
+ );
+ }
+ expect(events).toHaveLength(0);
+
+ await wsClient.stop({ announceOffline: false, reason: 'same-account-reconnect' });
+ await connect();
+ mocks.openThread.mockClear();
+ mocks.openThread.mockImplementation(async (messageId?: string) => {
+ if (messageId === 'om_unconfirmed_0') {
+ return { kind: 'opened' as const, messageId: 'om_first', threadId: 'omt_first' };
+ }
+ return { kind: 'unconfirmed' as const };
+ });
+
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.openThread).toHaveBeenCalledWith('om_unconfirmed_0');
+ expect(events.some((event) => event.messageId === 'om_unconfirmed_0')).toBe(true);
+ vi.useRealTimers();
+ });
+
+ it('延迟恢复 await openThread 期间换账号后不再登记锚点或派发 turn', async () => {
+ vi.useFakeTimers();
+ let resolveOpen!: (value: {
+ kind: 'opened';
+ messageId: string;
+ threadId: string;
+ }) => void;
+ mocks.openThread
+ .mockResolvedValueOnce({ kind: 'unconfirmed' })
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveOpen = resolve;
+ }),
+ );
+ const events = collectMessages();
+ await connect();
+ await mocks.eventHandlers['im.message.receive_v1'](groupMainFlowMessage('换账号'));
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.openThread).toHaveBeenCalledTimes(2);
+
+ await wsClient.stop({ announceOffline: false, reason: 'switch-account' });
+ const connecting = wsClient.start(
+ { appId: 'cli_other_bot', appSecret: 'secret', service: 'feishu' },
+ { announceLifecycle: false },
+ );
+ mocks.options.at(-1)?.onReady?.();
+ await connecting;
+
+ resolveOpen({ kind: 'opened', messageId: 'om_stale', threadId: 'omt_stale' });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(events).toHaveLength(0);
+ expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();
+ expect(mocks.pushReplyAnchor).not.toHaveBeenCalled();
+ vi.useRealTimers();
+ });
});
diff --git a/packages/lizi-im/src/feishu/index.ts b/packages/lizi-im/src/feishu/index.ts
index 17082f0737..821f01b5ea 100644
--- a/packages/lizi-im/src/feishu/index.ts
+++ b/packages/lizi-im/src/feishu/index.ts
@@ -38,10 +38,288 @@ import * as streamingText from './streamingText.js';
import { downloadAttachments, type DownloadResult } from './attachmentDownloader.js';
import type { AttachmentRef } from './incomingContent.js';
+/** 连接仍在时重新入队后的排空退避: 100ms / 300ms / 900ms / 2.7s, 耗尽坐等下一次 connected。 */
+const CONNECTED_FLUSH_RETRY_DELAYS_MS = [100, 300, 900, 2700] as const;
+
export class FeishuIM extends BaseIM implements ChannelIM {
+ /** 重连空窗暂存的开场白卡消费在连接就绪后排空(见 deferOpenerConsume)。 */
+ private readonly offImStatus: () => void;
+ /** 串行排空, 避免 connected 与失败重试重叠处理同一条目。 */
+ private flushChain: Promise<void> = Promise.resolve();
+ /** 正在排空的条目: 兜底发送等它结束, 不另发一份相同终态。 */
+ private readonly flushingOpenerConsumes = new Map<
+ string,
+ Promise<{ messageId: string } | null>
+ >();
+ /** 排空已成功、尚未被原兜底发送认领的收据(按 openerId, 当拍过期)。 */
+ private readonly completedOpenerConsumes = new Map<string, { messageId: string }>();
+ private readonly completedOpenerConsumeTimers = new Map<string, ReturnType<typeof setTimeout>>();
+ /**
+ * 空窗暂存后, 只有「原兜底发送」可以认领排空结果。按 openerId 记账 —
+ * 同 lane 的后续发送(/help 等)不得复用上一轮的 messageId。
+ */
+ private readonly pendingFallbackOpenerIds = new Map<
+ string,
+ { userId: string; kind: 'markdown' | 'spec' }
+ >();
+ /** consume 暂存后按轮次压栈, 原兜底发送 pop 出本轮 openerId。 */
+ private readonly notedFallbackStacks = new Map<string, string[]>();
+ private retryFlushTimer: ReturnType<typeof setTimeout> | null = null;
+ private retryFlushAttempt = 0;
+ private disposed = false;
+
constructor(host: IMHost) {
super('feishu', host);
setHost(host, this.log);
+ const onImStatus = (status: IMStatus) => {
+ if (status.kind !== 'connected') return;
+ this.resetConnectedFlushRetry();
+ void this.flushDeferredOpenerConsumes();
+ };
+ feishuEvents.on('imStatus', onImStatus);
+ this.offImStatus = () => feishuEvents.off('imStatus', onImStatus);
+ }
+
+ private openerConsumeKey(userId: string, kind: 'markdown' | 'spec'): string {
+ return `${kind}:${userId}`;
+ }
+
+ private notePendingFallback(
+ userId: string,
+ kind: 'markdown' | 'spec',
+ openerId: string,
+ rememberForCaller = false,
+ ): void {
+ this.pendingFallbackOpenerIds.set(openerId, { userId, kind });
+ if (!rememberForCaller) return;
+ const key = this.openerConsumeKey(userId, kind);
+ const stack = this.notedFallbackStacks.get(key) ?? [];
+ stack.push(openerId);
+ this.notedFallbackStacks.set(key, stack);
+ }
+
+ takeNotedFallbackOpenerId(userId: string, kind: 'markdown' | 'spec'): string | undefined {
+ const key = this.openerConsumeKey(userId, kind);
+ const stack = this.notedFallbackStacks.get(key);
+ const openerId = stack?.pop();
+ if (stack && stack.length === 0) this.notedFallbackStacks.delete(key);
+ return openerId;
+ }
+
+ private claimFallbackOpenerId(
+ userId: string,
+ kind: 'markdown' | 'spec',
+ fallbackOpenerId: string | undefined,
+ ): string | undefined {
+ if (!fallbackOpenerId) return undefined;
+ const meta = this.pendingFallbackOpenerIds.get(fallbackOpenerId);
+ if (!meta || meta.userId !== userId || meta.kind !== kind) return undefined;
+ this.pendingFallbackOpenerIds.delete(fallbackOpenerId);
+ return fallbackOpenerId;
+ }
+
+ private rememberCompletedOpenerConsume(openerId: string, messageId: string): void {
+ this.completedOpenerConsumes.set(openerId, { messageId });
+ const prev = this.completedOpenerConsumeTimers.get(openerId);
+ if (prev) clearTimeout(prev);
+ this.completedOpenerConsumeTimers.set(
+ openerId,
+ setTimeout(() => {
+ this.completedOpenerConsumeTimers.delete(openerId);
+ this.completedOpenerConsumes.delete(openerId);
+ }, 0),
+ );
+ }
+
+ private takeCompletedOpenerConsume(openerId: string): { messageId: string } | undefined {
+ const receipt = this.completedOpenerConsumes.get(openerId);
+ if (!receipt) return undefined;
+ this.completedOpenerConsumes.delete(openerId);
+ const timer = this.completedOpenerConsumeTimers.get(openerId);
+ if (timer) {
+ clearTimeout(timer);
+ this.completedOpenerConsumeTimers.delete(openerId);
+ }
+ return receipt;
+ }
+
+ /** 取消挂起的排空重试并把退避进度清零(connected / 成功排空 / dispose)。 */
+ private resetConnectedFlushRetry(): void {
+ if (this.retryFlushTimer) {
+ clearTimeout(this.retryFlushTimer);
+ this.retryFlushTimer = null;
+ }
+ this.retryFlushAttempt = 0;
+ }
+
+ /**
+ * 当前连接仍在时重新入队后主动再排空, 不坐等下一次 connected。
+ * 用递增延迟 + 次数上限, 避免限流/权限/服务故障持续失败时零延迟 REST 风暴。
+ */
+ private scheduleConnectedFlushRetry(): void {
+ if (this.disposed || this.retryFlushTimer) return;
+ const delay = CONNECTED_FLUSH_RETRY_DELAYS_MS[this.retryFlushAttempt];
+ if (delay === undefined) {
+ this.log.warn(
+ 'flushDeferredOpenerConsumes: retry budget exhausted — waiting for next connected',
+ );
+ return;
+ }
+ this.retryFlushTimer = setTimeout(() => {
+ this.retryFlushTimer = null;
+ if (this.disposed || !outbound.getBoundClient()) return;
+ this.retryFlushAttempt += 1;
+ void this.flushDeferredOpenerConsumes();
+ }, delay);
+ }
+
+ private flushDeferredOpenerConsumes(): Promise<void> {
+ // drain + 登记在途必须同步: connected 与兜底发送发生在同一轮时,
+ // 发送才能看见正在排空的条目。
+ const batch = this.claimFlushBatch();
+ this.flushChain = this.flushChain.then(
+ () => this.processFlushBatch(batch),
+ () => this.processFlushBatch(batch),
+ );
+ return this.flushChain;
+ }
+
+ private claimFlushBatch(): {
+ pinnedClient: NonNullable<ReturnType<typeof outbound.getBoundClient>>;
+ epoch: number;
+ evicted: string[];
+ items: Array<{
+ entry: ReturnType<typeof outbound.drainDeferredOpenerConsumes>[number];
+ openerId: string;
+ resolveFlush: (result: { messageId: string } | null) => void;
+ }>;
+ } | null {
+ const pinnedClient = outbound.getBoundClient();
+ if (!pinnedClient) return null;
+ const pending = outbound.drainDeferredOpenerConsumes();
+ const evicted = outbound.drainEvictedOpeners();
+ if (pending.length === 0 && evicted.length === 0) return null;
+ const items = pending.map((entry) => {
+ let resolveFlush!: (result: { messageId: string } | null) => void;
+ const flushPromise = new Promise<{ messageId: string } | null>((resolve) => {
+ resolveFlush = resolve;
+ });
+ this.flushingOpenerConsumes.set(entry.openerId, flushPromise);
+ return { entry, openerId: entry.openerId, resolveFlush };
+ });
+ return { pinnedClient, epoch: outbound.getAccountEpoch(), evicted, items };
+ }
+
+ /** 排空重连空窗暂存的开场白卡消费(claim + patch/替换), 失败只 log。 */
+ private async processFlushBatch(
+ batch: ReturnType<FeishuIM['claimFlushBatch']>,
+ ): Promise<void> {
+ if (!batch) return;
+ const { pinnedClient, epoch, evicted, items } = batch;
+ let requeued = false;
+ // 容量淘汰的开场白卡: 撤回它们(条目没了, 但卡还在话题里 — 不撤回就是
+ // 永久「思考中」)。撤回经 pinnedClient, 失败只 log。
+ for (const evictedId of evicted) {
+ try {
+ await outbound.recallOwnMessageWith(pinnedClient, evictedId);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ this.log.warn(`flushDeferredOpenerConsumes evicted-opener recall failed: ${msg}`);
+ }
+ }
+ for (const { entry, openerId, resolveFlush } of items) {
+ // 每个条目处理前重新校验账号代次: 前一个条目的 patch await 期间换代
+ // 时, 剩余条目不得经新 client 修改旧账号的开场白 — 直接丢弃整批。
+ if (outbound.getAccountEpoch() !== epoch) {
+ this.log.info('flushDeferredOpenerConsumes: account changed — dropping remaining entries');
+ resolveFlush(null);
+ this.flushingOpenerConsumes.delete(openerId);
+ this.completedOpenerConsumes.delete(openerId);
+ continue;
+ }
+ // 条目在暂存时就原子预留了 opener(携带 id)— 排空直接使用, 不会被
+ // 后续轮次认领。在途 promise 已在 claimFlushBatch 同步登记。
+ try {
+ if ('markdown' in entry) {
+ await streamingText.patchMarkdown(openerId, entry.markdown);
+ } else {
+ await outbound.updateInteractive(openerId, entry.spec);
+ outbound.registerCardLane(entry.userId, openerId);
+ }
+ this.rememberCompletedOpenerConsume(openerId, openerId);
+ resolveFlush({ messageId: openerId });
+ } catch (err) {
+ // patch/替换失败: 与即时消费同口径 — 撤回开场白卡(pin 到排空开始
+ // 时的 client)并回拨锚点, 然后**补发终态兜底**。
+ const msg = err instanceof Error ? err.message : String(err);
+ this.log.warn(`flushDeferredOpenerConsumes failed: ${msg}`);
+ // 排空期间账号已换代/清凭证: 丢弃条目, 不撤回、不发送(旧账号终态
+ // 不得经新账号 client 呈现 — 跨账号红线)。
+ if (outbound.getAccountEpoch() !== epoch) {
+ this.log.info('flushDeferredOpenerConsumes: account changed — dropping entry');
+ resolveFlush(null);
+ continue;
+ }
+ // 撤回始终 pin 到排空开始时的 client — 同账号再次重连(而非换账号)
+ // 时旧 REST client 仍可尝试撤回, 不会留下永久「思考中」卡; 换账号
+ // 时 pinnedClient 属于旧账号, 用它撤回旧卡正是安全方向。
+ const recalled = await outbound.recallOwnMessageWith(pinnedClient, openerId);
+ // 撤回 await 期间也可能换代/清凭证 — 发送前**再次**校验账号代次,
+ // 旧账号终态不得经新 client 呈现(跨账号红线)。
+ if (outbound.getAccountEpoch() !== epoch) {
+ this.log.info('flushDeferredOpenerConsumes: account changed during recall — dropping entry');
+ resolveFlush(null);
+ continue;
+ }
+ if (!recalled) {
+ // 撤回失败: 思考中卡还在。不得回拨+另发, 否则用户同时看到卡和新回答。
+ this.log.warn('flushDeferredOpenerConsumes: recall failed — re-deferred');
+ outbound.deferOpenerConsume(entry);
+ this.notePendingFallback(
+ entry.userId,
+ 'markdown' in entry ? 'markdown' : 'spec',
+ entry.openerId,
+ );
+ requeued = true;
+ resolveFlush(null);
+ continue;
+ }
+ outbound.rearmAnchorToTrigger(entry.userId);
+ try {
+ // 走 outbound 直发, 避免再进 sendWithDeferred 等待自己造成死锁。
+ const sent =
+ 'markdown' in entry
+ ? await outbound.sendInteractive(entry.userId, {
+ body: entry.markdown,
+ buttons: [],
+ })
+ : await outbound.sendInteractive(entry.userId, entry.spec);
+ this.rememberCompletedOpenerConsume(openerId, sent.messageId);
+ resolveFlush(sent);
+ } catch (sendErr) {
+ // 兜底发送也失败: 重新入队并在当前连接上主动再排空。清凭证后
+ // 不得重新入队 — 否则登出前的终态会被重新呈现给新一轮会话。
+ const sendMsg = sendErr instanceof Error ? sendErr.message : String(sendErr);
+ if (outbound.getAccountEpoch() === epoch) {
+ this.log.warn(`flushDeferredOpenerConsumes fallback send failed (re-deferred): ${sendMsg}`);
+ outbound.deferOpenerConsume(entry);
+ this.notePendingFallback(
+ entry.userId,
+ 'markdown' in entry ? 'markdown' : 'spec',
+ entry.openerId,
+ );
+ requeued = true;
+ } else {
+ this.log.info('flushDeferredOpenerConsumes: credentials cleared — dropping entry');
+ }
+ resolveFlush(null);
+ }
+ } finally {
+ this.flushingOpenerConsumes.delete(openerId);
+ }
+ }
+ if (requeued) this.scheduleConnectedFlushRetry();
+ else this.retryFlushAttempt = 0;
}
// ── lifecycle ───────────────────────────────────────────────────────────────
@@ -72,7 +350,16 @@ export class FeishuIM extends BaseIM implements ChannelIM {
async dispose(): Promise<void> {
this.log.info('dispose');
+ this.disposed = true;
+ this.resetConnectedFlushRetry();
+ for (const timer of this.completedOpenerConsumeTimers.values()) clearTimeout(timer);
+ this.completedOpenerConsumeTimers.clear();
+ this.completedOpenerConsumes.clear();
+ this.pendingFallbackOpenerIds.clear();
+ this.notedFallbackStacks.clear();
+ this.offImStatus();
cancelAppRegistration();
+ await this.flushChain.catch(() => undefined);
await wsClient.stop({
offlineTimeoutMs: wsClient.QUIT_OFFLINE_ANNOUNCE_TIMEOUT_MS,
reason: 'transport-dispose',
@@ -107,8 +394,17 @@ export class FeishuIM extends BaseIM implements ChannelIM {
// ── outbound ────────────────────────────────────────────────────────────────
- sendText(userId: string, text: string): Promise<{ messageId: string }> {
- return outbound.sendText(userId, text);
+ async sendText(
+ userId: string,
+ text: string,
+ opts?: { threadTs?: string; fallbackOpenerId?: string },
+ ): Promise<{ messageId: string }> {
+ return this.sendWithDeferredOpenerConsume(
+ userId,
+ 'markdown',
+ () => outbound.sendText(userId, text),
+ opts?.fallbackOpenerId,
+ );
}
/**
@@ -122,8 +418,17 @@ export class FeishuIM extends BaseIM implements ChannelIM {
* 适合发"提示语"类消息 — 文案里有 *strong*, `code`, [link] 等且想让用户
* 看到正确渲染的场合。
*/
- sendMarkdownText(userId: string, markdown: string): Promise<{ messageId: string }> {
- return outbound.sendInteractive(userId, { body: markdown, buttons: [] });
+ async sendMarkdownText(
+ userId: string,
+ markdown: string,
+ opts?: { threadTs?: string; fallbackOpenerId?: string },
+ ): Promise<{ messageId: string }> {
+ return this.sendWithDeferredOpenerConsume(
+ userId,
+ 'markdown',
+ () => outbound.sendInteractive(userId, { body: markdown, buttons: [] }),
+ opts?.fallbackOpenerId,
+ );
}
startStreamingText(userId: string, initial?: string): Promise<StreamingTextHandle> {
@@ -138,12 +443,275 @@ export class FeishuIM extends BaseIM implements ChannelIM {
return streamingText.patchMarkdown(messageId, markdown);
}
- sendInteractiveCard(
+ /**
+ * 消费群主流 @ 开话题的 pending 开场白卡: 认领并把 markdown patch 上去 —
+ * 非流式终态(!stop / 纯 unsupported)截流时, 「思考中」卡就地变成回复,
+ * 不会卡住也不会被同话题下一条消息 patch 错卡。无 pending opener、或
+ * 同账号空窗暂存, 返回 false(调用方走正常发送)。patch 失败且账号已换代
+ * 时返回 true: 旧轮次已丢弃, 调用方不得用新 client 跨账号发。
+ */
+ async consumePendingOpenerCard(userId: string, markdown: string): Promise<boolean> {
+ // 重连空窗(stop→start 之间 client 已解绑): 暂存消费, 连接就绪后由
+ // flushDeferredOpenerConsumes 排空(claim + patch)— 不认领(注册保留)、
+ // 也不让本轮终态丢失或残留被下一条消息误认领。返回 **false**(仅入队,
+ // 未送达): 调用方走兜底发送(空窗内必然失败、被既有 catch 收口), 且
+ // /ctr 等「仅送达后进入控制态」的调用方不会被误导。
+ // 重连空窗(stop→start 之间 client 已解绑): **原子预留** opener(claim
+ // 并随条目携带 id)— 后续消息的 streamingText.start 不会误认领这张卡,
+ // 排空时也不会因已被领取而静默丢弃; 排空失败可重新入队重试。
+ const reservedOpenerId = outbound.claimPatchableOpener(userId);
+ if (!outbound.getBoundClient()) {
+ if (reservedOpenerId) {
+ outbound.deferOpenerConsume({ userId, openerId: reservedOpenerId, markdown });
+ this.notePendingFallback(userId, 'markdown', reservedOpenerId, true);
+ }
+ return false;
+ }
+ const openerId = reservedOpenerId;
+ if (!openerId) return false;
+ // 触发时的 client / 账号代次 — patch 失败后撤回必须 pin 到它们:
+ // 中途换凭证时不得拿新账号的 client 删除旧账号的开场白, 也不得指示
+ // 调用方用新 client 向旧 lane 回落发送。
+ const triggeringClient = outbound.getBoundClient();
+ const epoch = outbound.getAccountEpoch();
+ try {
+ await streamingText.patchMarkdown(openerId, markdown);
+ return true;
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ this.log.warn(`consumePendingOpenerCard patch failed: ${msg}`);
+ return this.recoverFailedOpenerConsume(userId, openerId, epoch, triggeringClient, {
+ markdown,
+ });
+ }
+ }
+
+ /**
+ * 消费群主流 @ 开话题的 pending 开场白卡并把卡片 spec 原地替换上去 —
+ * slash 的首个卡片反馈(/ctr picker、/model 选择卡等)就地变成开场白卡,
+ * 话题里只有一张卡且锚点有效(不是撤回后拿已删消息当锚点)。无 pending
+ * opener、或同账号空窗暂存, 返回 false(调用方走正常发卡)。替换失败且
+ * 账号已换代时返回 true: 旧轮次已丢弃, 调用方不得跨账号发卡。
+ */
+ async consumePendingOpenerAsCard(userId: string, spec: InteractiveCardSpec): Promise<boolean> {
+ // 同 consumePendingOpenerCard: 重连空窗暂存(未送达, 返回 false),
+ // 连接就绪后排空。false 让 safeSendCard 报告未送达 — /ctr 不会在
+ // 卡片尚未可见时 enterControl(否则重连失败/排空失败会把用户锁死)。
+ const reservedOpenerId = outbound.claimPatchableOpener(userId);
+ if (!outbound.getBoundClient()) {
+ if (reservedOpenerId) {
+ outbound.deferOpenerConsume({ userId, openerId: reservedOpenerId, spec });
+ this.notePendingFallback(userId, 'spec', reservedOpenerId, true);
+ }
+ return false;
+ }
+ const openerId = reservedOpenerId;
+ if (!openerId) return false;
+ // 同 consumePendingOpenerCard: 撤回 pin 到触发时的 client, 失败路径核代次。
+ const triggeringClient = outbound.getBoundClient();
+ const epoch = outbound.getAccountEpoch();
+ try {
+ await outbound.updateInteractive(openerId, spec);
+ // 替换后的交互卡同样要登记发卡 lane — 否则按钮回调 resolveCardLane
+ // 查不到, 被 cardActionHandler 的群卡 fail-closed 门当旧卡拒绝。
+ outbound.registerCardLane(userId, openerId);
+ return true;
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ this.log.warn(`consumePendingOpenerAsCard replace failed: ${msg}`);
+ return this.recoverFailedOpenerConsume(userId, openerId, epoch, triggeringClient, {
+ spec,
+ });
+ }
+ }
+
+ /**
+ * patch/替换失败后的账号代次门。未换账号且撤回成功才能回拨+回落发送;
+ * 撤回失败重新暂存走有界排空(思考中卡还在, 不得另发); 同账号空窗重新暂存;
+ * 已换账号丢弃旧轮次并返回 true, 避免调用方用新 client 向旧 lane 发送。
+ */
+ private async recoverFailedOpenerConsume(
+ userId: string,
+ openerId: string,
+ epoch: number,
+ triggeringClient: ReturnType<typeof outbound.getBoundClient>,
+ payload: { markdown: string } | { spec: InteractiveCardSpec },
+ ): Promise<boolean> {
+ if (outbound.getAccountEpoch() !== epoch) {
+ this.log.info('consumePendingOpener: account changed — dropping turn');
+ if (triggeringClient) {
+ const recalled = await outbound.recallOwnMessageWith(triggeringClient, openerId);
+ if (!recalled) {
+ this.log.warn('consumePendingOpener: recall failed after account change — dropping turn');
+ }
+ }
+ return true;
+ }
+ if (!outbound.getBoundClient()) {
+ this.log.warn('consumePendingOpener: reconnect window — re-deferred');
+ outbound.deferOpenerConsume({ userId, openerId, ...payload });
+ this.notePendingFallback(
+ userId,
+ 'markdown' in payload ? 'markdown' : 'spec',
+ openerId,
+ true,
+ );
+ return false;
+ }
+ if (triggeringClient) {
+ const recalled = await outbound.recallOwnMessageWith(triggeringClient, openerId);
+ if (outbound.getAccountEpoch() !== epoch) {
+ this.log.info('consumePendingOpener: account changed during recall — dropping turn');
+ return true;
+ }
+ if (!recalled) {
+ // 撤回失败: 思考中卡还在。不回拨、不让调用方另发; 重新暂存走有界排空。
+ this.log.warn('consumePendingOpener: recall failed — re-deferred');
+ outbound.deferOpenerConsume({ userId, openerId, ...payload });
+ this.notePendingFallback(
+ userId,
+ 'markdown' in payload ? 'markdown' : 'spec',
+ openerId,
+ true,
+ );
+ this.scheduleConnectedFlushRetry();
+ return false;
+ }
+ } else if (outbound.getAccountEpoch() !== epoch) {
+ this.log.info('consumePendingOpener: account changed during recall — dropping turn');
+ return true;
+ }
+ outbound.rearmAnchorToTrigger(userId);
+ return false;
+ }
+
+ getPendingOpenerTrigger(userId: string): string | undefined {
+ return outbound.getOpenerTrigger(userId);
+ }
+
+ async sendInteractiveCard(
userId: string,
spec: InteractiveCardSpec,
- opts?: { threadTs?: string; deliverToOwnerDm?: boolean; ownerDmNote?: string },
+ opts?: {
+ threadTs?: string;
+ fallbackOpenerId?: string;
+ deliverToOwnerDm?: boolean;
+ ownerDmNote?: string;
+ },
): Promise<{ messageId: string }> {
- return outbound.sendInteractive(userId, spec, opts);
+ return this.sendWithDeferredOpenerConsume(
+ userId,
+ 'spec',
+ () => outbound.sendInteractive(userId, spec, opts),
+ opts?.fallbackOpenerId,
+ );
+ }
+
+ /**
+ * 兜底发送包装: 空窗暂存后连接已恢复时, 优先**就地收口**被预留的 opener
+ * (patch/替换暂存内容)而不是另发 — 不留「思考中」卡、不重复呈现同一终态。
+ * 收口失败则撤回预留卡 + 回拨锚点, 回落正常发送。
+ */
+ private async sendWithDeferredOpenerConsume(
+ userId: string,
+ kind: 'markdown' | 'spec',
+ send: () => Promise<{ messageId: string }>,
+ requestedFallbackOpenerId?: string,
+ ): Promise<{ messageId: string }> {
+ const epoch = outbound.getAccountEpoch();
+ const clientAtTake = outbound.getBoundClient();
+ const fallbackOpenerId = this.claimFallbackOpenerId(userId, kind, requestedFallbackOpenerId);
+ if (fallbackOpenerId) {
+ const flushing = this.flushingOpenerConsumes.get(fallbackOpenerId);
+ if (flushing) {
+ const flushed = await flushing;
+ this.takeCompletedOpenerConsume(fallbackOpenerId);
+ // 排空已成功就复用收据, 即使等待期间换了代 — 旧卡已就地收口,
+ // 不再经新账号 client 另发。只有排空以 null 收口时才要拦回落发送。
+ if (flushed) return flushed;
+ if (outbound.getAccountEpoch() !== epoch) {
+ // 等待期间换代: 排空以 null 收口并丢掉旧条目。这里若继续
+ // send() 会用新账号 client 把旧轮次终态打到旧 lane。
+ this.log.info(
+ 'sendWithDeferredOpenerConsume: account changed while waiting for flush — dropping turn',
+ );
+ throw new Error('account changed while waiting for opener flush');
+ }
+ } else {
+ const completed = this.takeCompletedOpenerConsume(fallbackOpenerId);
+ if (completed) return completed;
+ }
+ }
+ const entry = fallbackOpenerId
+ ? outbound.takeDeferredOpenerConsumeById(fallbackOpenerId)
+ : undefined;
+ if (entry) {
+ if (entry.epoch !== epoch) {
+ // 条目属于旧账号: 丢弃(不得跨账号 patch/撤回/发送), 调用方内容
+ // 是当前账号的, 照常发送。
+ this.log.info('sendWithDeferredOpenerConsume: stale-account entry dropped');
+ return send();
+ }
+ try {
+ if ('markdown' in entry) {
+ await streamingText.patchMarkdown(entry.openerId, entry.markdown);
+ } else {
+ await outbound.updateInteractive(entry.openerId, entry.spec);
+ outbound.registerCardLane(userId, entry.openerId);
+ }
+ return { messageId: entry.openerId };
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ // 就地收口失败。换代/清凭证: 丢弃(跨账号红线); 空窗(仍无 client):
+ // 重新入队等下一次 connected 排空; 否则撤回预留卡 + 回拨 + 回落。
+ if (outbound.getAccountEpoch() !== epoch) {
+ this.log.info('sendWithDeferredOpenerConsume: account changed mid-patch — dropping entry');
+ throw err;
+ }
+ if (!outbound.getBoundClient()) {
+ this.log.warn(`sendWithDeferredOpenerConsume patch failed in reconnect window (re-deferred): ${msg}`);
+ outbound.deferOpenerConsume(entry);
+ this.notePendingFallback(userId, kind, entry.openerId);
+ throw err;
+ }
+ this.log.warn(`sendWithDeferredOpenerConsume patch failed (recalling reserved opener): ${msg}`);
+ const recalled = await outbound.recallOwnMessageWith(
+ clientAtTake ?? outbound.getBoundClient()!,
+ entry.openerId,
+ );
+ // 撤回 await 期间也可能再次断线 — 发送前复查代次(跨账号红线)。
+ if (outbound.getAccountEpoch() !== epoch) {
+ this.log.info('sendWithDeferredOpenerConsume: account changed during recall — dropping entry');
+ throw err;
+ }
+ if (!recalled) {
+ // 撤回失败: 思考中卡还在。不回拨、不另发; 外层 catch 重新入队排空。
+ this.log.warn('sendWithDeferredOpenerConsume: recall failed — keeping opener for retry');
+ throw err;
+ }
+ outbound.rearmAnchorToTrigger(userId);
+ // fallthrough: 回落正常发送
+ }
+ }
+ const sendClient = outbound.getBoundClient();
+ try {
+ return await send();
+ } catch (sendErr) {
+ // 最终兜底失败: 条目已从队列移除。账号代次未变时重新入队并走有界
+ // 退避排空 — 限流/临时故障时 client 可能没换代, 不能只在换 client
+ // 时才重试, 否则终态永久丢失。
+ if (entry && outbound.getAccountEpoch() === epoch) {
+ this.log.warn(
+ outbound.getBoundClient() !== sendClient
+ ? 'sendWithDeferredOpenerConsume final send failed across reconnect (re-deferred)'
+ : 'sendWithDeferredOpenerConsume final send failed (re-deferred for flush retry)',
+ );
+ outbound.deferOpenerConsume(entry);
+ this.notePendingFallback(userId, kind, entry.openerId);
+ this.scheduleConnectedFlushRetry();
+ }
+ throw sendErr;
+ }
}
updateInteractiveCard(messageId: string, spec: InteractiveCardSpec): Promise<void> {
diff --git a/packages/lizi-im/src/feishu/ipc.ts b/packages/lizi-im/src/feishu/ipc.ts
index 92c4792de6..abd3f7caa9 100644
--- a/packages/lizi-im/src/feishu/ipc.ts
+++ b/packages/lizi-im/src/feishu/ipc.ts
@@ -19,6 +19,7 @@ import { feishuEvents } from './events.js';
import * as wsClient from './wsClient.js';
import * as storage from './storage.js';
import * as ownerGuard from './ownerGuard.js';
+import * as outbound from './outbound.js';
import {
pollAppRegistration,
requestAppRegistration,
@@ -387,5 +388,10 @@ export async function clearAndDisconnect(): Promise<void> {
reason: 'credentials-cleared',
clearOwnerBeforeIdle: true,
});
+ // 逻辑凭证清除(而非 transport 重连): 清掉账号态并重置 lastBoundCreds —
+ // 之后重新保存相同 appId/service 不会被误判为同账号重连, 登出前的
+ // opener/锚点不会被新一轮会话认领; 挂起的孤儿提示重试同样丢弃。
+ outbound.forgetBoundAccount();
+ wsClient.clearOrphanRetriesForCredentialClear();
storage.clearAll();
}
diff --git a/packages/lizi-im/src/feishu/messages.ts b/packages/lizi-im/src/feishu/messages.ts
index 3021b86bee..f7dae0d79c 100644
--- a/packages/lizi-im/src/feishu/messages.ts
+++ b/packages/lizi-im/src/feishu/messages.ts
@@ -20,6 +20,12 @@ export const messages = {
/** 非 owner 在群里 @bot 的礼貌回应(per-user 冷却防刷屏, 与 telegram 同语义)。 */
strangerNotice:
'👋 我是一位主人的个人 Cindy 助理,只响应主人本人的指令~\nI am a personal Cindy assistant and only respond to my owner.',
+ /**
+ * 开场白卡已发出但话题 id 无法恢复、撤回也失败时的兜底提示 — 回复落在
+ * 开场白所在话题内, 本轮不起 turn(降级群 lane 会一边留着「思考中」的
+ * 开场白卡一边把回答刷进群主流)。per-opener 冷却防重投事件重复提示。
+ */
+ threadOrphanNotice: '开话题出了点小问题, 这条没能处理, 麻烦再 @ 我一次~',
},
// (inbound.skipped removed — orchestrator owns the wording for "pure
// unsupported" / "mixed unsupported" replies; @cindy/im just emits the raw
diff --git a/packages/lizi-im/src/feishu/outbound.ts b/packages/lizi-im/src/feishu/outbound.ts
index 7665e88201..4a0cd22d69 100644
--- a/packages/lizi-im/src/feishu/outbound.ts
+++ b/packages/lizi-im/src/feishu/outbound.ts
@@ -40,7 +40,52 @@ const FEISHU_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
let client: Lark.Client | null = null;
let creds: BotCredentials | null = null;
+/** 最近一次 bind 的账号身份 — 跨 unbind 保留, 用于判「账号是否真替换」。 */
+let lastBoundCreds: BotCredentials | null = null;
+
+function sameBoundAccount(next: BotCredentials): boolean {
+ return (
+ lastBoundCreds !== null &&
+ lastBoundCreds.appId === next.appId &&
+ lastBoundCreds.service === next.service
+ );
+}
+
+/**
+ * 账号代次 — 账号身份变化(换账号 bind / 明确清凭证)时递增: 在途的排空/兜底
+ * 续段据此丢弃, 旧账号的终态不得经新账号的 client 呈现。
+ */
+let accountEpoch = 0;
+
+function clearAccountScopedOutboundState(): void {
+ laneAnchors.clear();
+ patchableOpeners.clear();
+ openerTriggers.clear();
+ clearDeferredOpenerConsumes();
+ accountEpoch += 1;
+}
+
+/**
+ * 明确清除凭证/登出路径(clearAndDisconnect)用: 与 transport 重连区分 —
+ * 清掉账号态并重置 lastBoundCreds, 之后重新保存相同 appId/service 不会被
+ * 误判为同账号重连(登出前的 opener/锚点不得被新一轮会话认领)。
+ */
+export function forgetBoundAccount(): void {
+ clearAccountScopedOutboundState();
+ lastBoundCreds = null;
+}
+
+/** 当前账号代次(清凭证递增) — 在途排空续段比对用。 */
+export function getAccountEpoch(): number {
+ return accountEpoch;
+}
+
export function bindClient(c: BotCredentials): void {
+ // 账号真正替换(appId/service 变化)才清开场白卡与话题锚点: 同账号 transport
+ // 重连(reconnectSavedCredentials: stop → start 同凭证)时 turn 仍在跑, 未消费
+ // 的 opener / 锚点必须仍可被认领, 否则答案无处 patch、话题出站没有 reply 根。
+ if (!sameBoundAccount(c)) clearAccountScopedOutboundState();
+ lastBoundCreds = c;
creds = c;
client = new Lark.Client({
appId: c.appId,
@@ -52,8 +97,8 @@ export function bindClient(c: BotCredentials): void {
export function unbindClient(): void {
client = null;
creds = null;
- laneAnchors.clear();
cardLanes.clear();
+ // patchableOpeners / laneAnchors 不随 unbind 清空(见 bindClient 的账号替换清理)。
}
// ── group lane reply anchors ──────────────────────────────────────────────────
@@ -61,7 +106,7 @@ export function unbindClient(): void {
// 出站按回合领取(流式建卡时 advance)。话题 lane 的**所有**出站都走 reply
// 锚点 — 被回复消息在话题里, 回复自动落回话题(会话与挂回一次解决);
// 普通群 lane 只有回合首条出站 reply(引用式"挂在提问下"), 后续 chat_id 直发。
-// 连接换代(unbindClient)清空 — 旧锚点不跨代错配(telegram 同语义)。
+// 账号替换时清空 — 同账号 transport 重连保留, 避免进行中的 turn 丢掉话题锚点。
interface LaneAnchorState {
/** 待领取的触发消息 id FIFO(多条消息先后触发同一 lane 各自排队)。 */
@@ -70,13 +115,23 @@ interface LaneAnchorState {
held: string | null;
/** 普通群: held 是否已用于引用回复(用过则后续 chat_id 直发)。 */
quotedHeld: boolean;
+ /**
+ * held 是群主流触发消息(开场白撤回后的回拨锚点)时置位 — 对它 reply 必须带
+ * reply_in_thread 才会落回话题(触发消息本人在群主流)。
+ */
+ inThreadReply: boolean;
}
const laneAnchors = new Map<string, LaneAnchorState>();
/** wsClient 在 owner 群触发时登记回挂锚点。 */
export function pushReplyAnchor(laneUserId: string, messageId: string): void {
- const state = laneAnchors.get(laneUserId) ?? { queue: [], held: null, quotedHeld: false };
+ const state = laneAnchors.get(laneUserId) ?? {
+ queue: [],
+ held: null,
+ quotedHeld: false,
+ inThreadReply: false,
+ };
state.queue.push(messageId);
laneAnchors.set(laneUserId, state);
}
@@ -88,8 +143,20 @@ export function pushReplyAnchor(laneUserId: string, messageId: string): void {
const patchableOpeners = new Map<string, string>();
-export function pushPatchableOpener(laneUserId: string, messageId: string): void {
+/**
+ * 开场白卡对应的触发消息 id(lane → 群主流触发消息)。开场白 patch/替换失败
+ * 被撤回后, 话题里不再有合法锚点 — 回拨到触发消息并带 reply_in_thread 回复
+ * 才能落回话题(触发消息本人在群主流)。
+ */
+const openerTriggers = new Map<string, string>();
+
+export function pushPatchableOpener(
+ laneUserId: string,
+ messageId: string,
+ triggerMessageId?: string,
+): void {
patchableOpeners.set(laneUserId, messageId);
+ if (triggerMessageId) openerTriggers.set(laneUserId, triggerMessageId);
}
/**
@@ -101,19 +168,138 @@ export function claimPatchableOpener(laneUserId: string): string | null {
const openerId = patchableOpeners.get(laneUserId);
if (!openerId) return null;
patchableOpeners.delete(laneUserId);
- const state = laneAnchors.get(laneUserId) ?? { queue: [], held: null, quotedHeld: false };
+ // openerTriggers 保留 — patch/替换失败撤回开场白卡时需要回拨锚点
+ // (rearmAnchorToTrigger 消费); 正常认领成功则随下次 push 覆盖或账号替换清空。
+ const state = laneAnchors.get(laneUserId) ?? {
+ queue: [],
+ held: null,
+ quotedHeld: false,
+ inThreadReply: false,
+ };
// 锚点队列头正常就是这张开场白卡; 对不上说明顺序被破坏, 保守起见仍保留队列。
if (state.queue[0] === openerId) state.queue.shift();
state.held = openerId;
state.quotedHeld = true;
+ state.inThreadReply = false;
laneAnchors.set(laneUserId, state);
return openerId;
}
+/**
+ * 重连空窗(outbound client 已解绑)时到达的开场白卡消费暂存 — 同账号重连后
+ * 由 FeishuIM 排空(见 drainDeferredOpenerConsumes): 若此时直接认领, 后续
+ * patch/撤回全部失败且注册被永久移除; 若完全放弃, 本轮终态丢失且注册残留
+ * 会被下一条消息误认领。上限防御, 超限丢最旧。
+ */
+export type DeferredOpenerConsume = (
+ | { userId: string; openerId: string; markdown: string }
+ | { userId: string; openerId: string; spec: InteractiveCardSpec }
+) & { epoch: number };
+
+const MAX_DEFERRED_OPENER_CONSUMES = 50;
+const deferredOpenerConsumes: DeferredOpenerConsume[] = [];
+
+/**
+ * 容量淘汰的开场白卡 id — 条目被挤掉时其 opener 已被原子预留(不可再认领),
+ * 静默删除会留下永久「思考中」卡: 记录 id, 连接恢复排空时撤回。
+ */
+// 上限防御撤除: 每个条目只是短消息 id, 且连接恢复排空即清 — 有界淘汰会
+// 再次静默丢卡(阈值从 51 推迟到 101 而已), 不留可收口记录违背设计。
+const evictedOpeners: string[] = [];
+
+/** 账号替换时清空暂存消费(属旧账号的开场白卡, 新账号不需要)。 */
+function clearDeferredOpenerConsumes(): void {
+ deferredOpenerConsumes.length = 0;
+ evictedOpeners.length = 0;
+}
+
+export function deferOpenerConsume(
+ entry: { userId: string; openerId: string } & (
+ | { markdown: string }
+ | { spec: InteractiveCardSpec }
+ ),
+): void {
+ deferredOpenerConsumes.push({ ...entry, epoch: accountEpoch });
+ while (deferredOpenerConsumes.length > MAX_DEFERRED_OPENER_CONSUMES) {
+ const evicted = deferredOpenerConsumes.shift();
+ if (evicted) {
+ evictedOpeners.push(evicted.openerId);
+ }
+ }
+}
+
+/** 取出被容量淘汰的开场白卡 id(清空), 连接恢复排空时撤回。 */
+export function drainEvictedOpeners(): string[] {
+ return evictedOpeners.splice(0, evictedOpeners.length);
+}
+
+/** 取出全部暂存的消费(清空), 调用方在连接就绪后排空。 */
+export function drainDeferredOpenerConsumes(): DeferredOpenerConsume[] {
+ return deferredOpenerConsumes.splice(0, deferredOpenerConsumes.length);
+}
+
+/**
+ * 取出并移除某 lane 的匹配暂存消费 — 调用方的兜底发送在连接恢复后执行时,
+ * 优先就地收口被预留的 opener(见 FeishuIM 的发送包装): patch/替换成功即
+ * 不再另发、不留卡; 无匹配返回 undefined。
+ */
+export function takeMatchingDeferredOpenerConsume(
+ userId: string,
+ kind: 'markdown' | 'spec',
+): DeferredOpenerConsume | undefined {
+ for (let i = deferredOpenerConsumes.length - 1; i >= 0; i--) {
+ const entry = deferredOpenerConsumes[i]!;
+ if (entry.userId !== userId) continue;
+ if (kind === 'markdown' && !('markdown' in entry)) continue;
+ if (kind === 'spec' && !('spec' in entry)) continue;
+ deferredOpenerConsumes.splice(i, 1);
+ return entry;
+ }
+ return undefined;
+}
+
+/** 按 openerId 取出暂存消费 — 原兜底发送认领本轮条目, 避免同 lane 后续发送误领。 */
+export function takeDeferredOpenerConsumeById(openerId: string): DeferredOpenerConsume | undefined {
+ const index = deferredOpenerConsumes.findIndex((entry) => entry.openerId === openerId);
+ if (index < 0) return undefined;
+ return deferredOpenerConsumes.splice(index, 1)[0];
+}
+
+/**
+ * 返回该 lane 上 pending opener 的触发消息 id(没有则返回 undefined)。
+ * 调用方用它判断「这张思考卡是不是本轮消息创建的」— 空文本终态等场景下
+ * 不应消费上一轮遗留的 opener。
+ */
+export function getOpenerTrigger(laneUserId: string): string | undefined {
+ return openerTriggers.get(laneUserId);
+}
+
+/**
+ * patch/替换失败撤回开场白卡后调用: 把 held 锚点回拨到触发消息(带
+ * reply_in_thread 标记)。兜底发送向触发消息 reply 且 reply_in_thread=true,
+ * 仍落回话题 — 而不是向已删除的开场白卡 reply 失败。无触发记录返回 false。
+ */
+export function rearmAnchorToTrigger(laneUserId: string): boolean {
+ const triggerId = openerTriggers.get(laneUserId);
+ openerTriggers.delete(laneUserId);
+ if (!triggerId) return false;
+ const state = laneAnchors.get(laneUserId) ?? {
+ queue: [],
+ held: null,
+ quotedHeld: false,
+ inThreadReply: false,
+ };
+ state.held = triggerId;
+ state.quotedHeld = true;
+ state.inThreadReply = true;
+ laneAnchors.set(laneUserId, state);
+ return true;
+}
+
type SendTarget =
| { kind: 'open_id'; id: string }
| { kind: 'chat_id'; id: string }
- | { kind: 'reply'; messageId: string };
+ | { kind: 'reply'; messageId: string; replyInThread?: boolean };
/**
* userId → 本次出站目标。
@@ -127,7 +313,12 @@ function resolveSendTarget(userId: string, opts?: { advanceRound?: boolean }): S
const lane = decodeLaneUserId(userId);
if (!lane) return { kind: 'open_id', id: userId };
- const state = laneAnchors.get(userId) ?? { queue: [], held: null, quotedHeld: false };
+ const state = laneAnchors.get(userId) ?? {
+ queue: [],
+ held: null,
+ quotedHeld: false,
+ inThreadReply: false,
+ };
laneAnchors.set(userId, state);
// 领取条件: advanceRound(流式建卡 = 新回合)必领; 其余出站只在完全没有
// 持有时领(首次一次性回复)。回合中途的卡片/文件**不领** — 队列里可能已经
@@ -136,12 +327,16 @@ function resolveSendTarget(userId: string, opts?: { advanceRound?: boolean }): S
if ((opts?.advanceRound || !state.held) && state.queue.length > 0) {
state.held = state.queue.shift() ?? null;
state.quotedHeld = false;
+ state.inThreadReply = false;
}
if (lane.threadId) {
// 话题 lane: 必须 reply 锚点才能落回话题; 没有锚点宁可失败也不能把
- // 消息发进群主流(位置错误比丢失更糟)。
- return state.held ? { kind: 'reply', messageId: state.held } : null;
+ // 消息发进群主流(位置错误比丢失更糟)。held 是回拨的群主流触发消息时
+ // 带 reply_in_thread 回复才能落回话题。
+ return state.held
+ ? { kind: 'reply', messageId: state.held, replyInThread: state.inThreadReply || undefined }
+ : null;
}
if (state.held && !state.quotedHeld) {
state.quotedHeld = true;
@@ -160,7 +355,12 @@ async function createMessage(
if (target.kind === 'reply') {
const res = await c.im.v1.message.reply({
path: { message_id: target.messageId },
- data: { content, msg_type: msgType },
+ data: {
+ content,
+ msg_type: msgType,
+ // 回拨到群主流触发消息的锚点: 必须 reply_in_thread 才落回话题。
+ ...(target.replyInThread ? { reply_in_thread: true } : {}),
+ },
});
const id = res.data?.message_id ?? '';
if (!id) throw new Error('[feishu/outbound] reply: no message_id in response');
@@ -223,16 +423,32 @@ export async function replyText(
// promise, 已完成的按 TTL 短缓存 — 重投事件直接复用同一个话题。缓存键是
// 触发消息 id(平台内唯一), 不随 unbindClient 清空(换代不会重放别的消息 id)。
-interface OpenThreadResult {
- messageId: string;
- threadId: string;
-}
+/** 开话题结果 — 调用方按状态决定路由与降级(见 openThread 文档)。 */
+export type OpenThreadOutcome =
+ /** 话题已开, 开场白 messageId + threadId 都是话题内合法锚点/身份。 */
+ | { kind: 'opened'; messageId: string; threadId: string }
+ /** 无可确认已发出的开场白(API 失败/无 id, 或已成功撤回) — 可降级群 lane。 */
+ | { kind: 'degraded' }
+ /**
+ * 开场白已发出但 thread_id 恢复失败、撤回也失败 — 开场白孤立在话题里。
+ * 降级群 lane 会一边留着「思考中」的开场白卡、一边把回答刷进群主流;
+ * 调用方应回复开场白(落回话题)说明失败并放弃本轮, 而不是降级。
+ */
+ | { kind: 'orphaned'; openerMessageId: string }
+ /**
+ * reply 在超时/断线后用同一 uuid 有界重试仍拿不到回执 — 服务端可能已经
+ * 发出「思考中」卡。不能降级群 lane(会刷屏 + 留卡), 调用方应放弃本轮
+ * 并 evict 缓存, 让重投再用同一 uuid 取回原 message_id/thread_id。
+ */
+ | { kind: 'unconfirmed' };
const OPEN_THREAD_DEDUP_TTL_MS = 10 * 60_000;
const OPEN_THREAD_DEDUP_MAX_ENTRIES = 200;
+/** 超时/断线后用同一 uuid 再打 reply 的次数(不含首次)。 */
+const OPEN_THREAD_UNCERTAIN_RETRIES = 2;
const openThreadByTrigger = new Map<
string,
- { ts: number; promise: Promise<OpenThreadResult | null> }
+ { ts: number; promise: Promise<OpenThreadOutcome> }
>();
function pruneOpenThreadDedup(): void {
@@ -259,78 +475,199 @@ function pruneOpenThreadDedup(): void {
* 本轮流式卡**: 发一张「思考中」占位卡片(message 可被 patch 升级成正文),
* 之后流式卡直接 patch 它 — 话题里不会多出一条「开个话题聊这条」的占位
* 消息, 第一条可见内容就是答案本身(streamingText.start 经
- * claimPatchableOpener 认领)。返回开场白卡 id + 新话题 thread_id。
- * 同一触发消息并发/重复调用共享同一次开话题 — 防飞书重投事件开出多个话题
- * (含进程重启: uuid 走服务端去重)。
+ * claimPatchableOpener 认领)。返回 opened / degraded / orphaned / unconfirmed
+ * (见类型注释)。同一触发消息并发/重复调用
+ * 共享同一次开话题 — 防飞书重投事件开出多个话题(含进程重启: uuid 走服务端
+ * 去重)。
*
- * 失败语义: API 失败或响应缺 message_id → null(没有可确认已发出的开场白);
- * 响应有 message_id 但缺 thread_id → 用 message.get 补查话题 id, 查不到就
- * 撤回开场白再返回 null — 不让「回复都在里面」的开场白承诺落空。调用方在
- * null 时降级回群 lane 旧行为(引用回复 + chat_id 直发)。
+ * 失败语义: API 失败或响应缺 message_id → degraded(没有可确认已发出的开场白);
+ * 响应有 message_id 但缺 thread_id → 用 message.get 补查话题 id; 查不到就
+ * 撤回开场白 — 撤回成功 → degraded, 撤回失败(含业务错误码)→ orphaned。
+ * reply 超时/断线等不确定错误 → 同一 uuid 有界重试取回原消息; 仍无回执 →
+ * unconfirmed(不降级)。任何状态都不出现「开场白可见但回答进群主流」。
*/
-export function openThread(replyToMessageId: string): Promise<OpenThreadResult | null> {
+export function openThread(replyToMessageId: string): Promise<OpenThreadOutcome> {
const now = Date.now();
const cached = openThreadByTrigger.get(replyToMessageId);
if (cached && now - cached.ts <= OPEN_THREAD_DEDUP_TTL_MS) return cached.promise;
- const promise = doOpenThread(replyToMessageId);
+ const promise = doOpenThread(replyToMessageId).then((outcome) => {
+ // unconfirmed 不是稳定结论: 清掉缓存, 重投再用同一 uuid 取回原消息。
+ if (outcome.kind === 'unconfirmed') openThreadByTrigger.delete(replyToMessageId);
+ return outcome;
+ });
openThreadByTrigger.set(replyToMessageId, { ts: now, promise });
pruneOpenThreadDedup();
return promise;
}
-async function doOpenThread(replyToMessageId: string): Promise<OpenThreadResult | null> {
+/**
+ * 移除某触发消息的开话题结果缓存 — 只在「放弃本轮、期待重投重试」的路径
+ * 调用(连接换代丢弃时与入站认领释放配套)。不 evict 的话, 重投会复用旧连接
+ * 上的 degraded/orphaned 结果(旧客户端已 unbind, 补查/撤回必然失败), 而不是
+ * 用新客户端重试 API。孤儿提示失败的重试路径不 evict — 复用 orphaned 结果
+ * 重试提示正是设计意图。
+ */
+export function evictOpenThreadOutcome(replyToMessageId: string): void {
+ openThreadByTrigger.delete(replyToMessageId);
+}
+
+/**
+ * 用指定 client 撤回 bot 自己发的消息 — patch/替换失败路径把撤回 pin 到
+ * 触发账号: 中途换凭证时不得拿新账号的 client 删除旧账号的开场白。
+ */
+/** 飞书 REST 2xx 仍可能带非零业务码; SDK 对此不抛。缺省或 0 才算成功。 */
+function feishuBusinessRejectReason(res: { code?: number; msg?: string }): string | null {
+ if (res.code === undefined || res.code === 0) return null;
+ return res.msg ? `${res.msg} (code=${res.code})` : `code=${res.code}`;
+}
+
+export async function recallOwnMessageWith(
+ c: Lark.Client,
+ messageId: string,
+): Promise<boolean> {
const log = getLog();
try {
- const res = await ensureClient().im.v1.message.reply({
- path: { message_id: replyToMessageId },
- data: {
- content: JSON.stringify(buildMarkdownCardV2(transportMessages.streaming.randomThinking())),
- msg_type: 'interactive',
- reply_in_thread: true,
- // 服务端幂等键: 同一触发消息重复开话题(重投事件、进程重启后重放)时,
- // 飞书按 uuid 去重(1 小时内同 uuid 至多发一条, 重复调用返回原消息
- // id), 不会开出第二个话题。
- uuid: replyToMessageId,
- },
- });
- const messageId = res.data?.message_id ?? '';
- const threadId = res.data?.thread_id ?? '';
- if (!messageId) {
- log.warn(
- '[feishu/outbound] openThread: no message_id in response — nothing provably sent',
- );
- return null;
+ const res = await c.im.v1.message.delete({ path: { message_id: messageId } });
+ const rejected = feishuBusinessRejectReason(res);
+ if (rejected) {
+ log.warn(`[feishu/outbound] recallOwnMessage rejected: ${rejected}`);
+ return false;
}
- if (threadId) return { messageId, threadId };
- // 部分成功: 开场白已发出但响应缺 thread_id — 补查消息详情恢复话题 id。
- const recovered = await tryFetchMessageThreadId(messageId);
- if (recovered) return { messageId, threadId: recovered };
- // 恢复不了: 撤回开场白再降级, 避免「回复都在里面」的开场白留在群里误导。
+ return true;
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`[feishu/outbound] recallOwnMessage failed: ${msg}`);
+ return false;
+ }
+}
+
+/**
+ * 撤回 bot 自己发的消息(孤儿开场白卡重试耗尽后的最后兜底)。返回是否成功;
+ * 失败只 log — 撤回成功用户看到干净群主流而不是永久「思考中」卡, 撤回失败
+ * 说明故障仍未恢复, 已无更进一步的兜底手段。
+ */
+export async function recallOwnMessage(messageId: string): Promise<boolean> {
+ return recallOwnMessageWith(ensureClient(), messageId);
+}
+
+/** reply 抛错是否「结果不确定」: 请求可能已在服务端落地, 不能立刻假定没发。 */
+function isUncertainOpenThreadError(err: unknown): boolean {
+ const name = err instanceof Error ? err.name : '';
+ const msg = err instanceof Error ? err.message : String(err);
+ const code =
+ err && typeof err === 'object' && 'code' in err ? String((err as { code?: unknown }).code) : '';
+ const hay = `${name} ${code} ${msg}`.toLowerCase();
+ return /timeout|timed?\s*out|etimedout|econnreset|econnrefused|econnaborted|enotfound|eai_again|epipe|socket hang up|network|fetch failed|aborted|und_err/.test(
+ hay,
+ );
+}
+
+async function replyOpenThread(
+ c: Lark.Client,
+ replyToMessageId: string,
+): Promise<{ messageId: string; threadId: string } | 'degraded' | 'unconfirmed'> {
+ const log = getLog();
+ const maxAttempts = 1 + OPEN_THREAD_UNCERTAIN_RETRIES;
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
try {
- await ensureClient().im.v1.message.delete({ path: { message_id: messageId } });
- log.warn(
- '[feishu/outbound] openThread: thread_id unrecoverable — opener recalled, fallback to group lane',
- );
+ const res = await c.im.v1.message.reply({
+ path: { message_id: replyToMessageId },
+ data: {
+ content: JSON.stringify(buildMarkdownCardV2(transportMessages.streaming.randomThinking())),
+ msg_type: 'interactive',
+ reply_in_thread: true,
+ // 服务端幂等键: 同一触发消息重复开话题(重投事件、进程重启后重放)时,
+ // 飞书按 uuid 去重(1 小时内同 uuid 至多发一条, 重复调用返回原消息
+ // id), 不会开出第二个话题。超时后用同一 uuid 重试即可取回原消息。
+ uuid: replyToMessageId,
+ },
+ });
+ const messageId = res.data?.message_id ?? '';
+ const threadId = res.data?.thread_id ?? '';
+ if (!messageId) {
+ log.warn(
+ '[feishu/outbound] openThread: no message_id in response — nothing provably sent',
+ );
+ return 'degraded';
+ }
+ return { messageId, threadId };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
- log.warn(
- `[feishu/outbound] openThread: thread_id unrecoverable, opener recall failed (non-fatal): ${msg}`,
- );
+ const uncertain = isUncertainOpenThreadError(err);
+ if (uncertain && attempt < maxAttempts) {
+ log.warn(
+ `[feishu/outbound] openThread reply uncertain (retry ${attempt}/${OPEN_THREAD_UNCERTAIN_RETRIES} with same uuid): ${msg}`,
+ );
+ continue;
+ }
+ if (uncertain) {
+ log.warn(
+ `[feishu/outbound] openThread reply unconfirmed after ${maxAttempts} attempts — not degrading: ${msg}`,
+ );
+ return 'unconfirmed';
+ }
+ log.warn(`[feishu/outbound] openThread failed (fallback to group lane): ${msg}`);
+ return 'degraded';
}
- return null;
+ }
+ return 'unconfirmed';
+}
+
+async function doOpenThread(replyToMessageId: string): Promise<OpenThreadOutcome> {
+ const log = getLog();
+ // 全程 pin 到触发时的 client: reply / message.get / message.delete 都用
+ // 同一个实例。中途换账号(unbindClient + bindClient 新凭证)时, 补查与
+ // 撤回仍走创建开场白的那条连接 — 不会经新账号的 client 操作旧消息。
+ let c: Lark.Client;
+ try {
+ c = ensureClient();
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.warn(`[feishu/outbound] openThread failed (fallback to group lane): ${msg}`);
- return null;
+ return { kind: 'degraded' };
+ }
+ const replied = await replyOpenThread(c, replyToMessageId);
+ if (replied === 'degraded') return { kind: 'degraded' };
+ if (replied === 'unconfirmed') return { kind: 'unconfirmed' };
+ const { messageId, threadId } = replied;
+ if (threadId) return { kind: 'opened', messageId, threadId };
+ // 部分成功: 开场白已发出但响应缺 thread_id — 补查消息详情恢复话题 id。
+ const recovered = await tryFetchMessageThreadId(c, messageId);
+ if (recovered) return { kind: 'opened', messageId, threadId: recovered };
+ // 恢复不了: 撤回开场白再降级, 避免「思考中」的开场白卡留在群里误导。
+ try {
+ const del = await c.im.v1.message.delete({
+ path: { message_id: messageId },
+ });
+ // SDK 对业务错误不抛异常, 2xx 响应也可能带非零 code — 只有 code 缺省
+ // 或为 0 才算撤回成功, 否则开场白卡仍在群里, 降级会制造误导组合。
+ if (del.code !== undefined && del.code !== 0) {
+ log.error(
+ `[feishu/outbound] openThread: opener recall rejected (code=${del.code}) — opener orphaned: ${del.msg ?? ''}`,
+ );
+ return { kind: 'orphaned', openerMessageId: messageId };
+ }
+ log.warn(
+ '[feishu/outbound] openThread: thread_id unrecoverable — opener recalled, fallback to group lane',
+ );
+ return { kind: 'degraded' };
+ } catch (err) {
+ // 撤回也失败: 开场白卡孤立在话题里 — 宁可让调用方放弃本轮(回复开场白
+ // 说明失败), 也不能降级群 lane 制造「开场白可见 + 回答刷群主流」。
+ const msg = err instanceof Error ? err.message : String(err);
+ log.error(
+ `[feishu/outbound] openThread: thread_id unrecoverable and opener recall failed — opener orphaned: ${msg}`,
+ );
+ return { kind: 'orphaned', openerMessageId: messageId };
}
}
/** 用 message.get 补查开场白消息的 thread_id(部分成功恢复);失败返回 ''。 */
-async function tryFetchMessageThreadId(messageId: string): Promise<string> {
+async function tryFetchMessageThreadId(c: Lark.Client, messageId: string): Promise<string> {
const log = getLog();
try {
- const res = await ensureClient().im.v1.message.get({ path: { message_id: messageId } });
+ const res = await c.im.v1.message.get({ path: { message_id: messageId } });
return res.data?.items?.[0]?.thread_id ?? '';
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
@@ -387,7 +724,7 @@ export async function removeReaction(messageId: string, reactionId: string): Pro
// 键对不上会让 /ctr 锁永远清不掉。发往 lane 的卡在发送成功后把 messageId 登记
// 回发卡 lane, 回调时反查归一成同一条 lane;私聊卡(open_id)与改投 owner DM 的卡
// 不登记, 回调保持 open_id。飞书卡片回调有效期 30 天, 过期条目不会再有点击,
-// 按 31 天 TTL + 上限淘汰;unbindClient 随连接换代清空(与 laneAnchors 同口径)。
+// 按 31 天 TTL + 上限淘汰;unbindClient 清空(卡片回调不跨连接认领旧卡)。
const CARD_LANE_TTL_MS = 31 * 24 * 60 * 60 * 1000;
const CARD_LANE_MAX_ENTRIES = 512;
@@ -413,7 +750,8 @@ function pruneCardLanes(): void {
}
/** 发卡成功后在 lane 通道登记 card messageId → laneUserId;私聊发送不登记。 */
-function registerCardLane(userId: string, messageId: string): void {
+/** 登记交互卡的发卡 lane(按钮回调 resolveCardLane 反查用)。 */
+export function registerCardLane(userId: string, messageId: string): void {
if (!decodeLaneUserId(userId)) return;
cardLanes.set(messageId, { ts: Date.now(), lane: userId });
pruneCardLanes();
@@ -463,19 +801,27 @@ export async function updateInteractive(
spec: InteractiveCardSpec,
): Promise<void> {
const card = buildInteractiveCardV1(spec);
- await ensureClient().im.v1.message.patch({
+ const res = await ensureClient().im.v1.message.patch({
path: { message_id: messageId },
data: { content: JSON.stringify(card) },
});
+ const rejected = feishuBusinessRejectReason(res);
+ if (rejected) {
+ throw new Error(`updateInteractive rejected: ${rejected}`);
+ }
}
// ── raw card patch (used by streamingText for v2 markdown patching) ───────────
export async function patchCardRaw(messageId: string, cardJson: unknown): Promise<void> {
- await ensureClient().im.v1.message.patch({
+ const res = await ensureClient().im.v1.message.patch({
path: { message_id: messageId },
data: { content: JSON.stringify(cardJson) },
});
+ const rejected = feishuBusinessRejectReason(res);
+ if (rejected) {
+ throw new Error(`patchCardRaw rejected: ${rejected}`);
+ }
}
/**
diff --git a/packages/lizi-im/src/feishu/wsClient.ts b/packages/lizi-im/src/feishu/wsClient.ts
index 7f812e2eca..966042396d 100644
--- a/packages/lizi-im/src/feishu/wsClient.ts
+++ b/packages/lizi-im/src/feishu/wsClient.ts
@@ -30,6 +30,17 @@
* `g/{chatId}[/{threadId}]`, speaker = owner, record reply anchor,
* emit IMMessageEvent
*
+ * 入站统一门禁(所有 chat_type 生效):
+ * → 重推去重: 同一 (appId, message_id) 只处理一次(见 claimInboundMessage)
+ * → 连接换代门禁: 处理途中的 await(附件下载/开话题)之后复查
+ * isActiveConnection(generation, botAppId) — 断开/换账号的旧连接轮次
+ * 直接丢弃, 不 push 锚点、不 emit, 不会路由进新账号的 client/session
+ * → 群主流 @ 开话题(opened / degraded / orphaned / unconfirmed):
+ * opened → 新话题 lane; degraded → 降级群 lane 旧行为; orphaned →
+ * 回复开场白(落回话题)说明失败并放弃本轮, 不降级刷群主流;
+ * unconfirmed → 事件已 ACK, 定时再用同一 uuid 有界重试, 取回后
+ * 恢复 turn 或走 orphan 收口, 不立刻降级群主流
+ *
* card.action.trigger(_v1)
* → drop if sender not in whitelist
* → parse button value
@@ -56,6 +67,8 @@ import type { BotCredentials, FeishuConnectionStatus } from './internal-types.js
let client: Lark.WSClient | null = null;
let detector: ConflictDetector | null = null;
let currentBotAppId: string | null = null;
+/** 当前连接的 service(feishu/lark)— 账号边界含 service, 同名 appId 也不可串。 */
+let currentService: BotCredentials['service'] | null = null;
let currentStatus: FeishuConnectionStatus = 'idle';
let acceptingInbound = false;
let lifecycleGeneration = 0;
@@ -75,6 +88,612 @@ let botOpenId: string | null = null;
const STRANGER_NOTICE_COOLDOWN_MS = 60_000;
const strangerNoticeAt = new Map<string, number>();
+/**
+ * 开场白孤立(话题 id 不可恢复且撤回失败)时回复开场白说明失败 — per-opener
+ * 冷却(开场白消息 id → 上次提示 ts)防重投事件重复提示。回复挂在开场白下
+ * 自动落回话题, 不惊动群主流。
+ *
+ * 提示发送失败时: 释放入站认领(重推若来可重新处理)并**主动调度递增间隔的
+ * 延迟重试** — 飞书长连接对「处理 3s 内完成」的事件直接 ACK 不再重推, 只靠
+ * 释放认领等重推不可靠, 用户会永久看着「思考中」的开场白卡等不到说明。
+ * 每次重试前 gate 到触发时的 connection generation — 换代后旧账号的开场白
+ * 不会发进新账号的会话。重试由定时器执行, 不经过本函数的冷却(重推在冷却期
+ * 内到达会被拦截, 不会双发); 3 次重试(总窗口 ~2 分钟)全失败后放弃 —
+ * 再长的故障窗口里平台重推同样无效, 无限重试只会让定时器跨连接悬挂。
+ */
+const ORPHAN_NOTICE_COOLDOWN_MS = 60_000;
+const orphanNoticeAt = new Map<string, number>();
+
+/**
+ * 清凭证代次。clearOrphanRetriesForCredentialClear 只删 map 条目, 挡不住
+ * 已经 await 出去的 REST。代次在清凭证时递增, 发送前后比对: 过期续段不得
+ * 再 suspend/schedule, 否则同账号再登录会把登出前的 opener 重试/撤回复活。
+ */
+let orphanRetryEpoch = 0;
+
+/**
+ * 提示**成功送达**的 opener 集合。与 orphanNoticeAt 分离: 后者在发送前
+ * 就 set(表达「最近一次尝试」, 失败不回溯), 前者只在成功路径加入 —
+ * 送达是终态事实, 不随时间失效: 重试链用它判断「提示已由其它路径送达,
+ * 本链应收尾」, 挂起超 60s 的旧重试失败时同样成立。stop() 清空, 并有
+ * 容量上限(孤儿事件每次一个 opener, 进程内不会无界增长)。
+ */
+const ORPHAN_DELIVERED_MAX_ENTRIES = 200;
+const orphanNoticeDelivered = new Set<string>();
+
+function markNoticeDelivered(openerMessageId: string): void {
+ orphanNoticeDelivered.add(openerMessageId);
+ while (orphanNoticeDelivered.size > ORPHAN_DELIVERED_MAX_ENTRIES) {
+ const oldest = orphanNoticeDelivered.values().next().value;
+ if (typeof oldest !== 'string') break;
+ orphanNoticeDelivered.delete(oldest);
+ }
+}
+
+/** 重试间隔按尝试次数递增 — attempt 0 用首个间隔, 超出数组则放弃。 */
+const ORPHAN_NOTICE_RETRY_DELAYS_MS = [10_000, 30_000, 90_000] as const;
+
+interface PendingOrphanRetry {
+ timer: ReturnType<typeof setTimeout>;
+ botAppId: string;
+ service: BotCredentials['service'];
+ openerMessageId: string;
+ /** 触发消息 id — 重试成功时重新认领, 抑制冷却后的重投再次进入提示流程。 */
+ messageId: string;
+ /** 已尝试次数 — stop() 挂起后恢复时保持退避进度。 */
+ attempt: number;
+}
+
+const orphanNoticeRetries = new Map<string, PendingOrphanRetry>();
+
+/**
+ * stop() 时被挂起的排队重试(定时器已取消, 元数据保留)。同账号重连后由
+ * start() 重新入队 — 否则事件已被 ACK, 重试随 stop 消失, 用户会一直看到
+ * 「思考中」的开场白卡。跨账号不恢复(appId + service 双键, 见
+ * resumeOrphanRetriesFor 的过滤)。
+ */
+interface SuspendedOrphanRetry {
+ botAppId: string;
+ service: BotCredentials['service'];
+ openerMessageId: string;
+ messageId: string;
+ attempt: number;
+}
+const suspendedOrphanRetries: SuspendedOrphanRetry[] = [];
+
+/**
+ * 该 opener 的尝试预算天花板(opener → 最高 attempt, 只增不减, 跨链保持)。
+ * 重投失败路径原本会用 attempt 0 覆盖更先进的重试链 — 反复重连+重投会把
+ * 预算反复重置, 撤回兜底永远到不了; 天花板让任何新链都从既有进度续接。
+ */
+const ORPHAN_ATTEMPT_CEILING_MAX_ENTRIES = 200;
+const orphanAttemptCeiling = new Map<string, number>();
+
+function bumpOrphanAttemptCeiling(openerMessageId: string, attempt: number): number {
+ const ceiling = Math.max(orphanAttemptCeiling.get(openerMessageId) ?? 0, attempt);
+ orphanAttemptCeiling.set(openerMessageId, ceiling);
+ while (orphanAttemptCeiling.size > ORPHAN_ATTEMPT_CEILING_MAX_ENTRIES) {
+ const oldest = orphanAttemptCeiling.keys().next().value;
+ if (typeof oldest !== 'string') break;
+ orphanAttemptCeiling.delete(oldest);
+ }
+ return ceiling;
+}
+
+/** 挂起一个排队重试(按 opener 去重, 预算续接天花板)。 */
+function suspendOrphanRetry(entry: SuspendedOrphanRetry): void {
+ entry.attempt = bumpOrphanAttemptCeiling(entry.openerMessageId, entry.attempt);
+ for (let i = suspendedOrphanRetries.length - 1; i >= 0; i--) {
+ if (suspendedOrphanRetries[i]!.openerMessageId === entry.openerMessageId) {
+ suspendedOrphanRetries.splice(i, 1);
+ }
+ }
+ // 不设容量帽: 每条都是尚未终态化的孤儿收口链, 事件已 ACK。
+ // 静默 shift 最早一条会让重连后既不提示也不撤回, 用户永久看到「思考中」。
+ suspendedOrphanRetries.push(entry);
+}
+
+/**
+ * start() 连接就绪后调用: 匹配当前账号(appId + service)的挂起重试恢复
+ * 入队(保持退避进度); **不匹配的直接丢弃** — 换账号时旧账号遗留的重试
+ * 不能无限期等待账号再次出现(届时向早已过时的 opener 补发提示/撤回)。
+ */
+function resumeOrphanRetriesFor(botAppId: string, service: BotCredentials['service']): void {
+ for (let i = suspendedOrphanRetries.length - 1; i >= 0; i--) {
+ const entry = suspendedOrphanRetries[i]!;
+ suspendedOrphanRetries.splice(i, 1);
+ if (entry.botAppId !== botAppId || entry.service !== service) continue;
+ scheduleOrphanNoticeRetry(
+ entry.botAppId,
+ entry.service,
+ entry.openerMessageId,
+ entry.messageId,
+ entry.attempt,
+ );
+ }
+}
+
+/**
+ * 连接状态处置: 同一 bot 活跃 → false(照常执行); 已换成别的账号 → true
+ * (终止 — 旧账号的开场白不得经新 client 操作); 无连接(停止/重连中) →
+ * true 且挂起排队等重连(事件已 ACK, 终止会让提示永久消失)。
+ */
+function suspendOrDropOnConnectionChange(
+ botAppId: string,
+ service: BotCredentials['service'],
+ entry: SuspendedOrphanRetry,
+ context: string,
+): boolean {
+ if (isSameBotActive(botAppId, service)) return false;
+ const log = getLog();
+ const accountChanged =
+ currentBotAppId !== null && (currentBotAppId !== botAppId || currentService !== service);
+ if (accountChanged) {
+ log.info(`[feishu/wsClient] orphan opener ${context} skipped: account changed`);
+ return true;
+ }
+ suspendOrphanRetry(entry);
+ log.info(`[feishu/wsClient] orphan opener ${context} suspended for same-bot reconnect`);
+ return true;
+}
+
+/**
+ * openThread 回执不确定时的 ACK 后恢复链。三次即时 uuid 重试仍无回执时,
+ * 事件会在 3s 内被 ACK, 不能指望平台重投。这里按孤儿提示同一套间隔
+ * (10s/30s/90s) 再用同一 uuid 取回原消息: opened → 补发 turn;
+ * orphaned → 走孤儿提示收口; degraded → 确认无卡后降级群 lane 起 turn;
+ * 仍 unconfirmed → 下一档。stop 挂起、同账号 start 恢复。
+ */
+interface UnconfirmedOpenRetry {
+ timer?: ReturnType<typeof setTimeout>;
+ botAppId: string;
+ service: BotCredentials['service'];
+ messageId: string;
+ chatId: string;
+ senderOpenId: string;
+ text: string;
+ attachments: Awaited<ReturnType<typeof downloadAttachments>>['attachments'];
+ unsupported: ReturnType<typeof parseIncoming>['unsupported'];
+ raw: RawMessageEvent;
+ attempt: number;
+}
+
+const unconfirmedOpenRetries = new Map<string, UnconfirmedOpenRetry>();
+const suspendedUnconfirmedOpens: UnconfirmedOpenRetry[] = [];
+
+function clearUnconfirmedOpenRetries(): void {
+ for (const retry of unconfirmedOpenRetries.values()) {
+ if (retry.timer) clearTimeout(retry.timer);
+ }
+ unconfirmedOpenRetries.clear();
+ suspendedUnconfirmedOpens.length = 0;
+}
+
+function suspendUnconfirmedOpenRetry(entry: UnconfirmedOpenRetry): void {
+ if (entry.timer) {
+ clearTimeout(entry.timer);
+ entry.timer = undefined;
+ }
+ unconfirmedOpenRetries.delete(entry.messageId);
+ for (let i = suspendedUnconfirmedOpens.length - 1; i >= 0; i--) {
+ if (suspendedUnconfirmedOpens[i]!.messageId === entry.messageId) {
+ suspendedUnconfirmedOpens.splice(i, 1);
+ }
+ }
+ // 不设容量帽: 每条都是尚未终态化的轮次, 事件已 ACK、入站认领仍在。
+ // 静默 shift 最早一条会让重连后既不重派 turn, 也无法收口服务端思考卡。
+ suspendedUnconfirmedOpens.push(entry);
+}
+
+function resumeUnconfirmedOpenRetriesFor(
+ botAppId: string,
+ service: BotCredentials['service'],
+): void {
+ for (let i = suspendedUnconfirmedOpens.length - 1; i >= 0; i--) {
+ const entry = suspendedUnconfirmedOpens[i]!;
+ suspendedUnconfirmedOpens.splice(i, 1);
+ if (entry.botAppId !== botAppId || entry.service !== service) continue;
+ scheduleUnconfirmedOpenRetry(entry);
+ }
+}
+
+function scheduleUnconfirmedOpenRetry(entry: UnconfirmedOpenRetry): void {
+ const delay = ORPHAN_NOTICE_RETRY_DELAYS_MS[entry.attempt];
+ if (delay === undefined) {
+ getLog().error(
+ '[feishu/wsClient] unconfirmed openThread retries exhausted — holding for next reconnect',
+ );
+ // 事件已 ACK, 不能释放恢复链: 挂起并把 attempt 归零, 同账号重连后再走
+ // 一轮 10/30/90s。留着耗尽的 attempt 会让 resume 立刻再次耗尽。
+ suspendUnconfirmedOpenRetry({ ...entry, timer: undefined, attempt: 0 });
+ return;
+ }
+ const existing = unconfirmedOpenRetries.get(entry.messageId);
+ if (existing?.timer) clearTimeout(existing.timer);
+ const epoch = orphanRetryEpoch;
+ entry.timer = setTimeout(() => {
+ unconfirmedOpenRetries.delete(entry.messageId);
+ void retryUnconfirmedOpen(entry, epoch);
+ }, delay);
+ unconfirmedOpenRetries.set(entry.messageId, entry);
+}
+
+async function retryUnconfirmedOpen(
+ entry: UnconfirmedOpenRetry,
+ epoch: number,
+): Promise<void> {
+ const log = getLog();
+ if (!isSameBotActive(entry.botAppId, entry.service)) {
+ const accountChanged =
+ currentBotAppId !== null &&
+ (currentBotAppId !== entry.botAppId || currentService !== entry.service);
+ if (accountChanged) {
+ log.info('[feishu/wsClient] unconfirmed openThread retry skipped: account changed');
+ return;
+ }
+ suspendUnconfirmedOpenRetry({ ...entry, timer: undefined });
+ log.info('[feishu/wsClient] unconfirmed openThread retry suspended for same-bot reconnect');
+ return;
+ }
+ const opener = await outbound.openThread(entry.messageId);
+ if (orphanRetryEpoch !== epoch) return;
+ // saveAndConnect 的普通换账号只 stop/start, 不推进 orphanRetryEpoch —
+ // await 后必须再核当前 bot, 否则会把 A 的 opener/turn 写进 B 的 outbound。
+ if (!isSameBotActive(entry.botAppId, entry.service)) {
+ const accountChanged =
+ currentBotAppId !== null &&
+ (currentBotAppId !== entry.botAppId || currentService !== entry.service);
+ if (accountChanged) {
+ log.info('[feishu/wsClient] unconfirmed openThread dropped after await: account changed');
+ return;
+ }
+ suspendUnconfirmedOpenRetry({ ...entry, timer: undefined });
+ log.info('[feishu/wsClient] unconfirmed openThread suspended after await for same-bot reconnect');
+ return;
+ }
+ if (opener.kind === 'unconfirmed') {
+ scheduleUnconfirmedOpenRetry({ ...entry, timer: undefined, attempt: entry.attempt + 1 });
+ return;
+ }
+ if (opener.kind === 'orphaned') {
+ log.error(
+ `[feishu/wsClient] unconfirmed openThread recovered as orphaned opener=...${opener.openerMessageId.slice(-8)}`,
+ );
+ await sendOrphanOpenerNotice(
+ entry.botAppId,
+ entry.service,
+ entry.messageId,
+ opener.openerMessageId,
+ );
+ return;
+ }
+ let laneUserId: string;
+ let groupContextLane: { chatId: string; threadId: string } | undefined;
+ if (opener.kind === 'opened') {
+ laneUserId = encodeLaneUserId(entry.chatId, opener.threadId);
+ outbound.pushReplyAnchor(laneUserId, opener.messageId);
+ outbound.pushPatchableOpener(laneUserId, opener.messageId, entry.messageId);
+ groupContextLane = { chatId: entry.chatId, threadId: '' };
+ } else {
+ // degraded 只说明这次调用没确认发出, 不能否定先前 unconfirmed 请求已经
+ // 落地。当成确认无卡去群主流派 turn, 会一边留着思考卡一边刷屏。
+ log.info(
+ '[feishu/wsClient] unconfirmed openThread still unknown after degraded — keeping recovery chain',
+ );
+ scheduleUnconfirmedOpenRetry({ ...entry, timer: undefined, attempt: entry.attempt + 1 });
+ return;
+ }
+ log.info(
+ `[feishu/wsClient] unconfirmed openThread recovered as ${opener.kind} — emitting deferred turn`,
+ );
+ feishuEvents.emit('message', {
+ channelName: 'feishu',
+ senderId: laneUserId,
+ chatId: entry.chatId,
+ contextId: entry.botAppId,
+ messageId: entry.messageId,
+ text: entry.text,
+ speaker: { id: entry.senderOpenId, name: '', isOwner: true },
+ ...(groupContextLane ? { groupContextLane } : {}),
+ attachments: entry.attachments,
+ unsupported: entry.unsupported,
+ raw: entry.raw,
+ });
+}
+
+/** 测试注入口 — 清空挂起/排队重试。生产代码不要调用。 */
+export function resetOrphanRetriesForTest(): void {
+ for (const retry of orphanNoticeRetries.values()) clearTimeout(retry.timer);
+ orphanNoticeRetries.clear();
+ suspendedOrphanRetries.length = 0;
+ orphanAttemptCeiling.clear();
+ clearUnconfirmedOpenRetries();
+}
+
+/**
+ * 明确清除凭证/登出(clearAndDisconnect)时丢弃孤儿重试状态: 排队/挂起的
+ * 重试、预算与送达标记全部清空, 并递增 orphanRetryEpoch, 让已 await 出去
+ * 的 REST 续段在落定后放弃 — 之后重新保存相同 appId/service 不会恢复旧
+ * 重试向登出前的 opener 补发提示或撤回旧卡(那是 transport 重连才该有的
+ * 保留语义)。
+ */
+export function clearOrphanRetriesForCredentialClear(): void {
+ orphanRetryEpoch += 1;
+ for (const retry of orphanNoticeRetries.values()) clearTimeout(retry.timer);
+ orphanNoticeRetries.clear();
+ suspendedOrphanRetries.length = 0;
+ orphanAttemptCeiling.clear();
+ orphanNoticeDelivered.clear();
+ clearUnconfirmedOpenRetries();
+ // 注意: orphanNoticeInFlight **不清空** — 在途 REST 无法取消, 保留去重
+ // 记账让同凭证快速重登录后的重投共享旧请求(而不是并发第二条提示);
+ // 旧请求落定后条目自清理, 续段由 orphanRetryEpoch 放弃。
+}
+
+/** 该 opener 的提示是否已成功送达过(首发/重投/重试任一成功 — 终态)。 */
+function wasNoticeDelivered(openerMessageId: string): boolean {
+ return orphanNoticeDelivered.has(openerMessageId);
+}
+
+/**
+ * 重试/撤回的账号门: 换代后只要还是**同一个 bot**(appId + service 双键,
+ * Feishu/Lark 同名 appId 也不可串 — 凭证替换逻辑同样视 service 为账号
+ * 边界), 提示/撤回仍然安全 — 用当前 client 继续即可(同账号可操作自己发
+ * 的消息, 跨 stop 保留的重试因此不会死在 stale generation 上); 只有换成
+ * 别的账号或无连接时才失败, 旧账号的开场白不得经新账号的 client 操作。
+ */
+function isSameBotActive(botAppId: string, service: BotCredentials['service']): boolean {
+ return acceptingInbound && currentBotAppId === botAppId && currentService === service;
+}
+
+/**
+ * 该 opener 当前**正在执行**的提示发送(in-flight 去重)。重试的 timer 条目
+ * 在 setTimeout 回调里先删后发 — 仅凭 orphanNoticeRetries 看不到执行中的
+ * 发送; 这里单独记账, 任何路径的发送开始前先查: 冷却后的重投不会与执行
+ * 中的重试并发发出第二条提示。结果在所有等待者间共享 — 谁发起都只有一条。
+ */
+interface InFlightOrphanSend {
+ epoch: number;
+ promise: Promise<'delivered' | 'failed'>;
+}
+const orphanNoticeInFlight = new Map<string, InFlightOrphanSend>();
+
+/**
+ * 处理中的入站消息记账(key = `${appId}:${messageId}` → 所属 generation)。
+ * stop() 用它释放「认领了但所属连接即将失效、不会有产出」的消息认领 —
+ * 同账号重连后该消息的重投能被新连接处理(不被仍持有的认领压掉); 已处理
+ * 完的消息认领不受影响(重推抑制不变)。
+ */
+const inboundInFlight = new Map<string, { generation: number }>();
+
+/**
+ * 发送孤儿提示(单一 in-flight): 同一 opener 并发进入时共享同一次发送结果,
+ * 不会打出第二条。成功即标记送达(终态); 失败返回 'failed' 由调用方决定
+ * 释放认领/安排重试。
+ */
+function sendOrphanNoticeOnce(
+ openerMessageId: string,
+ epoch: number,
+): Promise<'delivered' | 'failed' | 'stale'> {
+ const inFlight = orphanNoticeInFlight.get(openerMessageId);
+ if (inFlight) {
+ // 清凭证前创建的 in-flight 不得被新代处理者当作本代结果推进 — 否则
+ // 旧请求失败时新 handler 的 epoch 校验通过, 登出前的重试复活。
+ if (inFlight.epoch !== epoch) return Promise.resolve('stale');
+ return inFlight.promise;
+ }
+ const log = getLog();
+ const attempt = (async (): Promise<'delivered' | 'failed'> => {
+ try {
+ await outbound.replyText(openerMessageId, transportMessages.group.threadOrphanNotice);
+ markNoticeDelivered(openerMessageId);
+ log.info('[feishu/wsClient] orphan opener notice delivered');
+ return 'delivered';
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`[feishu/wsClient] orphan opener notice send failed: ${msg}`);
+ return 'failed';
+ }
+ })();
+ // set 与 get 在同一同步块内完成 — 并发调用不会双双通过(JS 单线程)。
+ orphanNoticeInFlight.set(openerMessageId, { epoch, promise: attempt });
+ return attempt.finally(() => {
+ // 结果已共享给所有等待者后才清理; 幂等删除, 早到的 finally 不影响
+ // 已经持有 promise 引用的等待者。
+ orphanNoticeInFlight.delete(openerMessageId);
+ });
+}
+
+async function sendOrphanOpenerNotice(
+ botAppId: string,
+ service: BotCredentials['service'],
+ messageId: string,
+ openerMessageId: string,
+): Promise<void> {
+ const log = getLog();
+ // 终态守卫: 提示已送达过(执行中重试/重投任一成功)则不再发送 — 这次投递
+ // 不产出可见结果, 释放本次认领。
+ if (wasNoticeDelivered(openerMessageId)) {
+ releaseInboundClaim(botAppId, messageId);
+ return;
+ }
+ const last = orphanNoticeAt.get(openerMessageId) ?? 0;
+ if (Date.now() - last < ORPHAN_NOTICE_COOLDOWN_MS) {
+ // 冷却命中(重投场景): 这次投递不产出任何可见结果 — 释放本次认领, 否则
+ // 冷却期间的 claim 会卡满 10 分钟, 换代后新连接的重投被丢弃(stop 已清掉
+ // 定时重试), 用户的 @ 就丢了。
+ releaseInboundClaim(botAppId, messageId);
+ return;
+ }
+ orphanNoticeAt.set(openerMessageId, Date.now());
+ // in-flight 去重: 执行中的重试会与这里共享同一次发送 — 重投不并发打出
+ // 第二条提示; 结果为共享, 送达/失败按共享结果处理。
+ const epoch = orphanRetryEpoch;
+ const outcome = await sendOrphanNoticeOnce(openerMessageId, epoch);
+ if (epoch !== orphanRetryEpoch) {
+ // 清凭证发生在发送期间: 续段放弃 — 不再 schedule/suspend。
+ log.info('[feishu/wsClient] orphan opener notice stale after credential clear — dropping continuation');
+ return;
+ }
+ if (outcome === 'stale') {
+ // 加入的 in-flight 是清凭证前创建的: 本代不推进其失败结果, 但也不能
+ // 丢掉本代收口链(事件已 ACK)— 安排本代重试, 旧请求落定后的下一次
+ // 尝试会以当前代次重新发起。
+ log.info('[feishu/wsClient] orphan opener notice joined stale in-flight — scheduling own retry');
+ scheduleOrphanNoticeRetry(botAppId, service, openerMessageId, messageId, 0);
+ return;
+ }
+ if (outcome === 'delivered') {
+ // 送达: 重新认领触发消息(后续重投被入站去重拦下) + 清掉该 opener 的
+ // 挂起重试(重试绕过冷却, 不清会在稍后重复提示, 甚至重试耗尽时误撤回)。
+ claimInboundMessage(botAppId, messageId);
+ const pending = orphanNoticeRetries.get(openerMessageId);
+ if (pending) {
+ clearTimeout(pending.timer);
+ orphanNoticeRetries.delete(openerMessageId);
+ }
+ } else {
+ releaseInboundClaim(botAppId, messageId);
+ log.warn(
+ '[feishu/wsClient] orphan opener notice failed — inbound claim released',
+ );
+ // 发送失败发生在 stop 之后时, 连接已不在: 直接挂起排队(不创建定时器),
+ // 同账号重连后恢复; 已换账号则终止, 由新账号的重投走自己的处理。
+ const handled = suspendOrDropOnConnectionChange(
+ botAppId,
+ service,
+ { botAppId, service, openerMessageId, messageId, attempt: 0 },
+ 'first-send',
+ );
+ if (!handled) {
+ scheduleOrphanNoticeRetry(botAppId, service, openerMessageId, messageId, 0);
+ }
+ }
+}
+
+function scheduleOrphanNoticeRetry(
+ botAppId: string,
+ service: BotCredentials['service'],
+ openerMessageId: string,
+ messageId: string,
+ attempt: number,
+): void {
+ const log = getLog();
+ // 预算续接天花板: 共享失败后重投路径的 attempt 0 不得覆盖更先进的
+ // 重试链(否则反复重连+重投永远到不了撤回兜底)。
+ attempt = bumpOrphanAttemptCeiling(openerMessageId, attempt);
+ const delay = ORPHAN_NOTICE_RETRY_DELAYS_MS[attempt];
+ if (delay === undefined) {
+ // 提示已由其它路径(重投成功)送达时, 撤回会误删一张已经给出说明的卡 —
+ // 跳过撤回, 收尾重试链。
+ if (wasNoticeDelivered(openerMessageId)) {
+ log.info('[feishu/wsClient] orphan notice already delivered — skipping opener recall');
+ return;
+ }
+ // 账号门: 已换成别的账号时终止(旧账号的开场白卡不得经新账号的 client
+ // 操作); 无连接(停止/重连中)时挂起等重连恢复 — 终止会让事件已被 ACK
+ // 的撤回链永久消失; 同一 bot 重连则照常(见 isSameBotActive)。
+ if (
+ suspendOrDropOnConnectionChange(
+ botAppId,
+ service,
+ { botAppId, service, openerMessageId, messageId, attempt },
+ 'recall',
+ )
+ ) {
+ return;
+ }
+ // 重试耗尽: 最后兜底是撤回开场白卡 — 撤回成功用户看到干净群主流而不是
+ // 永久「思考中」卡; 撤回失败说明故障仍未恢复, 已无更进一步的兜底手段。
+ log.error(
+ '[feishu/wsClient] orphan opener notice retries exhausted — recalling opener card as last resort',
+ );
+ void outbound.recallOwnMessage(openerMessageId);
+ return;
+ }
+ const existing = orphanNoticeRetries.get(openerMessageId);
+ if (existing) clearTimeout(existing.timer);
+ const timer = setTimeout(() => {
+ orphanNoticeRetries.delete(openerMessageId);
+ void retryOrphanOpenerNotice(botAppId, service, openerMessageId, messageId, attempt);
+ }, delay);
+ orphanNoticeRetries.set(openerMessageId, {
+ timer,
+ botAppId,
+ service,
+ openerMessageId,
+ messageId,
+ attempt,
+ });
+}
+
+async function retryOrphanOpenerNotice(
+ botAppId: string,
+ service: BotCredentials['service'],
+ openerMessageId: string,
+ messageId: string,
+ attempt: number,
+): Promise<void> {
+ const log = getLog();
+ // 账号门(重连安全): 换代后仍是同一个 bot 就用当前 client 继续重试 —
+ // 跨 stop 保留的重试链不会死在 stale generation 上; 换成别的账号时
+ // 终止(旧账号的开场白不发进新账号的会话); 无连接时挂起等重连恢复 —
+ // 停止状态排队的重试若在重连前触发, 终止会让提示永久消失。
+ if (
+ suspendOrDropOnConnectionChange(
+ botAppId,
+ service,
+ { botAppId, service, openerMessageId, messageId, attempt },
+ 'retry',
+ )
+ ) {
+ return;
+ }
+ // 提示已由其它路径送达(执行中的重试与重投成功交错) — 放弃整条重试链。
+ if (wasNoticeDelivered(openerMessageId)) {
+ log.info('[feishu/wsClient] orphan notice already delivered — retry chain dropped');
+ return;
+ }
+ // in-flight 去重: 与冷却后的重投共享同一次发送 — 不会并发打出第二条提示;
+ // 若重投的发送已在进行, 这里等待它的结果而不是另发一条。
+ const epoch = orphanRetryEpoch;
+ const outcome = await sendOrphanNoticeOnce(openerMessageId, epoch);
+ if (epoch !== orphanRetryEpoch) {
+ log.info('[feishu/wsClient] orphan opener notice retry stale after credential clear — dropping continuation');
+ return;
+ }
+ if (outcome === 'stale') {
+ // 同上: 不推进旧请求结果, 但保留本代重试链。
+ log.info('[feishu/wsClient] orphan opener notice retry joined stale in-flight — scheduling own retry');
+ scheduleOrphanNoticeRetry(botAppId, service, openerMessageId, messageId, attempt);
+ return;
+ }
+ if (outcome === 'delivered') {
+ // 送达: 重新认领触发消息(抑制冷却后的重投再次进入提示流程)。
+ claimInboundMessage(botAppId, messageId);
+ log.info('[feishu/wsClient] orphan opener notice retry succeeded');
+ return;
+ }
+ // 失败发生在共享发送 await 期间时, 其它路径可能已成功送达 — 先查终态
+ // 标记再决定是否继续, 否则会重复提示甚至耗尽后误撤回已成功提示过的卡。
+ if (wasNoticeDelivered(openerMessageId)) {
+ log.info('[feishu/wsClient] orphan notice delivered during retry — retry chain dropped');
+ return;
+ }
+ log.warn(`[feishu/wsClient] orphan opener notice retry failed (attempt ${attempt})`);
+ // 发送失败可能发生在 stop 之后: 无连接时直接挂起(不创建定时器), 换账号
+ // 时终止 — 同账号重连后恢复。
+ const handled = suspendOrDropOnConnectionChange(
+ botAppId,
+ service,
+ { botAppId, service, openerMessageId, messageId, attempt: attempt + 1 },
+ 'retry-failed',
+ );
+ if (!handled) {
+ scheduleOrphanNoticeRetry(botAppId, service, openerMessageId, messageId, attempt + 1);
+ }
+}
+
/**
* 入站消息去重 —— 飞书事件是「至少送达一次」: 服务端等不到我们的 ACK 就会把
* 同一条消息**原样再推一遍**(同一个 message_id)。没有这道闸, 重推会被当成一条
@@ -115,6 +734,28 @@ function claimInboundMessage(appId: string, messageId: string): boolean {
return true;
}
+/**
+ * 释放某条消息的入站认领 —— 只在「认领了但本轮没有产出任何用户可见结果」的
+ * 放弃路径上调用(连接换代丢弃、孤儿开场白提示发送失败), 让重推能在新连接/
+ * 重试路径上重新处理。正常处理完(含已给出失败说明的放弃)绝不释放, 否则重推
+ * 会再次起 turn。
+ */
+function releaseInboundClaim(appId: string, messageId: string): void {
+ seenInboundMessages.delete(`${appId}:${messageId}`);
+}
+
+/**
+ * 放弃一条已认领但未产出结果的入站消息(连接换代丢弃路径): 释放去重认领 +
+ * evict 开话题结果缓存。只释放认领不 evict 的话, 重投会复用旧连接上的
+ * degraded/orphaned 缓存结果(旧客户端已 unbind, 补查/撤回必然失败)而不是
+ * 用新客户端重试 API。孤儿提示失败的重试不经过这里 — 复用 orphaned 结果
+ * 重试提示正是设计意图。
+ */
+function abandonInboundTurn(botAppId: string, messageId: string): void {
+ releaseInboundClaim(botAppId, messageId);
+ outbound.evictOpenThreadOutcome(messageId);
+}
+
/** 测试注入口 — 生产代码不要调用(生产语义就是跨 stop/start 不清空)。 */
export function resetInboundDedupeForTest(): void {
seenInboundMessages.clear();
@@ -348,6 +989,7 @@ export async function start(
const startedGeneration = ++lifecycleGeneration;
acceptingInbound = true;
currentBotAppId = creds.appId;
+ currentService = creds.service;
setStatus('testing');
const startDetector = new ConflictDetector({
@@ -385,7 +1027,14 @@ export async function start(
const eventDispatcher = new Lark.EventDispatcher({}).register({
'im.message.receive_v1': async (data: unknown) => {
try {
- await handleIncomingMessage(creds.appId, data as RawMessageEvent);
+ // 传入本代 connection 的 generation — 处理途中有 await(附件下载/
+ // 开话题), 恢复执行时必须复查门禁, 防止旧连接的轮次漏进新连接。
+ await handleIncomingMessage(
+ creds.appId,
+ creds.service,
+ startedGeneration,
+ data as RawMessageEvent,
+ );
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error('[feishu/wsClient] handleIncomingMessage threw:', msg);
@@ -419,6 +1068,10 @@ export async function start(
case 'connected':
if (currentStatus !== 'connected') setStatus('connected');
void fetchBotOpenId();
+ // 恢复本 bot 在 stop() 时被挂起的排队重试(同账号重连) — 事件已被
+ // ACK, 不恢复的话孤儿提示/撤回链随断连永久消失。
+ resumeOrphanRetriesFor(creds.appId, creds.service);
+ resumeUnconfirmedOpenRetriesFor(creds.appId, creds.service);
if (opts.announceLifecycle !== false) {
void announceLifecycle('online');
} else {
@@ -508,6 +1161,36 @@ export async function stop(opts: StopOptions = {}): Promise<void> {
}
botOpenId = null;
strangerNoticeAt.clear();
+ orphanNoticeAt.clear();
+ orphanNoticeDelivered.clear();
+ // 排队的重试挂起(不丢弃): 事件已被 ACK, 直接取消会让提示永远不再出现 —
+ // 元数据入 suspendedOrphanRetries, 同账号重连后由 start() 恢复入队。
+ for (const retry of orphanNoticeRetries.values()) {
+ clearTimeout(retry.timer);
+ suspendOrphanRetry({
+ botAppId: retry.botAppId,
+ service: retry.service,
+ openerMessageId: retry.openerMessageId,
+ messageId: retry.messageId,
+ attempt: retry.attempt,
+ });
+ }
+ orphanNoticeRetries.clear();
+ for (const retry of [...unconfirmedOpenRetries.values()]) {
+ suspendUnconfirmedOpenRetry(retry);
+ }
+ // 注意: orphanNoticeInFlight **不**清空 — in-flight 的 REST 请求在 stop()
+ // 时已捕获旧 client, close 不保证取消它; 保留去重记账, 同 bot 重连后的
+ // 重投仍会共享那次在途发送而不是并发第二条(条目随 promise 落定自清理)。
+ // 处理中的入站消息: 所属连接即将失效, 该消息不会再有产出 — 释放认领并
+ // evict 开话题缓存, 让同账号重连后的重投被新连接处理(而不是被仍持有的
+ // 认领压掉后 ACK 掉、且不再有重投保证); 已处理完的消息认领不动。
+ for (const key of inboundInFlight.keys()) {
+ seenInboundMessages.delete(key);
+ const sep = key.indexOf(':');
+ if (sep > 0) outbound.evictOpenThreadOutcome(key.slice(sep + 1));
+ }
+ inboundInFlight.clear();
outbound.unbindClient();
if (opts.clearOwnerBeforeIdle) {
pendingOfflineNotice = false;
@@ -515,6 +1198,7 @@ export async function stop(opts: StopOptions = {}): Promise<void> {
}
if (!opts.keepStatus) {
currentBotAppId = null;
+ currentService = null;
setStatus('idle');
}
}
@@ -613,9 +1297,14 @@ function mentionsSelf(
return mentions.some((m) => m.id?.open_id === selfOpenId);
}
-async function handleIncomingMessage(botAppId: string, data: RawMessageEvent): Promise<void> {
+async function handleIncomingMessage(
+ botAppId: string,
+ service: BotCredentials['service'],
+ generation: number,
+ data: RawMessageEvent,
+): Promise<void> {
const log = getLog();
- if (!acceptingInbound) {
+ if (!isActiveConnection(generation, botAppId)) {
log.info('[feishu/wsClient] drop inbound message while connection is stopping');
return;
}
@@ -651,9 +1340,42 @@ async function handleIncomingMessage(botAppId: string, data: RawMessageEvent): P
return;
}
+ inboundInFlight.set(`${botAppId}:${messageId}`, { generation });
+ try {
+ await processClaimedMessage(botAppId, service, generation, data, {
+ messageId,
+ chatId,
+ isGroup,
+ senderOpenId,
+ });
+ } finally {
+ // 自己的 entry 才清 — 重连后新连接可能已为同一条消息重新记账。
+ const entry = inboundInFlight.get(`${botAppId}:${messageId}`);
+ if (entry?.generation === generation) inboundInFlight.delete(`${botAppId}:${messageId}`);
+ }
+}
+
+async function processClaimedMessage(
+ botAppId: string,
+ service: BotCredentials['service'],
+ generation: number,
+ data: RawMessageEvent,
+ base: {
+ messageId: string;
+ chatId: string;
+ isGroup: boolean;
+ senderOpenId: string;
+ },
+): Promise<void> {
+ const log = getLog();
+ const { messageId, chatId, isGroup, senderOpenId } = base;
+ // 上游(handleIncomingMessage)已做过非空门, 这里保留可选链防御:
+ // 提取分支后 data.message 的窄化不跨函数传递。
+ const msgType = data.message?.message_type ?? '';
+ const rawContent = data.message?.content ?? '';
if (isGroup) {
// 没 @ 到本 bot 的群消息一律丢(bot open_id 未知时也丢 — 惰性失效)。
- if (!mentionsSelf(data.message.mentions, botOpenId)) return;
+ if (!mentionsSelf(data.message?.mentions, botOpenId)) return;
// 群里绝不 TOFU 认主(钉钉同款): 没有 owner 时群消息全丢。
if (!ownerGuard.firstAllowed()) {
log.info('[feishu/wsClient] drop group mention: no owner bound yet');
@@ -726,7 +1448,7 @@ async function handleIncomingMessage(botAppId: string, data: RawMessageEvent): P
// 群消息: 剥 @bot 占位符、其他 @ 转显示名。
const text =
- isGroup && data.message.mentions && botOpenId
+ isGroup && data.message?.mentions && botOpenId
? resolveMentionPlaceholders(parsed.text, data.message.mentions, botOpenId)
: parsed.text;
@@ -735,6 +1457,18 @@ async function handleIncomingMessage(botAppId: string, data: RawMessageEvent): P
return;
}
+ // 入站门禁复查: 附件下载等 await 期间连接可能已 stop()/换账号换代 — 不复查
+ // 会把旧连接的轮次推进新连接的编排状态(锚点污染/跨账号出站)。
+ if (!isActiveConnection(generation, botAppId)) {
+ // stop() 已释放认领(重连接管)时不得再碰 — 新连接可能已为同一条消息
+ // 重新认领; 记账还在(处理在 stop 之外被换代)→ 释放让重投可处理。
+ if (inboundInFlight.get(`${botAppId}:${messageId}`)?.generation === generation) {
+ abandonInboundTurn(botAppId, messageId);
+ }
+ log.info('[feishu/wsClient] drop inbound message: connection changed during processing');
+ return;
+ }
+
// 群 lane: senderId = g/{chatId}[/{threadId}], 出站按 lane 解码回群。
// 话题内触发直接进话题 lane(锚点=触发消息, 回复自动落回话题); 群主流
// 触发先以触发消息为根开话题再进新话题 lane(锚点=开场白消息) — 每话题
@@ -742,7 +1476,7 @@ async function handleIncomingMessage(botAppId: string, data: RawMessageEvent): P
let laneUserId: string | null = null;
let groupContextLane: { chatId: string; threadId: string } | undefined;
if (isGroup) {
- const incomingThreadId = data.message.thread_id;
+ const incomingThreadId = data.message?.thread_id;
if (incomingThreadId) {
laneUserId = encodeLaneUserId(chatId, incomingThreadId);
outbound.pushReplyAnchor(laneUserId, messageId);
@@ -753,16 +1487,57 @@ async function handleIncomingMessage(botAppId: string, data: RawMessageEvent): P
// 会话(用户感知: 不管在哪问, 工作目录都是绑定那个项目)。要跟接管会话
// 说话就在那个话题里说。
const opener = await outbound.openThread(messageId);
- if (opener) {
+ // 开话题是一次跨网络的 await — 期间用户可能断开/换账号: 复查门禁,
+ // 防止旧连接的锚点与事件漏进新连接(或已停机的编排状态)。
+ if (!isActiveConnection(generation, botAppId)) {
+ // 同上: stop() 已释放认领时不重复释放; 记账还在才 abandon(释放 +
+ // evict 开话题缓存, 让重推在新连接上用新客户端重试 API)。
+ if (inboundInFlight.get(`${botAppId}:${messageId}`)?.generation === generation) {
+ abandonInboundTurn(botAppId, messageId);
+ }
+ log.info('[feishu/wsClient] drop group message: connection changed while opening thread');
+ return;
+ }
+ if (opener.kind === 'opened') {
laneUserId = encodeLaneUserId(chatId, opener.threadId);
outbound.pushReplyAnchor(laneUserId, opener.messageId);
// 开场白卡是本轮流式卡: streamingText.start 认领后直接 patch,
- // 话题里不会多出一条占位消息。
- outbound.pushPatchableOpener(laneUserId, opener.messageId);
+ // 话题里不会多出一条占位消息。trigger 一并登记 — patch 失败撤回
+ // 开场白卡时锚点回拨到触发消息(reply_in_thread 落回话题)。
+ outbound.pushPatchableOpener(laneUserId, opener.messageId, messageId);
// 上下文取数 lane 与路由 lane 分离: 新话题是空的, 群历史前缀仍按
// 触发时所在的群主流拉取(「总结上面」等依赖上文的消息才能拿到
// 群主流历史), 由 host adapter 消费(IMMessageEvent.groupContextLane)。
groupContextLane = { chatId, threadId: '' };
+ } else if (opener.kind === 'orphaned') {
+ // 开场白卡已发出但话题 id 恢复失败、撤回也失败: 降级群 lane 会一边
+ // 留着「思考中」的开场白卡、一边把回答刷进群主流。不起 turn, 回复
+ // 开场白(落回话题)说明失败 — 宁可丢一轮, 不误导 + 不刷屏。
+ log.error(
+ `[feishu/wsClient] openThread orphaned opener=...${opener.openerMessageId.slice(-8)} — turn dropped with in-topic notice`,
+ );
+ await sendOrphanOpenerNotice(botAppId, service, messageId, opener.openerMessageId);
+ return;
+ } else if (opener.kind === 'unconfirmed') {
+ // 三次即时 uuid 重试仍无回执: 服务端可能已发出思考卡。事件会在 3s
+ // 内 ACK, 不能指望平台重投。不释放认领、不降级群主流, 改走 ACK 后
+ // 定时再用同一 uuid 取回 — 恢复 turn 或 orphan 收口。
+ log.error(
+ '[feishu/wsClient] openThread reply unconfirmed — scheduling delayed uuid recovery, not degrading',
+ );
+ scheduleUnconfirmedOpenRetry({
+ botAppId,
+ service,
+ messageId,
+ chatId,
+ senderOpenId,
+ text,
+ attachments,
+ unsupported,
+ raw: data,
+ attempt: 0,
+ });
+ return;
} else {
laneUserId = encodeLaneUserId(chatId, null);
outbound.pushReplyAnchor(laneUserId, messageId);